uatp.c revision 1.3 1 /* $NetBSD: uatp.c,v 1.3 2013/01/05 08:01:13 martin Exp $ */
2
3 /*-
4 * Copyright (c) 2011, 2012 Taylor R. Campbell
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29 /*
30 * uatp(4) - USB Apple Trackpad
31 *
32 * The uatp driver talks the protocol of the USB trackpads found in
33 * Apple laptops since 2005, including PowerBooks, iBooks, MacBooks,
34 * and MacBook Pros. Some of these also present generic USB HID mice
35 * on another USB report id, which the ums(4) driver can handle, but
36 * Apple's protocol gives more detailed sensor data that lets us detect
37 * multiple fingers to emulate multi-button mice and scroll wheels.
38 */
39
40 /*
42 * Protocol
43 *
44 * The device has a set of horizontal sensors, each being a column at a
45 * particular position on the x axis that tells you whether there is
46 * pressure anywhere on that column, and vertical sensors, each being a
47 * row at a particular position on the y axis that tells you whether
48 * there is pressure anywhere on that row.
49 *
50 * Whenever the device senses anything, it emits a readout of all of
51 * the sensors, in some model-dependent order. (For the order, see
52 * read_sample_1 and read_sample_2.) Each sensor datum is an unsigned
53 * eight-bit quantity representing some measure of pressure. (Of
54 * course, it really measures capacitance, not pressure, but we'll call
55 * it `pressure' here.)
56 */
57
58 /*
59 * Interpretation
60 *
61 * To interpret the finger's position on the trackpad, the driver
62 * computes a weighted average over all possible positions, weighted by
63 * the pressure at that position. The weighted average is computed in
64 * the dimensions of the screen, rather than the trackpad, in order to
65 * admit a finer resolution of positions than the trackpad grid.
66 *
67 * To update the finger's position smoothly on the trackpad, the driver
68 * computes a weighted average of the old raw position, the old
69 * smoothed position, and the new smoothed position. The weights are
70 * given by the old_raw_weight, old_smoothed_weight, and new_raw_weight
71 * sysctl knobs.
72 *
73 * Finally, to move the cursor, the driver takes the difference between
74 * the old and new positions and accelerates it according to some
75 * heuristic knobs that need to be reworked.
76 *
77 * Finally, there are some bells & whistles to detect tapping and to
78 * emulate a three-button mouse by leaving two or three fingers on the
79 * trackpad while pressing the button.
80 */
81
82 /*
83 * Future work
84 *
85 * With the raw sensor data available, we could implement fancier bells
86 * & whistles too, such as pinch-to-zoom. However, wsmouse supports
87 * only four-dimensional mice with buttons, and we already use two
88 * dimensions for mousing and two dimensions for scrolling, so there's
89 * no straightforward way to report zooming and other gestures to the
90 * operating system. Probably a better way to do this would be just to
91 * attach uhid(4) instead of uatp(4) and to read the raw sensors data
92 * yourself -- but that requires hairy mode switching for recent models
93 * (see geyser34_enable_raw_mode).
94 *
95 * XXX Rework the acceleration knobs.
96 * XXX Implement edge scrolling.
97 * XXX Fix sysctl setup; preserve knobs across suspend/resume.
98 * (uatp0 detaches and reattaches across suspend/resume, so as
99 * written, the sysctl tree is torn down and rebuilt, losing any
100 * state the user may have set.)
101 * XXX Refactor motion state so I can understand it again.
102 * Should make a struct uatp_motion for all that state.
103 * XXX Add hooks for ignoring trackpad input while typing.
104 */
105
106 /*
108 * Classifying devices
109 *
110 * I have only one MacBook to test this driver, but the driver should
111 * be applicable to almost every Apple laptop made since the beginning
112 * of 2005, so the driver reports lots of debugging output to help to
113 * classify devices. Boot with `boot -v' (verbose) and check the
114 * output of `dmesg | grep uatp' to answer the following questions:
115 *
116 * - What devices (vendor, product, class, subclass, proto, USB HID
117 * report dump) fail to attach when you think they should work?
118 * (vendor not apple, class not hid, proto not mouse)
119 *
120 * - What devices have an unknown product id?
121 * `unknown vendor/product id'
122 *
123 * - What devices have the wrong screen-to-trackpad ratios?
124 * `... x sensors, scaled by ... for ... points on screen'
125 * `... y sensors, scaled by ... for ... points on screen'
126 * You can tweak hw.uatp0.x_ratio and hw.uatp0.y_ratio to adjust
127 * this, up to a maximum of 384 for each value.
128 *
129 * - What devices have the wrong input size?
130 * `expected input size ... but got ... for Apple trackpad'
131 *
132 * - What devices give wrong-sized packets?
133 * `discarding ...-byte input'
134 *
135 * - What devices split packets in chunks?
136 * `partial packet: ... bytes'
137 *
138 * - What devices develop large sensor readouts?
139 * `large sensor readout: ...'
140 *
141 * - What devices have the wrong number of sensors? Are there parts of
142 * your trackpad that the system doesn't seem to notice? You can
143 * tweak hw.uatp0.x_sensors and hw.uatp0.y_sensors, up to a maximum
144 * of 32 for each value.
145 */
146
147 #include <sys/cdefs.h>
149 __KERNEL_RCSID(0, "$NetBSD: uatp.c,v 1.3 2013/01/05 08:01:13 martin Exp $");
150
151 #include <sys/atomic.h>
152 #include <sys/device.h>
153 #include <sys/errno.h>
154 #include <sys/ioctl.h>
155 #include <sys/param.h>
156 #include <sys/sysctl.h>
157 #include <sys/systm.h>
158 #include <sys/time.h>
159 #include <sys/types.h>
160 #include <sys/workqueue.h>
161
162 /* WTF? */
163 extern int hz;
164
165 /* Order is important here...sigh... */
166 #include <dev/usb/usb.h>
167 #include <dev/usb/usbdi.h>
168 #include <dev/usb/usbdi_util.h>
169 #include <dev/usb/usbdevs.h>
170 #include <dev/usb/uhidev.h>
171 #include <dev/usb/hid.h>
172 #include <dev/usb/usbhid.h>
173
174 #include <dev/wscons/wsconsio.h>
175 #include <dev/wscons/wsmousevar.h>
176
177 #define CHECK(condition, fail) do { \
178 if (! (condition)) { \
179 aprint_error_dev(uatp_dev(sc), "%s: check failed: %s\n",\
180 __func__, #condition); \
181 fail; \
182 } \
183 } while (0)
184
185 #define UATP_DEBUG_ATTACH (1 << 0)
187 #define UATP_DEBUG_MISC (1 << 1)
188 #define UATP_DEBUG_WSMOUSE (1 << 2)
189 #define UATP_DEBUG_IOCTL (1 << 3)
190 #define UATP_DEBUG_RESET (1 << 4)
191 #define UATP_DEBUG_INTR (1 << 5)
192 #define UATP_DEBUG_PARSE (1 << 6)
193 #define UATP_DEBUG_TAP (1 << 7)
194 #define UATP_DEBUG_EMUL_BUTTON (1 << 8)
195 #define UATP_DEBUG_ACCUMULATE (1 << 9)
196 #define UATP_DEBUG_STATUS (1 << 10)
197 #define UATP_DEBUG_SPURINTR (1 << 11)
198 #define UATP_DEBUG_MOVE (1 << 12)
199 #define UATP_DEBUG_ACCEL (1 << 13)
200 #define UATP_DEBUG_TRACK_DIST (1 << 14)
201 #define UATP_DEBUG_PALM (1 << 15)
202
203 #if UATP_DEBUG
204 # define DPRINTF(sc, flags, format) do { \
205 if ((flags) & (sc)->sc_debug_flags) { \
206 printf("%s: %s: ", device_xname(uatp_dev(sc)), __func__); \
207 printf format; \
208 } \
209 } while (0)
210 #else
211 # define DPRINTF(sc, flags, format) do {} while (0)
212 #endif
213
214 /* Maximum number of bytes in an incoming packet of sensor data. */
215 #define UATP_MAX_INPUT_SIZE 81
216
217 /* Maximum number of sensors in each dimension. */
218 #define UATP_MAX_X_SENSORS 32
219 #define UATP_MAX_Y_SENSORS 32
220 #define UATP_MAX_SENSORS 32
221 #define UATP_SENSORS (UATP_MAX_X_SENSORS + UATP_MAX_Y_SENSORS)
222
223 /* Maximum accumulated sensor value. */
224 #define UATP_MAX_ACC 0xff
225
226 /* Maximum screen dimension to sensor dimension ratios. */
227 #define UATP_MAX_X_RATIO 0x180
228 #define UATP_MAX_Y_RATIO 0x180
229 #define UATP_MAX_RATIO 0x180
230
231 /* Maximum weight for positions in motion calculation. */
232 #define UATP_MAX_WEIGHT 0x7f
233
234 /* Maximum possible trackpad position in a single dimension. */
235 #define UATP_MAX_POSITION (UATP_MAX_SENSORS * UATP_MAX_RATIO)
236
237 /* Bounds on acceleration. */
238 #define UATP_MAX_MOTION_MULTIPLIER 16
239
240 /* Status bits transmitted in the last byte of an input packet. */
241 #define UATP_STATUS_BUTTON (1 << 0) /* Button pressed */
242 #define UATP_STATUS_BASE (1 << 2) /* Base sensor data */
243 #define UATP_STATUS_POST_RESET (1 << 4) /* Post-reset */
244
245 /* Forward declarations */
247
248 struct uatp_softc; /* Device driver state. */
249 struct uatp_descriptor; /* Descriptor for a particular model. */
250 struct uatp_parameters; /* Parameters common to a set of models. */
251 struct uatp_knobs; /* User-settable configuration knobs. */
252 enum uatp_tap_state {
253 TAP_STATE_INITIAL,
254 TAP_STATE_TAPPING,
255 TAP_STATE_TAPPED,
256 TAP_STATE_DOUBLE_TAPPING,
257 TAP_STATE_DRAGGING_DOWN,
258 TAP_STATE_DRAGGING_UP,
259 TAP_STATE_TAPPING_IN_DRAG,
260 };
261
262 static const struct uatp_descriptor *find_uatp_descriptor
263 (const struct uhidev_attach_arg *);
264 static device_t uatp_dev(const struct uatp_softc *);
265 static uint8_t *uatp_x_sample(struct uatp_softc *);
266 static uint8_t *uatp_y_sample(struct uatp_softc *);
267 static int *uatp_x_acc(struct uatp_softc *);
268 static int *uatp_y_acc(struct uatp_softc *);
269 static void uatp_clear_position(struct uatp_softc *);
270 static unsigned int uatp_x_sensors(const struct uatp_softc *);
271 static unsigned int uatp_y_sensors(const struct uatp_softc *);
272 static unsigned int uatp_x_ratio(const struct uatp_softc *);
273 static unsigned int uatp_y_ratio(const struct uatp_softc *);
274 static unsigned int uatp_old_raw_weight(const struct uatp_softc *);
275 static unsigned int uatp_old_smoothed_weight(const struct uatp_softc *);
276 static unsigned int uatp_new_raw_weight(const struct uatp_softc *);
277 static int scale_motion(const struct uatp_softc *, int, int *,
278 const unsigned int *, const unsigned int *);
279 static int uatp_scale_motion(const struct uatp_softc *, int, int *);
280 static int uatp_scale_fast_motion(const struct uatp_softc *, int, int *);
281 static int uatp_match(device_t, cfdata_t, void *);
282 static void uatp_attach(device_t, device_t, void *);
283 static void uatp_setup_sysctl(struct uatp_softc *);
284 static bool uatp_setup_sysctl_knob(struct uatp_softc *, int *, const char *,
285 const char *);
286 static void uatp_childdet(device_t, device_t);
287 static int uatp_detach(device_t, int);
288 static int uatp_activate(device_t, enum devact);
289 static int uatp_enable(void *);
290 static void uatp_disable(void *);
291 static int uatp_ioctl(void *, unsigned long, void *, int, struct lwp *);
292 static void geyser34_enable_raw_mode(struct uatp_softc *);
293 static void geyser34_initialize(struct uatp_softc *);
294 static int geyser34_finalize(struct uatp_softc *);
295 static void geyser34_deferred_reset(struct uatp_softc *);
296 static void geyser34_reset_worker(struct work *, void *);
297 static void uatp_intr(struct uhidev *, void *, unsigned int);
298 static bool base_sample_softc_flag(const struct uatp_softc *, const uint8_t *);
299 static bool base_sample_input_flag(const struct uatp_softc *, const uint8_t *);
300 static void read_sample_1(uint8_t *, uint8_t *, const uint8_t *);
301 static void read_sample_2(uint8_t *, uint8_t *, const uint8_t *);
302 static void accumulate_sample_1(struct uatp_softc *);
303 static void accumulate_sample_2(struct uatp_softc *);
304 static void uatp_input(struct uatp_softc *, uint32_t, int, int, int, int);
305 static uint32_t uatp_tapped_buttons(struct uatp_softc *);
306 static bool interpret_input(struct uatp_softc *, int *, int *, int *, int *,
307 uint32_t *);
308 static unsigned int interpret_dimension(struct uatp_softc *, const int *,
309 unsigned int, unsigned int, unsigned int *, unsigned int *);
310 static void tap_initialize(struct uatp_softc *);
311 static void tap_finalize(struct uatp_softc *);
312 static void tap_enable(struct uatp_softc *);
313 static void tap_disable(struct uatp_softc *);
314 static void tap_transition(struct uatp_softc *, enum uatp_tap_state,
315 const struct timeval *, unsigned int, unsigned int);
316 static void tap_transition_initial(struct uatp_softc *);
317 static void tap_transition_tapping(struct uatp_softc *, const struct timeval *,
318 unsigned int);
319 static void tap_transition_double_tapping(struct uatp_softc *,
320 const struct timeval *, unsigned int);
321 static void tap_transition_dragging_down(struct uatp_softc *);
322 static void tap_transition_tapping_in_drag(struct uatp_softc *,
323 const struct timeval *, unsigned int);
324 static void tap_transition_tapped(struct uatp_softc *, const struct timeval *);
325 static void tap_transition_dragging_up(struct uatp_softc *);
326 static void tap_reset(struct uatp_softc *);
327 static void tap_reset_wait(struct uatp_softc *);
328 static void tap_touched(struct uatp_softc *, unsigned int);
329 static bool tap_released(struct uatp_softc *);
330 static void schedule_untap(struct uatp_softc *);
331 static void untap_callout(void *);
332 static uint32_t emulated_buttons(struct uatp_softc *, unsigned int);
333 static void update_position(struct uatp_softc *, unsigned int,
334 unsigned int, unsigned int, int *, int *, int *, int *);
335 static void move_mouse(struct uatp_softc *, unsigned int, unsigned int,
336 int *, int *);
337 static void scroll_wheel(struct uatp_softc *, unsigned int, unsigned int,
338 int *, int *);
339 static void move(struct uatp_softc *, const char *, unsigned int, unsigned int,
340 int *, int *, int *, int *, unsigned int *, unsigned int *, int *, int *);
341 static int smooth(struct uatp_softc *, unsigned int, unsigned int,
342 unsigned int);
343 static bool motion_below_threshold(struct uatp_softc *, unsigned int,
344 int, int);
345 static int accelerate(struct uatp_softc *, unsigned int, unsigned int,
346 unsigned int, unsigned int, bool, int *);
347
348 struct uatp_knobs {
350 /*
351 * Button emulation. What do we do when two or three fingers
352 * are on the trackpad when the user presses the button?
353 */
354 unsigned int two_finger_buttons;
355 unsigned int three_finger_buttons;
356
357 #if 0
358 /*
359 * Edge scrolling.
360 *
361 * XXX Implement this. What units should these be in?
362 */
363 unsigned int top_edge;
364 unsigned int bottom_edge;
365 unsigned int left_edge;
366 unsigned int right_edge;
367 #endif
368
369 /*
370 * Multifinger tracking. What do we do with multiple fingers?
371 * 0. Ignore them.
372 * 1. Try to interpret them as ordinary mousing.
373 * 2. Act like a two-dimensional scroll wheel.
374 */
375 unsigned int multifinger_track;
376
377 /*
378 * Sensor parameters.
379 */
380 unsigned int x_sensors;
381 unsigned int x_ratio;
382 unsigned int y_sensors;
383 unsigned int y_ratio;
384 unsigned int sensor_threshold;
385 unsigned int sensor_normalizer;
386 unsigned int palm_width;
387 unsigned int old_raw_weight;
388 unsigned int old_smoothed_weight;
389 unsigned int new_raw_weight;
390
391 /*
392 * Motion parameters.
393 *
394 * XXX There should be a more principled model of acceleration.
395 */
396 unsigned int motion_remainder;
397 unsigned int motion_threshold;
398 unsigned int motion_multiplier;
399 unsigned int motion_divisor;
400 unsigned int fast_motion_threshold;
401 unsigned int fast_motion_multiplier;
402 unsigned int fast_motion_divisor;
403 unsigned int fast_per_direction;
404 unsigned int motion_delay;
405
406 /*
407 * Tapping.
408 */
409 unsigned int tap_limit_msec;
410 unsigned int double_tap_limit_msec;
411 unsigned int one_finger_tap_buttons;
412 unsigned int two_finger_tap_buttons;
413 unsigned int three_finger_tap_buttons;
414 unsigned int tap_track_distance_limit;
415 };
416
417 static const struct uatp_knobs default_knobs = {
419 /*
420 * Button emulation. Fingers on the trackpad don't change it
421 * by default -- it's still the left button.
422 *
423 * XXX The left button should have a name.
424 */
425 .two_finger_buttons = 1,
426 .three_finger_buttons = 1,
427
428 #if 0
429 /*
430 * Edge scrolling. Off by default.
431 */
432 .top_edge = 0,
433 .bottom_edge = 0,
434 .left_edge = 0,
435 .right_edge = 0,
436 #endif
437
438 /*
439 * Multifinger tracking. Ignore by default.
440 */
441 .multifinger_track = 0,
442
443 /*
444 * Sensor parameters.
445 */
446 .x_sensors = 0, /* default for model */
447 .x_ratio = 0, /* default for model */
448 .y_sensors = 0, /* default for model */
449 .y_ratio = 0, /* default for model */
450 .sensor_threshold = 5,
451 .sensor_normalizer = 5,
452 .palm_width = 0, /* palm detection disabled */
453 .old_raw_weight = 0,
454 .old_smoothed_weight = 5,
455 .new_raw_weight = 1,
456
457 /*
458 * Motion parameters.
459 */
460 .motion_remainder = 1,
461 .motion_threshold = 0,
462 .motion_multiplier = 1,
463 .motion_divisor = 1,
464 .fast_motion_threshold = 10,
465 .fast_motion_multiplier = 3,
466 .fast_motion_divisor = 2,
467 .fast_per_direction = 0,
468 .motion_delay = 4,
469
470 /*
471 * Tapping. Disabled by default, with a reasonable time set
472 * nevertheless so that you can just set the buttons to enable
473 * it.
474 */
475 .tap_limit_msec = 100,
476 .double_tap_limit_msec = 200,
477 .one_finger_tap_buttons = 0,
478 .two_finger_tap_buttons = 0,
479 .three_finger_tap_buttons = 0,
480 .tap_track_distance_limit = 200,
481 };
482
483 struct uatp_softc {
485 struct uhidev sc_hdev; /* USB parent. */
486 device_t sc_wsmousedev; /* Attached wsmouse device. */
487 const struct uatp_parameters *sc_parameters;
488 struct uatp_knobs sc_knobs;
489 struct sysctllog *sc_log; /* Log for sysctl knobs. */
490 const struct sysctlnode *sc_node; /* Our sysctl node. */
491 unsigned int sc_input_size; /* Input packet size. */
492 uint8_t sc_input[UATP_MAX_INPUT_SIZE]; /* Buffer for a packet. */
493 unsigned int sc_input_index; /* Current index into sc_input. */
494 int sc_acc[UATP_SENSORS]; /* Accumulated sensor state. */
495 uint8_t sc_base[UATP_SENSORS]; /* Base sample. */
496 uint8_t sc_sample[UATP_SENSORS];/* Current sample. */
497 unsigned int sc_motion_timer; /* XXX describe; motion_delay */
498 int sc_x_raw; /* Raw horiz. mouse position. */
499 int sc_y_raw; /* Raw vert. mouse position. */
500 int sc_z_raw; /* Raw horiz. scroll position. */
501 int sc_w_raw; /* Raw vert. scroll position. */
502 int sc_x_smoothed; /* Smoothed horiz. mouse position. */
503 int sc_y_smoothed; /* Smoothed vert. mouse position. */
504 int sc_z_smoothed; /* Smoothed horiz. scroll position. */
505 int sc_w_smoothed; /* Smoothed vert. scroll position. */
506 int sc_x_remainder; /* Remainders from acceleration. */
507 int sc_y_remainder;
508 int sc_z_remainder;
509 int sc_w_remainder;
510 unsigned int sc_track_distance; /* Distance^2 finger has tracked,
511 * squared to avoid sqrt in kernel. */
512 uint32_t sc_status; /* Status flags: */
513 #define UATP_ENABLED (1 << 0) /* . Is the wsmouse enabled? */
514 #define UATP_DYING (1 << 1) /* . Have we been deactivated? */
515 #define UATP_VALID (1 << 2) /* . Do we have valid sensor data? */
516 struct workqueue *sc_reset_wq; /* Workqueue for resetting. */
517 struct work sc_reset_work; /* Work for said workqueue. */
518 unsigned int sc_reset_pending; /* True if a reset is pending. */
519
520 callout_t sc_untap_callout; /* Releases button after tap. */
521 kmutex_t sc_tap_mutex; /* Protects the following fields. */
522 kcondvar_t sc_tap_cv; /* Signalled by untap callout. */
523 enum uatp_tap_state sc_tap_state; /* Current tap state. */
524 unsigned int sc_tapping_fingers; /* No. fingers tapping. */
525 unsigned int sc_tapped_fingers; /* No. fingers of last tap. */
526 struct timeval sc_tap_timer; /* Timer for tap state transitions. */
527 uint32_t sc_buttons; /* Physical buttons pressed. */
528 uint32_t sc_all_buttons; /* Buttons pressed or tapped. */
529
530 #if UATP_DEBUG
531 uint32_t sc_debug_flags; /* Debugging output enabled. */
532 #endif
533 };
534
535 struct uatp_descriptor {
537 uint16_t vendor;
538 uint16_t product;
539 const char *description;
540 const struct uatp_parameters *parameters;
541 };
542
543 struct uatp_parameters {
544 unsigned int x_ratio; /* Screen width / trackpad width. */
545 unsigned int x_sensors; /* Number of horizontal sensors. */
546 unsigned int x_sensors_17; /* XXX Same, on a 17" laptop. */
547 unsigned int y_ratio; /* Screen height / trackpad height. */
548 unsigned int y_sensors; /* Number of vertical sensors. */
549 unsigned int input_size; /* Size in bytes of input packets. */
550
551 /* Device-specific initialization routine. May be null. */
552 void (*initialize)(struct uatp_softc *);
553
554 /* Device-specific finalization routine. May be null. May fail. */
555 int (*finalize)(struct uatp_softc *);
556
557 /* Tests whether this is a base sample. Second argument is
558 * input_size bytes long. */
559 bool (*base_sample)(const struct uatp_softc *, const uint8_t *);
560
561 /* Reads a sensor sample from an input packet. First argument
562 * is UATP_MAX_X_SENSORS bytes long; second, UATP_MAX_Y_SENSORS
563 * bytes; third, input_size bytes. */
564 void (*read_sample)(uint8_t *, uint8_t *, const uint8_t *);
565
566 /* Accumulates sensor state in sc->sc_acc. */
567 void (*accumulate)(struct uatp_softc *);
568
569 /* Called on spurious interrupts to reset. May be null. */
570 void (*reset)(struct uatp_softc *);
571 };
572
573 /* Known device parameters */
575
576 static const struct uatp_parameters fountain_parameters = {
577 .x_ratio = 64, .x_sensors = 16, .x_sensors_17 = 26,
578 .y_ratio = 43, .y_sensors = 16,
579 .input_size = 81,
580 .initialize = NULL,
581 .finalize = NULL,
582 .base_sample = base_sample_softc_flag,
583 .read_sample = read_sample_1,
584 .accumulate = accumulate_sample_1,
585 .reset = NULL,
586 };
587
588 static const struct uatp_parameters geyser_1_parameters = {
589 .x_ratio = 64, .x_sensors = 16, .x_sensors_17 = 26,
590 .y_ratio = 43, .y_sensors = 16,
591 .input_size = 81,
592 .initialize = NULL,
593 .finalize = NULL,
594 .base_sample = base_sample_softc_flag,
595 .read_sample = read_sample_1,
596 .accumulate = accumulate_sample_1,
597 .reset = NULL,
598 };
599
600 static const struct uatp_parameters geyser_2_parameters = {
601 .x_ratio = 64, .x_sensors = 15, .x_sensors_17 = 20,
602 .y_ratio = 43, .y_sensors = 9,
603 .input_size = 64,
604 .initialize = NULL,
605 .finalize = NULL,
606 .base_sample = base_sample_softc_flag,
607 .read_sample = read_sample_2,
608 .accumulate = accumulate_sample_1,
609 .reset = NULL,
610 };
611
612 /*
613 * The Geyser 3 and Geyser 4 share parameters. They also present
614 * generic USB HID mice on a different report id, so we have smaller
615 * packets by one byte (uhidev handles multiplexing report ids) and
616 * extra initialization work to switch the mode from generic USB HID
617 * mouse to Apple trackpad.
618 */
619
620 static const struct uatp_parameters geyser_3_4_parameters = {
621 .x_ratio = 64, .x_sensors = 20, /* XXX */ .x_sensors_17 = 0,
622 .y_ratio = 64, .y_sensors = 9,
623 .input_size = 63, /* 64, minus one for the report id. */
624 .initialize = geyser34_initialize,
625 .finalize = geyser34_finalize,
626 .base_sample = base_sample_input_flag,
627 .read_sample = read_sample_2,
628 .accumulate = accumulate_sample_2,
629 .reset = geyser34_deferred_reset,
630 };
631
632 /* Known device models */
634
635 #define APPLE_TRACKPAD(PRODUCT, DESCRIPTION, PARAMETERS) \
636 { \
637 .vendor = USB_VENDOR_APPLE, \
638 .product = (PRODUCT), \
639 .description = "Apple " DESCRIPTION " trackpad", \
640 .parameters = (& (PARAMETERS)), \
641 }
642
643 #define POWERBOOK_TRACKPAD(PRODUCT, PARAMETERS) \
644 APPLE_TRACKPAD(PRODUCT, "PowerBook/iBook", PARAMETERS)
645 #define MACBOOK_TRACKPAD(PRODUCT, PARAMETERS) \
646 APPLE_TRACKPAD(PRODUCT, "MacBook/MacBook Pro", PARAMETERS)
647
648 static const struct uatp_descriptor uatp_descriptors[] =
649 {
650 POWERBOOK_TRACKPAD(0x020e, fountain_parameters),
651 POWERBOOK_TRACKPAD(0x020f, fountain_parameters),
652 POWERBOOK_TRACKPAD(0x030a, fountain_parameters),
653
654 POWERBOOK_TRACKPAD(0x030b, geyser_1_parameters),
655
656 POWERBOOK_TRACKPAD(0x0214, geyser_2_parameters),
657 POWERBOOK_TRACKPAD(0x0215, geyser_2_parameters),
658 POWERBOOK_TRACKPAD(0x0216, geyser_2_parameters),
659
660 MACBOOK_TRACKPAD(0x0217, geyser_3_4_parameters), /* 3 */
661 MACBOOK_TRACKPAD(0x0218, geyser_3_4_parameters), /* 3 */
662 MACBOOK_TRACKPAD(0x0219, geyser_3_4_parameters), /* 3 */
663
664 MACBOOK_TRACKPAD(0x021a, geyser_3_4_parameters), /* 4 */
665 MACBOOK_TRACKPAD(0x021b, geyser_3_4_parameters), /* 4 */
666 MACBOOK_TRACKPAD(0x021c, geyser_3_4_parameters), /* 4 */
667
668 MACBOOK_TRACKPAD(0x0229, geyser_3_4_parameters), /* 4 */
669 MACBOOK_TRACKPAD(0x022a, geyser_3_4_parameters), /* 4 */
670 MACBOOK_TRACKPAD(0x022b, geyser_3_4_parameters), /* 4 */
671 };
672
673 #undef MACBOOK_TRACKPAD
674 #undef POWERBOOK_TRACKPAD
675 #undef APPLE_TRACKPAD
676
677 /* Miscellaneous utilities */
679
680 static const struct uatp_descriptor *
681 find_uatp_descriptor(const struct uhidev_attach_arg *uha)
682 {
683 unsigned int i;
684
685 for (i = 0; i < __arraycount(uatp_descriptors); i++)
686 if ((uha->uaa->vendor == uatp_descriptors[i].vendor) &&
687 (uha->uaa->product == uatp_descriptors[i].product))
688 return &uatp_descriptors[i];
689
690 return NULL;
691 }
692
693 static device_t
694 uatp_dev(const struct uatp_softc *sc)
695 {
696 return sc->sc_hdev.sc_dev;
697 }
698
699 static uint8_t *
700 uatp_x_sample(struct uatp_softc *sc)
701 {
702 return &sc->sc_sample[0];
703 }
704
705 static uint8_t *
706 uatp_y_sample(struct uatp_softc *sc)
707 {
708 return &sc->sc_sample[UATP_MAX_X_SENSORS];
709 }
710
711 static int *
712 uatp_x_acc(struct uatp_softc *sc)
713 {
714 return &sc->sc_acc[0];
715 }
716
717 static int *
718 uatp_y_acc(struct uatp_softc *sc)
719 {
720 return &sc->sc_acc[UATP_MAX_X_SENSORS];
721 }
722
723 static void
724 uatp_clear_position(struct uatp_softc *sc)
725 {
726 memset(sc->sc_acc, 0, sizeof(sc->sc_acc));
727 sc->sc_motion_timer = 0;
728 sc->sc_x_raw = sc->sc_x_smoothed = -1;
729 sc->sc_y_raw = sc->sc_y_smoothed = -1;
730 sc->sc_z_raw = sc->sc_z_smoothed = -1;
731 sc->sc_w_raw = sc->sc_w_smoothed = -1;
732 sc->sc_x_remainder = 0;
733 sc->sc_y_remainder = 0;
734 sc->sc_z_remainder = 0;
735 sc->sc_w_remainder = 0;
736 sc->sc_track_distance = 0;
737 }
738
739 static unsigned int
741 uatp_x_sensors(const struct uatp_softc *sc)
742 {
743 if ((0 < sc->sc_knobs.x_sensors) &&
744 (sc->sc_knobs.x_sensors <= UATP_MAX_X_SENSORS))
745 return sc->sc_knobs.x_sensors;
746 else
747 return sc->sc_parameters->x_sensors;
748 }
749
750 static unsigned int
751 uatp_y_sensors(const struct uatp_softc *sc)
752 {
753 if ((0 < sc->sc_knobs.y_sensors) &&
754 (sc->sc_knobs.y_sensors <= UATP_MAX_Y_SENSORS))
755 return sc->sc_knobs.y_sensors;
756 else
757 return sc->sc_parameters->y_sensors;
758 }
759
760 static unsigned int
761 uatp_x_ratio(const struct uatp_softc *sc)
762 {
763 /* XXX Reject bogus values in sysctl. */
764 if ((0 < sc->sc_knobs.x_ratio) &&
765 (sc->sc_knobs.x_ratio <= UATP_MAX_X_RATIO))
766 return sc->sc_knobs.x_ratio;
767 else
768 return sc->sc_parameters->x_ratio;
769 }
770
771 static unsigned int
772 uatp_y_ratio(const struct uatp_softc *sc)
773 {
774 /* XXX Reject bogus values in sysctl. */
775 if ((0 < sc->sc_knobs.y_ratio) &&
776 (sc->sc_knobs.y_ratio <= UATP_MAX_Y_RATIO))
777 return sc->sc_knobs.y_ratio;
778 else
779 return sc->sc_parameters->y_ratio;
780 }
781
782 static unsigned int
784 uatp_old_raw_weight(const struct uatp_softc *sc)
785 {
786 /* XXX Reject bogus values in sysctl. */
787 if (sc->sc_knobs.old_raw_weight <= UATP_MAX_WEIGHT)
788 return sc->sc_knobs.old_raw_weight;
789 else
790 return 0;
791 }
792
793 static unsigned int
794 uatp_old_smoothed_weight(const struct uatp_softc *sc)
795 {
796 /* XXX Reject bogus values in sysctl. */
797 if (sc->sc_knobs.old_smoothed_weight <= UATP_MAX_WEIGHT)
798 return sc->sc_knobs.old_smoothed_weight;
799 else
800 return 0;
801 }
802
803 static unsigned int
804 uatp_new_raw_weight(const struct uatp_softc *sc)
805 {
806 /* XXX Reject bogus values in sysctl. */
807 if ((0 < sc->sc_knobs.new_raw_weight) &&
808 (sc->sc_knobs.new_raw_weight <= UATP_MAX_WEIGHT))
809 return sc->sc_knobs.new_raw_weight;
810 else
811 return 1;
812 }
813
814 static int
816 scale_motion(const struct uatp_softc *sc, int delta, int *remainder,
817 const unsigned int *multiplier, const unsigned int *divisor)
818 {
819 int product;
820
821 /* XXX Limit the divisor? */
822 if (((*multiplier) == 0) ||
823 ((*multiplier) > UATP_MAX_MOTION_MULTIPLIER) ||
824 ((*divisor) == 0))
825 DPRINTF(sc, UATP_DEBUG_ACCEL,
826 ("bad knobs; %d (+ %d) --> %d, rem 0\n",
827 delta, *remainder, (delta + (*remainder))));
828 else
829 DPRINTF(sc, UATP_DEBUG_ACCEL,
830 ("scale %d (+ %d) by %u/%u --> %d, rem %d\n",
831 delta, *remainder,
832 (*multiplier), (*divisor),
833 (((delta + (*remainder)) * ((int) (*multiplier)))
834 / ((int) (*divisor))),
835 (((delta + (*remainder)) * ((int) (*multiplier)))
836 % ((int) (*divisor)))));
837
838 if (sc->sc_knobs.motion_remainder)
839 delta += *remainder;
840 *remainder = 0;
841
842 if (((*multiplier) == 0) ||
843 ((*multiplier) > UATP_MAX_MOTION_MULTIPLIER) ||
844 ((*divisor) == 0))
845 return delta;
846
847 product = (delta * ((int) (*multiplier)));
848 *remainder = (product % ((int) (*divisor)));
849 return (product / ((int) (*divisor)));
850 }
851
852 static int
853 uatp_scale_motion(const struct uatp_softc *sc, int delta, int *remainder)
854 {
855 return scale_motion(sc, delta, remainder,
856 &sc->sc_knobs.motion_multiplier,
857 &sc->sc_knobs.motion_divisor);
858 }
859
860 static int
861 uatp_scale_fast_motion(const struct uatp_softc *sc, int delta, int *remainder)
862 {
863 return scale_motion(sc, delta, remainder,
864 &sc->sc_knobs.fast_motion_multiplier,
865 &sc->sc_knobs.fast_motion_divisor);
866 }
867
868 /* Driver goop */
870
871 CFATTACH_DECL2_NEW(uatp, sizeof(struct uatp_softc), uatp_match, uatp_attach,
872 uatp_detach, uatp_activate, NULL, uatp_childdet);
873
874 static const struct wsmouse_accessops uatp_accessops = {
875 .enable = uatp_enable,
876 .disable = uatp_disable,
877 .ioctl = uatp_ioctl,
878 };
879
880 static int
881 uatp_match(device_t parent, cfdata_t match, void *aux)
882 {
883 const struct uhidev_attach_arg *uha = aux;
884 void *report_descriptor;
885 int report_size, input_size;
886 const struct uatp_descriptor *uatp_descriptor;
887
888 aprint_debug("%s: vendor 0x%04x, product 0x%04x\n", __func__,
889 (unsigned int)uha->uaa->vendor,
890 (unsigned int)uha->uaa->product);
891 aprint_debug("%s: class 0x%04x, subclass 0x%04x, proto 0x%04x\n",
892 __func__,
893 (unsigned int)uha->uaa->class,
894 (unsigned int)uha->uaa->subclass,
895 (unsigned int)uha->uaa->proto);
896
897 uhidev_get_report_desc(uha->parent, &report_descriptor, &report_size);
898 input_size = hid_report_size(report_descriptor, report_size,
899 hid_input, uha->reportid);
900 aprint_debug("%s: reportid %d, input size %d\n", __func__,
901 (int)uha->reportid, input_size);
902
903 /*
904 * Keyboards, trackpads, and eject buttons share common vendor
905 * and product ids, but not protocols: only the trackpad
906 * reports a mouse protocol.
907 */
908 if (uha->uaa->proto != UIPROTO_MOUSE)
909 return UMATCH_NONE;
910
911 /* Check for a known vendor/product id. */
912 uatp_descriptor = find_uatp_descriptor(uha);
913 if (uatp_descriptor == NULL) {
914 aprint_debug("%s: unknown vendor/product id\n", __func__);
915 return UMATCH_NONE;
916 }
917
918 /* Check for the expected input size. */
919 if ((input_size < 0) ||
920 ((unsigned int)input_size !=
921 uatp_descriptor->parameters->input_size)) {
922 aprint_debug("%s: expected input size %u\n", __func__,
923 uatp_descriptor->parameters->input_size);
924 return UMATCH_NONE;
925 }
926
927 return UMATCH_VENDOR_PRODUCT_CONF_IFACE;
928 }
929
930 static void
932 uatp_attach(device_t parent, device_t self, void *aux)
933 {
934 struct uatp_softc *sc = device_private(self);
935 const struct uhidev_attach_arg *uha = aux;
936 const struct uatp_descriptor *uatp_descriptor;
937 void *report_descriptor;
938 int report_size, input_size;
939 struct wsmousedev_attach_args a;
940
941 /* Set up uhidev state. (Why doesn't uhidev do most of this?) */
942 sc->sc_hdev.sc_dev = self;
943 sc->sc_hdev.sc_intr = uatp_intr;
944 sc->sc_hdev.sc_parent = uha->parent;
945 sc->sc_hdev.sc_report_id = uha->reportid;
946
947 /* Identify ourselves to dmesg. */
948 uatp_descriptor = find_uatp_descriptor(uha);
949 KASSERT(uatp_descriptor != NULL);
950 aprint_normal(": %s\n", uatp_descriptor->description);
951 aprint_naive(": %s\n", uatp_descriptor->description);
952 aprint_verbose_dev(self,
953 "vendor 0x%04x, product 0x%04x, report id %d\n",
954 (unsigned int)uha->uaa->vendor, (unsigned int)uha->uaa->product,
955 (int)uha->reportid);
956
957 uhidev_get_report_desc(uha->parent, &report_descriptor, &report_size);
958 input_size = hid_report_size(report_descriptor, report_size, hid_input,
959 uha->reportid);
960 KASSERT(0 < input_size);
961 sc->sc_input_size = input_size;
962
963 /* Initialize model-specific parameters. */
964 sc->sc_parameters = uatp_descriptor->parameters;
965 KASSERT(sc->sc_parameters->input_size == input_size);
966 KASSERT(sc->sc_parameters->x_sensors <= UATP_MAX_X_SENSORS);
967 KASSERT(sc->sc_parameters->x_ratio <= UATP_MAX_X_RATIO);
968 KASSERT(sc->sc_parameters->y_sensors <= UATP_MAX_Y_SENSORS);
969 KASSERT(sc->sc_parameters->y_ratio <= UATP_MAX_Y_RATIO);
970 aprint_verbose_dev(self,
971 "%u x sensors, scaled by %u for %u points on screen\n",
972 sc->sc_parameters->x_sensors, sc->sc_parameters->x_ratio,
973 sc->sc_parameters->x_sensors * sc->sc_parameters->x_ratio);
974 aprint_verbose_dev(self,
975 "%u y sensors, scaled by %u for %u points on screen\n",
976 sc->sc_parameters->y_sensors, sc->sc_parameters->y_ratio,
977 sc->sc_parameters->y_sensors * sc->sc_parameters->y_ratio);
978 if (sc->sc_parameters->initialize)
979 sc->sc_parameters->initialize(sc);
980
981 /* Register with pmf. Nothing special for suspend/resume. */
982 if (!pmf_device_register(self, NULL, NULL))
983 aprint_error_dev(self, "couldn't establish power handler\n");
984
985 /* Initialize knobs and create sysctl subtree to tweak them. */
986 sc->sc_knobs = default_knobs;
987 uatp_setup_sysctl(sc);
988
989 /* Initialize tapping. */
990 tap_initialize(sc);
991
992 /* Attach wsmouse. */
993 a.accessops = &uatp_accessops;
994 a.accesscookie = sc;
995 sc->sc_wsmousedev = config_found(self, &a, wsmousedevprint);
996 }
997
998 /* Sysctl setup */
1000
1001 static void
1002 uatp_setup_sysctl(struct uatp_softc *sc)
1003 {
1004 int error;
1005
1006 error = sysctl_createv(&sc->sc_log, 0, NULL, NULL, CTLFLAG_PERMANENT,
1007 CTLTYPE_NODE, "hw", NULL,
1008 NULL, 0, NULL, 0,
1009 CTL_HW, CTL_EOL);
1010 if (error != 0) {
1011 aprint_error_dev(uatp_dev(sc), "unable to set up sysctl: %d\n",
1012 error);
1013 return;
1014 }
1015
1016 error = sysctl_createv(&sc->sc_log, 0, NULL, &sc->sc_node, 0,
1017 CTLTYPE_NODE, device_xname(uatp_dev(sc)),
1018 SYSCTL_DESCR("uatp configuration knobs"),
1019 NULL, 0, NULL, 0,
1020 CTL_HW, CTL_CREATE, CTL_EOL);
1021 if (error != 0) {
1022 aprint_error_dev(uatp_dev(sc),
1023 "unable to set up sysctl tree hw.%s: %d\n",
1024 device_xname(uatp_dev(sc)), error);
1025 goto err;
1026 }
1027
1028 #if UATP_DEBUG
1029 if (!uatp_setup_sysctl_knob(sc, &sc->sc_debug_flags, "debug",
1030 "uatp(4) debug flags"))
1031 goto err;
1032 #endif
1033
1034 /*
1035 * Button emulation.
1036 */
1037 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.two_finger_buttons,
1038 "two_finger_buttons",
1039 "buttons to emulate with two fingers on trackpad"))
1040 goto err;
1041 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.three_finger_buttons,
1042 "three_finger_buttons",
1043 "buttons to emulate with three fingers on trackpad"))
1044 goto err;
1045
1046 #if 0
1047 /*
1048 * Edge scrolling.
1049 */
1050 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.top_edge, "top_edge",
1051 "width of top edge for edge scrolling"))
1052 goto err;
1053 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.bottom_edge,
1054 "bottom_edge", "width of bottom edge for edge scrolling"))
1055 goto err;
1056 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.left_edge, "left_edge",
1057 "width of left edge for edge scrolling"))
1058 goto err;
1059 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.right_edge, "right_edge",
1060 "width of right edge for edge scrolling"))
1061 goto err;
1062 #endif
1063
1064 /*
1066 * Multifinger tracking.
1067 */
1068 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.multifinger_track,
1069 "multifinger_track",
1070 "0 to ignore multiple fingers, 1 to reset, 2 to scroll"))
1071 goto err;
1072
1073 /*
1074 * Sensor parameters.
1075 */
1076 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.x_sensors, "x_sensors",
1077 "number of x sensors"))
1078 goto err;
1079 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.x_ratio, "x_ratio",
1080 "screen width to trackpad width ratio"))
1081 goto err;
1082 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.y_sensors, "y_sensors",
1083 "number of y sensors"))
1084 goto err;
1085 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.y_ratio, "y_ratio",
1086 "screen height to trackpad height ratio"))
1087 goto err;
1088 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.sensor_threshold,
1089 "sensor_threshold", "sensor threshold"))
1090 goto err;
1091 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.sensor_normalizer,
1092 "sensor_normalizer", "sensor normalizer"))
1093 goto err;
1094 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.palm_width,
1095 "palm_width", "lower bound on width/height of palm"))
1096 goto err;
1097 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.old_raw_weight,
1098 "old_raw_weight", "weight of old raw position"))
1099 goto err;
1100 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.old_smoothed_weight,
1101 "old_smoothed_weight", "weight of old smoothed position"))
1102 goto err;
1103 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.new_raw_weight,
1104 "new_raw_weight", "weight of new raw position"))
1105 goto err;
1106 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.motion_remainder,
1107 "motion_remainder", "remember motion division remainder"))
1108 goto err;
1109 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.motion_threshold,
1110 "motion_threshold", "threshold before finger moves cursor"))
1111 goto err;
1112 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.motion_multiplier,
1113 "motion_multiplier", "numerator of motion scale"))
1114 goto err;
1115 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.motion_divisor,
1116 "motion_divisor", "divisor of motion scale"))
1117 goto err;
1118 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.fast_motion_threshold,
1119 "fast_motion_threshold", "threshold before fast motion"))
1120 goto err;
1121 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.fast_motion_multiplier,
1122 "fast_motion_multiplier", "numerator of fast motion scale"))
1123 goto err;
1124 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.fast_motion_divisor,
1125 "fast_motion_divisor", "divisor of fast motion scale"))
1126 goto err;
1127 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.fast_per_direction,
1128 "fast_per_direction", "don't frobnitz the veeblefitzer!"))
1129 goto err;
1130 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.motion_delay,
1131 "motion_delay", "number of packets before motion kicks in"))
1132 goto err;
1133
1134 /*
1136 * Tapping.
1137 */
1138 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.tap_limit_msec,
1139 "tap_limit_msec", "milliseconds before a touch is not a tap"))
1140 goto err;
1141 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.double_tap_limit_msec,
1142 "double_tap_limit_msec",
1143 "milliseconds before a second tap keeps the button down"))
1144 goto err;
1145 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.one_finger_tap_buttons,
1146 "one_finger_tap_buttons", "buttons for one-finger taps"))
1147 goto err;
1148 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.two_finger_tap_buttons,
1149 "two_finger_tap_buttons", "buttons for two-finger taps"))
1150 goto err;
1151 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.three_finger_tap_buttons,
1152 "three_finger_tap_buttons", "buttons for three-finger taps"))
1153 goto err;
1154 if (!uatp_setup_sysctl_knob(sc, &sc->sc_knobs.tap_track_distance_limit,
1155 "tap_track_distance_limit",
1156 "maximum distance^2 of tracking during tap"))
1157 goto err;
1158
1159 return;
1160
1161 err:
1162 sysctl_teardown(&sc->sc_log);
1163 sc->sc_node = NULL;
1164 }
1165
1166 static bool
1167 uatp_setup_sysctl_knob(struct uatp_softc *sc, int *ptr, const char *name,
1168 const char *description)
1169 {
1170 int error;
1171
1172 error = sysctl_createv(&sc->sc_log, 0, NULL, NULL, CTLFLAG_READWRITE,
1173 CTLTYPE_INT, name, SYSCTL_DESCR(description),
1174 NULL, 0, ptr, 0,
1175 CTL_HW, sc->sc_node->sysctl_num, CTL_CREATE, CTL_EOL);
1176 if (error != 0) {
1177 aprint_error_dev(uatp_dev(sc),
1178 "unable to setup sysctl node hw.%s.%s: %d\n",
1179 device_xname(uatp_dev(sc)), name, error);
1180 return false;
1181 }
1182
1183 return true;
1184 }
1185
1186 /* More driver goop */
1188
1189 static void
1190 uatp_childdet(device_t self, device_t child)
1191 {
1192 struct uatp_softc *sc = device_private(self);
1193
1194 DPRINTF(sc, UATP_DEBUG_MISC, ("detaching child %s\n",
1195 device_xname(child)));
1196
1197 /* Our only child is the wsmouse device. */
1198 if (child == sc->sc_wsmousedev)
1199 sc->sc_wsmousedev = NULL;
1200 }
1201
1202 static int
1203 uatp_detach(device_t self, int flags)
1204 {
1205 struct uatp_softc *sc = device_private(self);
1206
1207 DPRINTF(sc, UATP_DEBUG_MISC, ("detaching with flags %d\n", flags));
1208
1209 if (sc->sc_status & UATP_ENABLED) {
1210 aprint_error_dev(uatp_dev(sc), "can't detach while enabled\n");
1211 return EBUSY;
1212 }
1213
1214 if (sc->sc_parameters->finalize) {
1215 int error = sc->sc_parameters->finalize(sc);
1216 if (error != 0)
1217 return error;
1218 }
1219
1220 pmf_device_deregister(self);
1221
1222 sysctl_teardown(&sc->sc_log);
1223 sc->sc_node = NULL;
1224
1225 tap_finalize(sc);
1226
1227 return config_detach_children(self, flags);
1228 }
1229
1230 static int
1231 uatp_activate(device_t self, enum devact act)
1232 {
1233 struct uatp_softc *sc = device_private(self);
1234
1235 DPRINTF(sc, UATP_DEBUG_MISC, ("act %d\n", (int)act));
1236
1237 if (act != DVACT_DEACTIVATE)
1238 return EOPNOTSUPP;
1239
1240 sc->sc_status |= UATP_DYING;
1241
1242 return 0;
1243 }
1244
1245 /* wsmouse routines */
1247
1248 static int
1249 uatp_enable(void *v)
1250 {
1251 struct uatp_softc *sc = v;
1252
1253 DPRINTF(sc, UATP_DEBUG_WSMOUSE, ("enabling wsmouse\n"));
1254
1255 /* Refuse to enable if we've been deactivated. */
1256 if (sc->sc_status & UATP_DYING) {
1257 DPRINTF(sc, UATP_DEBUG_WSMOUSE, ("busy dying\n"));
1258 return EIO;
1259 }
1260
1261 /* Refuse to enable if we already are enabled. */
1262 if (sc->sc_status & UATP_ENABLED) {
1263 DPRINTF(sc, UATP_DEBUG_WSMOUSE, ("already enabled\n"));
1264 return EBUSY;
1265 }
1266
1267 sc->sc_status |= UATP_ENABLED;
1268 sc->sc_status &=~ UATP_VALID;
1269 sc->sc_input_index = 0;
1270 tap_enable(sc);
1271 uatp_clear_position(sc);
1272
1273 DPRINTF(sc, UATP_DEBUG_MISC, ("uhidev_open(%p)\n", &sc->sc_hdev));
1274 return uhidev_open(&sc->sc_hdev);
1275 }
1276
1277 static void
1278 uatp_disable(void *v)
1279 {
1280 struct uatp_softc *sc = v;
1281
1282 DPRINTF(sc, UATP_DEBUG_WSMOUSE, ("disabling wsmouse\n"));
1283
1284 if (!(sc->sc_status & UATP_ENABLED)) {
1285 DPRINTF(sc, UATP_DEBUG_WSMOUSE, ("not enabled\n"));
1286 return;
1287 }
1288
1289 tap_disable(sc);
1290 sc->sc_status &=~ UATP_ENABLED;
1291
1292 DPRINTF(sc, UATP_DEBUG_MISC, ("uhidev_close(%p)\n", &sc->sc_hdev));
1293 uhidev_close(&sc->sc_hdev);
1294 }
1295
1296 static int
1297 uatp_ioctl(void *v, unsigned long cmd, void *data, int flag, struct lwp *p)
1298 {
1299
1300 DPRINTF((struct uatp_softc*)v, UATP_DEBUG_IOCTL,
1301 ("cmd %lx, data %p, flag %x, lwp %p\n", cmd, data, flag, p));
1302
1303 /* XXX Implement any relevant wsmouse(4) ioctls. */
1304 return EPASSTHROUGH;
1305 }
1306
1307 /*
1309 * The Geyser 3 and 4 models talk the generic USB HID mouse protocol by
1310 * default. This mode switch makes them give raw sensor data instead
1311 * so that we can implement tapping, two-finger scrolling, &c.
1312 */
1313
1314 #define GEYSER34_RAW_MODE 0x04
1315 #define GEYSER34_MODE_REPORT_ID 0
1316 #define GEYSER34_MODE_INTERFACE 0
1317 #define GEYSER34_MODE_PACKET_SIZE 8
1318
1319 static void
1320 geyser34_enable_raw_mode(struct uatp_softc *sc)
1321 {
1322 usbd_device_handle udev = sc->sc_hdev.sc_parent->sc_udev;
1323 usb_device_request_t req;
1324 usbd_status status;
1325 uint8_t report[GEYSER34_MODE_PACKET_SIZE];
1326
1327 req.bmRequestType = UT_READ_CLASS_INTERFACE;
1328 req.bRequest = UR_GET_REPORT;
1329 USETW2(req.wValue, UHID_FEATURE_REPORT, GEYSER34_MODE_REPORT_ID);
1330 USETW(req.wIndex, GEYSER34_MODE_INTERFACE);
1331 USETW(req.wLength, GEYSER34_MODE_PACKET_SIZE);
1332
1333 DPRINTF(sc, UATP_DEBUG_RESET, ("get feature report\n"));
1334 status = usbd_do_request(udev, &req, report);
1335 if (status != USBD_NORMAL_COMPLETION) {
1336 aprint_error_dev(uatp_dev(sc),
1337 "error reading feature report: %s\n", usbd_errstr(status));
1338 return;
1339 }
1340
1341 #if UATP_DEBUG
1343 if (sc->sc_debug_flags & UATP_DEBUG_RESET) {
1344 unsigned int i;
1345 DPRINTF(sc, UATP_DEBUG_RESET, ("old feature report:"));
1346 for (i = 0; i < GEYSER34_MODE_PACKET_SIZE; i++)
1347 printf(" %02x", (unsigned int)report[i]);
1348 printf("\n");
1349 /* Doing this twice is harmless here and lets this be
1350 * one ifdef. */
1351 report[0] = GEYSER34_RAW_MODE;
1352 DPRINTF(sc, UATP_DEBUG_RESET, ("new feature report:"));
1353 for (i = 0; i < GEYSER34_MODE_PACKET_SIZE; i++)
1354 printf(" %02x", (unsigned int)report[i]);
1355 printf("\n");
1356 }
1357 #endif
1358
1359 report[0] = GEYSER34_RAW_MODE;
1360
1361 req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1362 req.bRequest = UR_SET_REPORT;
1363 USETW2(req.wValue, UHID_FEATURE_REPORT, GEYSER34_MODE_REPORT_ID);
1364 USETW(req.wIndex, GEYSER34_MODE_INTERFACE);
1365 USETW(req.wLength, GEYSER34_MODE_PACKET_SIZE);
1366
1367 DPRINTF(sc, UATP_DEBUG_RESET, ("set feature report\n"));
1368 status = usbd_do_request(udev, &req, report);
1369 if (status != USBD_NORMAL_COMPLETION) {
1370 aprint_error_dev(uatp_dev(sc),
1371 "error writing feature report: %s\n", usbd_errstr(status));
1372 return;
1373 }
1374 }
1375
1376 /*
1378 * The Geyser 3 and 4 need to be reset periodically after we detect a
1379 * continual flow of spurious interrupts. We use a workqueue for this.
1380 * The flag avoids deferring a reset more than once before it has run,
1381 * or detaching the device while there is a deferred reset pending.
1382 */
1383
1384 static void
1385 geyser34_initialize(struct uatp_softc *sc)
1386 {
1387 DPRINTF(sc, UATP_DEBUG_MISC, ("initializing\n"));
1388
1389 geyser34_enable_raw_mode(sc);
1390 sc->sc_reset_pending = 0;
1391
1392 if (workqueue_create(&sc->sc_reset_wq, "uatprstq",
1393 geyser34_reset_worker, sc, PRI_NONE, IPL_USB, WQ_MPSAFE)
1394 != 0) {
1395 sc->sc_reset_wq = NULL;
1396 aprint_error_dev(uatp_dev(sc),
1397 "couldn't create Geyser 3/4 reset workqueue\n");
1398 }
1399 }
1400
1401 static int
1402 geyser34_finalize(struct uatp_softc *sc)
1403 {
1404 DPRINTF(sc, UATP_DEBUG_MISC, ("finalizing\n"));
1405
1406 /* Can't destroy the work queue if there is work pending. */
1407 if (sc->sc_reset_pending) {
1408 DPRINTF(sc, UATP_DEBUG_MISC, ("EBUSY -- reset pending\n"));
1409 return EBUSY;
1410 }
1411
1412 if (sc->sc_reset_wq != NULL)
1413 workqueue_destroy(sc->sc_reset_wq);
1414
1415 return 0;
1416 }
1417
1418 static void
1419 geyser34_deferred_reset(struct uatp_softc *sc)
1420 {
1421 DPRINTF(sc, UATP_DEBUG_RESET, ("deferring reset\n"));
1422
1423 /* Initialization can fail, so make sure we have a work queue. */
1424 if (sc->sc_reset_wq == NULL)
1425 DPRINTF(sc, UATP_DEBUG_RESET, ("no work queue\n"));
1426 /* Check for pending work. */
1427 else if (atomic_swap_uint(&sc->sc_reset_pending, 1))
1428 DPRINTF(sc, UATP_DEBUG_RESET, ("already pending\n"));
1429 /* No work was pending; flag is now set. */
1430 else
1431 workqueue_enqueue(sc->sc_reset_wq, &sc->sc_reset_work, NULL);
1432 }
1433
1434 static void
1435 geyser34_reset_worker(struct work *work, void *arg)
1436 {
1437 struct uatp_softc *sc = arg;
1438
1439 DPRINTF(sc, UATP_DEBUG_RESET, ("resetting\n"));
1440
1441 /* Reset by putting it into raw mode. Not sure why. */
1442 geyser34_enable_raw_mode(sc);
1443
1444 /* Mark the device ready for new work. */
1445 (void)atomic_swap_uint(&sc->sc_reset_pending, 0);
1446 }
1447
1448 /* Interrupt handler */
1450
1451 static void
1452 uatp_intr(struct uhidev *addr, void *ibuf, unsigned int len)
1453 {
1454 struct uatp_softc *sc = (struct uatp_softc *)addr;
1455 uint8_t *input;
1456 int dx, dy, dz, dw;
1457 uint32_t buttons;
1458
1459 DPRINTF(sc, UATP_DEBUG_INTR, ("softc %p, ibuf %p, len %u\n",
1460 addr, ibuf, len));
1461
1462 /*
1463 * Some devices break packets up into chunks, so we accumulate
1464 * input up to the expected packet length, or if it would
1465 * overflow, discard the whole packet and start over.
1466 */
1467 if (sc->sc_input_size < len) {
1468 aprint_error_dev(uatp_dev(sc),
1469 "discarding %u-byte input packet\n", len);
1470 sc->sc_input_index = 0;
1471 return;
1472 } else if (sc->sc_input_size < (sc->sc_input_index + len)) {
1473 aprint_error_dev(uatp_dev(sc), "discarding %u-byte input\n",
1474 (sc->sc_input_index + len));
1475 sc->sc_input_index = 0;
1476 return;
1477 }
1478
1479 #if UATP_DEBUG
1480 if (sc->sc_debug_flags & UATP_DEBUG_INTR) {
1481 unsigned int i;
1482 uint8_t *bytes = ibuf;
1483 DPRINTF(sc, UATP_DEBUG_INTR, ("raw"));
1484 for (i = 0; i < len; i++)
1485 printf(" %02x", (unsigned int)bytes[i]);
1486 printf("\n");
1487 }
1488 #endif
1489
1490 memcpy(&sc->sc_input[sc->sc_input_index], ibuf, len);
1491 sc->sc_input_index += len;
1492 if (sc->sc_input_index != sc->sc_input_size) {
1493 /* Wait until packet is complete. */
1494 aprint_verbose_dev(uatp_dev(sc), "partial packet: %u bytes\n",
1495 len);
1496 return;
1497 }
1498
1499 /* Clear the buffer and process the now complete packet. */
1500 sc->sc_input_index = 0;
1501 input = sc->sc_input;
1502
1503 /* The last byte's first bit is set iff the button is pressed.
1504 * XXX Left button should have a name. */
1505 buttons = ((input[sc->sc_input_size - 1] & UATP_STATUS_BUTTON)
1506 ? 1 : 0);
1507
1508 /* Read the sample. */
1509 memset(uatp_x_sample(sc), 0, UATP_MAX_X_SENSORS);
1510 memset(uatp_y_sample(sc), 0, UATP_MAX_Y_SENSORS);
1511 sc->sc_parameters->read_sample(uatp_x_sample(sc), uatp_y_sample(sc),
1512 input);
1513
1514 #if UATP_DEBUG
1516 if (sc->sc_debug_flags & UATP_DEBUG_INTR) {
1517 unsigned int i;
1518 DPRINTF(sc, UATP_DEBUG_INTR, ("x sensors"));
1519 for (i = 0; i < uatp_x_sensors(sc); i++)
1520 printf(" %02x", (unsigned int)uatp_x_sample(sc)[i]);
1521 printf("\n");
1522 DPRINTF(sc, UATP_DEBUG_INTR, ("y sensors"));
1523 for (i = 0; i < uatp_y_sensors(sc); i++)
1524 printf(" %02x", (unsigned int)uatp_y_sample(sc)[i]);
1525 printf("\n");
1526 } else if ((sc->sc_debug_flags & UATP_DEBUG_STATUS) &&
1527 (input[sc->sc_input_size - 1] &~
1528 (UATP_STATUS_BUTTON | UATP_STATUS_BASE |
1529 UATP_STATUS_POST_RESET)))
1530 DPRINTF(sc, UATP_DEBUG_STATUS, ("status byte: %02x\n",
1531 input[sc->sc_input_size - 1]));
1532 #endif
1533
1534 /*
1535 * If this is a base sample, initialize the state to interpret
1536 * subsequent samples relative to it, and stop here.
1537 */
1538 if (sc->sc_parameters->base_sample(sc, input)) {
1539 DPRINTF(sc, UATP_DEBUG_PARSE,
1540 ("base sample, buttons %"PRIx32"\n", buttons));
1541 /* XXX Should the valid bit ever be reset? */
1542 sc->sc_status |= UATP_VALID;
1543 uatp_clear_position(sc);
1544 memcpy(sc->sc_base, sc->sc_sample, sizeof(sc->sc_base));
1545 /* XXX Perform 17" size detection like Linux? */
1546 return;
1547 }
1548
1549 /* If not, accumulate the change in the sensors. */
1550 sc->sc_parameters->accumulate(sc);
1551
1552 #if UATP_DEBUG
1553 if (sc->sc_debug_flags & UATP_DEBUG_ACCUMULATE) {
1554 unsigned int i;
1555 DPRINTF(sc, UATP_DEBUG_ACCUMULATE, ("accumulated x state:"));
1556 for (i = 0; i < uatp_x_sensors(sc); i++)
1557 printf(" %02x", (unsigned int)uatp_x_acc(sc)[i]);
1558 printf("\n");
1559 DPRINTF(sc, UATP_DEBUG_ACCUMULATE, ("accumulated y state:"));
1560 for (i = 0; i < uatp_y_sensors(sc); i++)
1561 printf(" %02x", (unsigned int)uatp_y_acc(sc)[i]);
1562 printf("\n");
1563 }
1564 #endif
1565
1566 /* Compute the change in coordinates and buttons. */
1567 dx = dy = dz = dw = 0;
1568 if ((!interpret_input(sc, &dx, &dy, &dz, &dw, &buttons)) &&
1569 /* If there's no input because we're releasing a button,
1570 * then it's not spurious. XXX Mutex? */
1571 (sc->sc_buttons == 0)) {
1572 DPRINTF(sc, UATP_DEBUG_SPURINTR, ("spurious interrupt\n"));
1573 if (sc->sc_parameters->reset)
1574 sc->sc_parameters->reset(sc);
1575 return;
1576 }
1577
1578 /* Report to wsmouse. */
1579 DPRINTF(sc, UATP_DEBUG_INTR,
1580 ("buttons %"PRIx32", dx %d, dy %d, dz %d, dw %d\n",
1581 buttons, dx, dy, dz, dw));
1582 mutex_enter(&sc->sc_tap_mutex);
1583 uatp_input(sc, buttons, dx, dy, dz, dw);
1584 mutex_exit(&sc->sc_tap_mutex);
1585 }
1586
1587 /*
1589 * Different ways to discern the base sample initializing the state.
1590 * `base_sample_softc_flag' uses a state flag stored in the softc;
1591 * `base_sample_input_flag' checks a flag at the end of the input
1592 * packet.
1593 */
1594
1595 static bool
1596 base_sample_softc_flag(const struct uatp_softc *sc, const uint8_t *input)
1597 {
1598 return !(sc->sc_status & UATP_VALID);
1599 }
1600
1601 static bool
1602 base_sample_input_flag(const struct uatp_softc *sc, const uint8_t *input)
1603 {
1604 /* XXX Should we also check the valid flag? */
1605 return !!(input[sc->sc_input_size - 1] & UATP_STATUS_BASE);
1606 }
1607
1608 /*
1609 * Pick apart the horizontal sensors from the vertical sensors.
1610 * Different models interleave them in different orders.
1611 */
1612
1613 static void
1614 read_sample_1(uint8_t *x, uint8_t *y, const uint8_t *input)
1615 {
1616 unsigned int i;
1617
1618 for (i = 0; i < 8; i++) {
1619 x[i] = input[5 * i + 2];
1620 x[i + 8] = input[5 * i + 4];
1621 x[i + 16] = input[5 * i + 42];
1622 if (i < 2)
1623 x[i + 24] = input[5 * i + 44];
1624
1625 y[i] = input[5 * i + 1];
1626 y[i + 8] = input[5 * i + 3];
1627 }
1628 }
1629
1630 static void
1631 read_sample_2(uint8_t *x, uint8_t *y, const uint8_t *input)
1632 {
1633 unsigned int i, j;
1634
1635 for (i = 0, j = 19; i < 20; i += 2, j += 3) {
1636 x[i] = input[j];
1637 x[i + 1] = input[j + 1];
1638 }
1639
1640 for (i = 0, j = 1; i < 9; i += 2, j += 3) {
1641 y[i] = input[j];
1642 y[i + 1] = input[j + 1];
1643 }
1644 }
1645
1646 static void
1648 accumulate_sample_1(struct uatp_softc *sc)
1649 {
1650 unsigned int i;
1651
1652 for (i = 0; i < UATP_SENSORS; i++) {
1653 sc->sc_acc[i] += (int8_t)(sc->sc_sample[i] - sc->sc_base[i]);
1654 if (sc->sc_acc[i] < 0) {
1655 sc->sc_acc[i] = 0;
1656 } else if (UATP_MAX_ACC < sc->sc_acc[i]) {
1657 DPRINTF(sc, UATP_DEBUG_ACCUMULATE,
1658 ("overflow %d\n", sc->sc_acc[i]));
1659 sc->sc_acc[i] = UATP_MAX_ACC;
1660 }
1661 }
1662
1663 memcpy(sc->sc_base, sc->sc_sample, sizeof(sc->sc_base));
1664 }
1665
1666 static void
1667 accumulate_sample_2(struct uatp_softc *sc)
1668 {
1669 unsigned int i;
1670
1671 for (i = 0; i < UATP_SENSORS; i++) {
1672 sc->sc_acc[i] = (int8_t)(sc->sc_sample[i] - sc->sc_base[i]);
1673 if (sc->sc_acc[i] < -0x80) {
1674 DPRINTF(sc, UATP_DEBUG_ACCUMULATE,
1675 ("underflow %u - %u = %d\n",
1676 (unsigned int)sc->sc_sample[i],
1677 (unsigned int)sc->sc_base[i],
1678 sc->sc_acc[i]));
1679 sc->sc_acc[i] += 0x100;
1680 }
1681 if (0x7f < sc->sc_acc[i]) {
1682 DPRINTF(sc, UATP_DEBUG_ACCUMULATE,
1683 ("overflow %u - %u = %d\n",
1684 (unsigned int)sc->sc_sample[i],
1685 (unsigned int)sc->sc_base[i],
1686 sc->sc_acc[i]));
1687 sc->sc_acc[i] -= 0x100;
1688 }
1689 if (sc->sc_acc[i] < 0)
1690 sc->sc_acc[i] = 0;
1691 }
1692 }
1693
1694 /*
1696 * Report input to wsmouse, if there is anything interesting to report.
1697 * We must take into consideration the current tap-and-drag button
1698 * state.
1699 */
1700
1701 static void
1702 uatp_input(struct uatp_softc *sc, uint32_t buttons,
1703 int dx, int dy, int dz, int dw)
1704 {
1705 uint32_t all_buttons;
1706
1707 KASSERT(mutex_owned(&sc->sc_tap_mutex));
1708 all_buttons = buttons | uatp_tapped_buttons(sc);
1709
1710 if ((sc->sc_wsmousedev != NULL) &&
1711 ((dx != 0) || (dy != 0) || (dz != 0) || (dw != 0) ||
1712 (all_buttons != sc->sc_all_buttons))) {
1713 int s = spltty();
1714 DPRINTF(sc, UATP_DEBUG_WSMOUSE, ("wsmouse input:"
1715 " buttons %"PRIx32", dx %d, dy %d, dz %d, dw %d\n",
1716 all_buttons, dx, -dy, dz, -dw));
1717 wsmouse_input(sc->sc_wsmousedev, all_buttons, dx, -dy, dz, -dw,
1718 WSMOUSE_INPUT_DELTA);
1719 splx(s);
1720 }
1721 sc->sc_buttons = buttons;
1722 sc->sc_all_buttons = all_buttons;
1723 }
1724
1725 /*
1726 * Interpret the current tap state to decide whether the tap buttons
1727 * are currently pressed.
1728 */
1729
1730 static uint32_t
1731 uatp_tapped_buttons(struct uatp_softc *sc)
1732 {
1733 KASSERT(mutex_owned(&sc->sc_tap_mutex));
1734 switch (sc->sc_tap_state) {
1735 case TAP_STATE_INITIAL:
1736 case TAP_STATE_TAPPING:
1737 return 0;
1738
1739 case TAP_STATE_TAPPED:
1740 case TAP_STATE_DOUBLE_TAPPING:
1741 case TAP_STATE_DRAGGING_DOWN:
1742 case TAP_STATE_DRAGGING_UP:
1743 case TAP_STATE_TAPPING_IN_DRAG:
1744 CHECK((0 < sc->sc_tapped_fingers), return 0);
1745 switch (sc->sc_tapped_fingers) {
1746 case 1: return sc->sc_knobs.one_finger_tap_buttons;
1747 case 2: return sc->sc_knobs.two_finger_tap_buttons;
1748 case 3:
1749 default: return sc->sc_knobs.three_finger_tap_buttons;
1750 }
1751
1752 default:
1753 aprint_error_dev(uatp_dev(sc), "%s: invalid tap state: %d\n",
1754 __func__, sc->sc_tap_state);
1755 return 0;
1756 }
1757 }
1758
1759 /*
1761 * Interpret the current input state to find a difference in all the
1762 * relevant coordinates and buttons to pass on to wsmouse, and update
1763 * any internal driver state necessary to interpret subsequent input
1764 * relative to this one.
1765 */
1766
1767 static bool
1768 interpret_input(struct uatp_softc *sc, int *dx, int *dy, int *dz, int *dw,
1769 uint32_t *buttons)
1770 {
1771 unsigned int x_pressure, x_raw, x_fingers;
1772 unsigned int y_pressure, y_raw, y_fingers;
1773 unsigned int fingers;
1774
1775 x_pressure = interpret_dimension(sc, uatp_x_acc(sc),
1776 uatp_x_sensors(sc), uatp_x_ratio(sc), &x_raw, &x_fingers);
1777 y_pressure = interpret_dimension(sc, uatp_y_acc(sc),
1778 uatp_y_sensors(sc), uatp_y_ratio(sc), &y_raw, &y_fingers);
1779
1780 DPRINTF(sc, UATP_DEBUG_PARSE,
1781 ("x %u @ %u, %uf; y %u @ %u, %uf; buttons %"PRIx32"\n",
1782 x_pressure, x_raw, x_fingers,
1783 y_pressure, y_raw, y_fingers,
1784 *buttons));
1785
1786 if ((x_pressure == 0) && (y_pressure == 0)) {
1787 bool ok;
1788 /* No fingers: clear position and maybe report a tap. */
1789 DPRINTF(sc, UATP_DEBUG_INTR,
1790 ("no position detected; clearing position\n"));
1791 if (*buttons == 0) {
1792 ok = tap_released(sc);
1793 } else {
1794 tap_reset(sc);
1795 /* Button pressed: interrupt is not spurious. */
1796 ok = true;
1797 }
1798 /*
1799 * Don't clear the position until after tap_released,
1800 * which needs to know the track distance.
1801 */
1802 uatp_clear_position(sc);
1803 return ok;
1804 } else if ((x_pressure == 0) || (y_pressure == 0)) {
1805 /* XXX What to do here? */
1806 DPRINTF(sc, UATP_DEBUG_INTR,
1807 ("pressure in only one dimension; ignoring\n"));
1808 return true;
1809 } else if ((x_pressure == 1) && (y_pressure == 1)) {
1810 fingers = max(x_fingers, y_fingers);
1811 CHECK((0 < fingers), return false);
1812 if (*buttons == 0)
1813 tap_touched(sc, fingers);
1814 else if (fingers == 1)
1815 tap_reset(sc);
1816 else /* Multiple fingers, button pressed. */
1817 *buttons = emulated_buttons(sc, fingers);
1818 update_position(sc, fingers, x_raw, y_raw, dx, dy, dz, dw);
1819 return true;
1820 } else {
1821 /* Palm detected in either or both of the dimensions. */
1822 DPRINTF(sc, UATP_DEBUG_INTR, ("palm detected; ignoring\n"));
1823 return true;
1824 }
1825 }
1826
1827 /*
1829 * Interpret the accumulated sensor state along one dimension to find
1830 * the number, mean position, and pressure of fingers. Returns 0 to
1831 * indicate no pressure, returns 1 and sets *position and *fingers to
1832 * indicate fingers, and returns 2 to indicate palm.
1833 *
1834 * XXX Give symbolic names to the return values.
1835 */
1836
1837 static unsigned int
1838 interpret_dimension(struct uatp_softc *sc, const int *acc,
1839 unsigned int n_sensors, unsigned int ratio,
1840 unsigned int *position, unsigned int *fingers)
1841 {
1842 unsigned int i, v, n_fingers, sum;
1843 unsigned int total[UATP_MAX_SENSORS];
1844 unsigned int weighted[UATP_MAX_SENSORS];
1845 unsigned int sensor_threshold = sc->sc_knobs.sensor_threshold;
1846 unsigned int sensor_normalizer = sc->sc_knobs.sensor_normalizer;
1847 unsigned int width = 0; /* GCC is not smart enough. */
1848 unsigned int palm_width = sc->sc_knobs.palm_width;
1849 enum { none, nondecreasing, decreasing } state = none;
1850
1851 if (sensor_threshold < sensor_normalizer)
1852 sensor_normalizer = sensor_threshold;
1853 if (palm_width == 0) /* Effectively disable palm detection. */
1854 palm_width = UATP_MAX_POSITION;
1855
1856 #define CHECK_(condition) CHECK(condition, return 0)
1857
1858 /*
1859 * Arithmetic bounds:
1860 * . n_sensors is at most UATP_MAX_SENSORS,
1861 * . n_fingers is at most UATP_MAX_SENSORS,
1862 * . i is at most UATP_MAX_SENSORS,
1863 * . sc->sc_acc[i] is at most UATP_MAX_ACC,
1864 * . i * sc->sc_acc[i] is at most UATP_MAX_SENSORS * UATP_MAX_ACC,
1865 * . each total[j] is at most UATP_MAX_SENSORS * UATP_MAX_ACC,
1866 * . each weighted[j] is at most UATP_MAX_SENSORS^2 * UATP_MAX_ACC,
1867 * . ratio is at most UATP_MAX_RATIO,
1868 * . each weighted[j] * ratio is at most
1869 * UATP_MAX_SENSORS^2 * UATP_MAX_ACC * UATP_MAX_RATIO,
1870 * which is #x5fa0000 with the current values of the constants,
1871 * and
1872 * . the sum of the positions is at most
1873 * UATP_MAX_SENSORS * UATP_MAX_POSITION,
1874 * which is #x60000 with the current values of the constants.
1875 * Hence all of the arithmetic here fits in int (and thus also
1876 * unsigned int). If you change the constants, though, you
1877 * must update the analysis.
1878 */
1879 __CTASSERT(0x5fa0000 == (UATP_MAX_SENSORS * UATP_MAX_SENSORS *
1880 UATP_MAX_ACC * UATP_MAX_RATIO));
1881 __CTASSERT(0x60000 == (UATP_MAX_SENSORS * UATP_MAX_POSITION));
1882 CHECK_(n_sensors <= UATP_MAX_SENSORS);
1883 CHECK_(ratio <= UATP_MAX_RATIO);
1884
1885 /*
1886 * Detect each finger by looking for a consecutive sequence of
1887 * increasing and then decreasing pressures above the sensor
1888 * threshold. Compute the finger's position as the weighted
1889 * average of positions, weighted by the pressure at that
1890 * position. Finally, return the average finger position.
1891 */
1892
1893 n_fingers = 0;
1894 memset(weighted, 0, sizeof weighted);
1895 memset(total, 0, sizeof total);
1896
1897 for (i = 0; i < n_sensors; i++) {
1899 CHECK_(0 <= acc[i]);
1900 v = acc[i];
1901
1902 /* Ignore values outside a sensible interval. */
1903 if (v <= sensor_threshold) {
1904 state = none;
1905 continue;
1906 } else if (UATP_MAX_ACC < v) {
1907 aprint_verbose_dev(uatp_dev(sc),
1908 "ignoring large accumulated sensor state: %u\n",
1909 v);
1910 continue;
1911 }
1912
1913 switch (state) {
1914 case none:
1915 n_fingers += 1;
1916 CHECK_(n_fingers <= n_sensors);
1917 state = nondecreasing;
1918 width = 1;
1919 break;
1920
1921 case nondecreasing:
1922 case decreasing:
1923 CHECK_(0 < i);
1924 CHECK_(0 <= acc[i - 1]);
1925 width += 1;
1926 if (palm_width <= (width * ratio)) {
1927 DPRINTF(sc, UATP_DEBUG_PALM,
1928 ("palm detected\n"));
1929 return 2;
1930 } else if ((state == nondecreasing) &&
1931 ((unsigned int)acc[i - 1] > v)) {
1932 state = decreasing;
1933 } else if ((state == decreasing) &&
1934 ((unsigned int)acc[i - 1] < v)) {
1935 n_fingers += 1;
1936 CHECK_(n_fingers <= n_sensors);
1937 state = nondecreasing;
1938 width = 1;
1939 }
1940 break;
1941
1942 default:
1943 aprint_error_dev(uatp_dev(sc),
1944 "bad finger detection state: %d", state);
1945 return 0;
1946 }
1947
1948 v -= sensor_normalizer;
1949 total[n_fingers - 1] += v;
1950 weighted[n_fingers - 1] += (i * v);
1951 CHECK_(total[n_fingers - 1] <=
1952 (UATP_MAX_SENSORS * UATP_MAX_ACC));
1953 CHECK_(weighted[n_fingers - 1] <=
1954 (UATP_MAX_SENSORS * UATP_MAX_SENSORS * UATP_MAX_ACC));
1955 }
1956
1957 if (n_fingers == 0)
1958 return 0;
1959
1960 sum = 0;
1961 for (i = 0; i < n_fingers; i++) {
1962 DPRINTF(sc, UATP_DEBUG_PARSE,
1963 ("finger at %u\n", ((weighted[i] * ratio) / total[i])));
1964 sum += ((weighted[i] * ratio) / total[i]);
1965 CHECK_(sum <= UATP_MAX_SENSORS * UATP_MAX_POSITION);
1966 }
1967
1968 *fingers = n_fingers;
1969 *position = (sum / n_fingers);
1970 return 1;
1971
1972 #undef CHECK_
1973 }
1974
1975 /* Tapping */
1977
1978 /*
1979 * There is a very hairy state machine for detecting taps. At every
1980 * touch, we record the maximum number of fingers touched, and don't
1981 * reset it to zero until the finger is released.
1982 *
1983 * INITIAL STATE
1984 * (no tapping fingers; no tapped fingers)
1985 * - On touch, go to TAPPING STATE.
1986 * - On any other input, remain in INITIAL STATE.
1987 *
1988 * TAPPING STATE: Finger touched; might be tap.
1989 * (tapping fingers; no tapped fingers)
1990 * - On release within the tap limit, go to TAPPED STATE.
1991 * - On release after the tap limit, go to INITIAL STATE.
1992 * - On any other input, remain in TAPPING STATE.
1993 *
1994 * TAPPED STATE: Finger recently tapped, and might double-tap.
1995 * (no tapping fingers; tapped fingers)
1996 * - On touch within the double-tap limit, go to DOUBLE-TAPPING STATE.
1997 * - On touch after the double-tap limit, go to TAPPING STATE.
1998 * - On no event after the double-tap limit, go to INITIAL STATE.
1999 * - On any other input, remain in TAPPED STATE.
2000 *
2001 * DOUBLE-TAPPING STATE: Finger touched soon after tap; might be double-tap.
2002 * (tapping fingers; tapped fingers)
2003 * - On release within the tap limit, release button and go to TAPPED STATE.
2004 * - On release after the tap limit, go to DRAGGING UP STATE.
2005 * - On touch after the tap limit, go to DRAGGING DOWN STATE.
2006 * - On any other input, remain in DOUBLE-TAPPING STATE.
2007 *
2008 * DRAGGING DOWN STATE: Finger has double-tapped and is dragging, not tapping.
2009 * (no tapping fingers; tapped fingers)
2010 * - On release, go to DRAGGING UP STATE.
2011 * - On any other input, remain in DRAGGING DOWN STATE.
2012 *
2013 * DRAGGING UP STATE: Finger has double-tapped and is up.
2014 * (no tapping fingers; tapped fingers)
2015 * - On touch, go to TAPPING IN DRAG STATE.
2016 * - On any other input, remain in DRAGGING UP STATE.
2017 *
2018 * TAPPING IN DRAG STATE: Tap-dancing while cross-dressed.
2019 * (tapping fingers; tapped fingers)
2020 * - On release within the tap limit, go to TAPPED STATE.
2021 * - On release after the tap limit, go to DRAGGING UP STATE.
2022 * - On any other input, remain in TAPPING IN DRAG STATE.
2023 *
2024 * Warning: The graph of states is split into two components, those
2025 * with tapped fingers and those without. The only path from any state
2026 * without tapped fingers to a state with tapped fingers must pass
2027 * through TAPPED STATE. Also, the only transitions into TAPPED STATE
2028 * must be from states with tapping fingers, which become the tapped
2029 * fingers. If you edit the state machine, you must either preserve
2030 * these properties, or globally transform the state machine to avoid
2031 * the bad consequences of violating these properties.
2032 */
2033
2034 static void
2036 uatp_tap_limit(const struct uatp_softc *sc, struct timeval *limit)
2037 {
2038 unsigned int msec = sc->sc_knobs.tap_limit_msec;
2039 limit->tv_sec = 0;
2040 limit->tv_usec = ((msec < 1000) ? (1000 * msec) : 100000);
2041 }
2042
2043 #if UATP_DEBUG
2044
2045 # define TAP_DEBUG_PRE(sc) tap_debug((sc), __func__, "")
2046 # define TAP_DEBUG_POST(sc) tap_debug((sc), __func__, " ->")
2047
2048 static void
2049 tap_debug(struct uatp_softc *sc, const char *caller, const char *prefix)
2050 {
2051 char buffer[128];
2052 const char *state;
2053
2054 KASSERT(mutex_owned(&sc->sc_tap_mutex));
2055 switch (sc->sc_tap_state) {
2056 case TAP_STATE_INITIAL: state = "initial"; break;
2057 case TAP_STATE_TAPPING: state = "tapping"; break;
2058 case TAP_STATE_TAPPED: state = "tapped"; break;
2059 case TAP_STATE_DOUBLE_TAPPING: state = "double-tapping"; break;
2060 case TAP_STATE_DRAGGING_DOWN: state = "dragging-down"; break;
2061 case TAP_STATE_DRAGGING_UP: state = "dragging-up"; break;
2062 case TAP_STATE_TAPPING_IN_DRAG: state = "tapping-in-drag"; break;
2063 default:
2064 snprintf(buffer, sizeof buffer, "unknown (%d)",
2065 sc->sc_tap_state);
2066 state = buffer;
2067 break;
2068 }
2069
2070 DPRINTF(sc, UATP_DEBUG_TAP,
2071 ("%s:%s state %s, %u tapping, %u tapped\n",
2072 caller, prefix, state,
2073 sc->sc_tapping_fingers, sc->sc_tapped_fingers));
2074 }
2075
2076 #else /* !UATP_DEBUG */
2077
2078 # define TAP_DEBUG_PRE(sc) do {} while (0)
2079 # define TAP_DEBUG_POST(sc) do {} while (0)
2080
2081 #endif
2082
2083 static void
2085 tap_initialize(struct uatp_softc *sc)
2086 {
2087 callout_init(&sc->sc_untap_callout, CALLOUT_MPSAFE);
2088 callout_setfunc(&sc->sc_untap_callout, untap_callout, sc);
2089 mutex_init(&sc->sc_tap_mutex, MUTEX_DEFAULT, IPL_USB);
2090 cv_init(&sc->sc_tap_cv, "uatptap");
2091 }
2092
2093 static void
2094 tap_finalize(struct uatp_softc *sc)
2095 {
2096 /* XXX Can the callout still be scheduled here? */
2097 callout_destroy(&sc->sc_untap_callout);
2098 mutex_destroy(&sc->sc_tap_mutex);
2099 cv_destroy(&sc->sc_tap_cv);
2100 }
2101
2102 static void
2103 tap_enable(struct uatp_softc *sc)
2104 {
2105 mutex_enter(&sc->sc_tap_mutex);
2106 tap_transition_initial(sc);
2107 sc->sc_buttons = 0; /* XXX Not the right place? */
2108 sc->sc_all_buttons = 0;
2109 mutex_exit(&sc->sc_tap_mutex);
2110 }
2111
2112 static void
2113 tap_disable(struct uatp_softc *sc)
2114 {
2115 /* Reset tapping, and wait for any callouts to complete. */
2116 tap_reset_wait(sc);
2117 }
2118
2119 /*
2120 * Reset tap state. If the untap callout has just fired, it may signal
2121 * a harmless button release event before this returns.
2122 */
2123
2124 static void
2125 tap_reset(struct uatp_softc *sc)
2126 {
2127 callout_stop(&sc->sc_untap_callout);
2128 mutex_enter(&sc->sc_tap_mutex);
2129 tap_transition_initial(sc);
2130 mutex_exit(&sc->sc_tap_mutex);
2131 }
2132
2133 /* Reset, but don't return until the callout is done running. */
2134
2135 static void
2136 tap_reset_wait(struct uatp_softc *sc)
2137 {
2138 bool fired = callout_stop(&sc->sc_untap_callout);
2139
2140 mutex_enter(&sc->sc_tap_mutex);
2141 if (fired)
2142 while (sc->sc_tap_state == TAP_STATE_TAPPED)
2143 if (cv_timedwait(&sc->sc_tap_cv, &sc->sc_tap_mutex,
2144 mstohz(1000))) {
2145 aprint_error_dev(uatp_dev(sc),
2146 "tap timeout\n");
2147 break;
2148 }
2149 if (sc->sc_tap_state == TAP_STATE_TAPPED)
2150 aprint_error_dev(uatp_dev(sc), "%s error\n", __func__);
2151 tap_transition_initial(sc);
2152 mutex_exit(&sc->sc_tap_mutex);
2153 }
2154
2155 static const struct timeval zero_timeval;
2157
2158 static void
2159 tap_transition(struct uatp_softc *sc, enum uatp_tap_state tap_state,
2160 const struct timeval *start_time,
2161 unsigned int tapping_fingers, unsigned int tapped_fingers)
2162 {
2163 KASSERT(mutex_owned(&sc->sc_tap_mutex));
2164 sc->sc_tap_state = tap_state;
2165 sc->sc_tap_timer = *start_time;
2166 sc->sc_tapping_fingers = tapping_fingers;
2167 sc->sc_tapped_fingers = tapped_fingers;
2168 }
2169
2170 static void
2171 tap_transition_initial(struct uatp_softc *sc)
2172 {
2173 /*
2174 * No checks. This state is always kosher, and sometimes a
2175 * fallback in case of failure.
2176 */
2177 tap_transition(sc, TAP_STATE_INITIAL, &zero_timeval, 0, 0);
2178 }
2179
2180 /* Touch transitions */
2181
2182 static void
2183 tap_transition_tapping(struct uatp_softc *sc, const struct timeval *start_time,
2184 unsigned int fingers)
2185 {
2186 CHECK((sc->sc_tapping_fingers <= fingers),
2187 do { tap_transition_initial(sc); return; } while (0));
2188 tap_transition(sc, TAP_STATE_TAPPING, start_time, fingers, 0);
2189 }
2190
2191 static void
2192 tap_transition_double_tapping(struct uatp_softc *sc,
2193 const struct timeval *start_time, unsigned int fingers)
2194 {
2195 CHECK((sc->sc_tapping_fingers <= fingers),
2196 do { tap_transition_initial(sc); return; } while (0));
2197 CHECK((0 < sc->sc_tapped_fingers),
2198 do { tap_transition_initial(sc); return; } while (0));
2199 tap_transition(sc, TAP_STATE_DOUBLE_TAPPING, start_time, fingers,
2200 sc->sc_tapped_fingers);
2201 }
2202
2203 static void
2205 tap_transition_dragging_down(struct uatp_softc *sc)
2206 {
2207 CHECK((0 < sc->sc_tapped_fingers),
2208 do { tap_transition_initial(sc); return; } while (0));
2209 tap_transition(sc, TAP_STATE_DRAGGING_DOWN, &zero_timeval, 0,
2210 sc->sc_tapped_fingers);
2211 }
2212
2213 static void
2214 tap_transition_tapping_in_drag(struct uatp_softc *sc,
2215 const struct timeval *start_time, unsigned int fingers)
2216 {
2217 CHECK((sc->sc_tapping_fingers <= fingers),
2218 do { tap_transition_initial(sc); return; } while (0));
2219 CHECK((0 < sc->sc_tapped_fingers),
2220 do { tap_transition_initial(sc); return; } while (0));
2221 tap_transition(sc, TAP_STATE_TAPPING_IN_DRAG, start_time, fingers,
2222 sc->sc_tapped_fingers);
2223 }
2224
2225 /* Release transitions */
2226
2227 static void
2228 tap_transition_tapped(struct uatp_softc *sc, const struct timeval *start_time)
2229 {
2230 /*
2231 * The fingers that were tapping -- of which there must have
2232 * been at least one -- are now the fingers that have tapped,
2233 * and there are no longer fingers tapping.
2234 */
2235 CHECK((0 < sc->sc_tapping_fingers),
2236 do { tap_transition_initial(sc); return; } while (0));
2237 tap_transition(sc, TAP_STATE_TAPPED, start_time, 0,
2238 sc->sc_tapping_fingers);
2239 schedule_untap(sc);
2240 }
2241
2242 static void
2243 tap_transition_dragging_up(struct uatp_softc *sc)
2244 {
2245 CHECK((0 < sc->sc_tapped_fingers),
2246 do { tap_transition_initial(sc); return; } while (0));
2247 tap_transition(sc, TAP_STATE_DRAGGING_UP, &zero_timeval, 0,
2248 sc->sc_tapped_fingers);
2249 }
2250
2251 static void
2253 tap_touched(struct uatp_softc *sc, unsigned int fingers)
2254 {
2255 struct timeval now, diff, limit;
2256
2257 CHECK((0 < fingers), return);
2258 callout_stop(&sc->sc_untap_callout);
2259 mutex_enter(&sc->sc_tap_mutex);
2260 TAP_DEBUG_PRE(sc);
2261 /*
2262 * Guarantee that the number of tapping fingers never decreases
2263 * except when it is reset to zero on release.
2264 */
2265 if (fingers < sc->sc_tapping_fingers)
2266 fingers = sc->sc_tapping_fingers;
2267 switch (sc->sc_tap_state) {
2268 case TAP_STATE_INITIAL:
2269 getmicrouptime(&now);
2270 tap_transition_tapping(sc, &now, fingers);
2271 break;
2272
2273 case TAP_STATE_TAPPING:
2274 /*
2275 * Number of fingers may have increased, so transition
2276 * even though we're already in TAPPING.
2277 */
2278 tap_transition_tapping(sc, &sc->sc_tap_timer, fingers);
2279 break;
2280
2281 case TAP_STATE_TAPPED:
2282 getmicrouptime(&now);
2283 /*
2284 * If the double-tap time limit has passed, it's the
2285 * callout's responsibility to handle that event, so we
2286 * assume the limit has not passed yet.
2287 */
2288 tap_transition_double_tapping(sc, &now, fingers);
2289 break;
2290
2291 case TAP_STATE_DOUBLE_TAPPING:
2292 getmicrouptime(&now);
2293 timersub(&now, &sc->sc_tap_timer, &diff);
2294 uatp_tap_limit(sc, &limit);
2295 if (timercmp(&diff, &limit, >) ||
2296 (sc->sc_track_distance >
2297 sc->sc_knobs.tap_track_distance_limit))
2298 tap_transition_dragging_down(sc);
2299 break;
2300
2301 case TAP_STATE_DRAGGING_DOWN:
2302 break;
2303
2304 case TAP_STATE_DRAGGING_UP:
2305 getmicrouptime(&now);
2306 tap_transition_tapping_in_drag(sc, &now, fingers);
2307 break;
2308
2309 case TAP_STATE_TAPPING_IN_DRAG:
2310 /*
2311 * Number of fingers may have increased, so transition
2312 * even though we're already in TAPPING IN DRAG.
2313 */
2314 tap_transition_tapping_in_drag(sc, &sc->sc_tap_timer, fingers);
2315 break;
2316
2317 default:
2318 aprint_error_dev(uatp_dev(sc), "%s: invalid tap state: %d\n",
2319 __func__, sc->sc_tap_state);
2320 tap_transition_initial(sc);
2321 break;
2322 }
2323 TAP_DEBUG_POST(sc);
2324 mutex_exit(&sc->sc_tap_mutex);
2325 }
2326
2327 static bool
2329 tap_released(struct uatp_softc *sc)
2330 {
2331 struct timeval now, diff, limit;
2332 void (*non_tapped_transition)(struct uatp_softc *);
2333 bool ok, temporary_release;
2334
2335 mutex_enter(&sc->sc_tap_mutex);
2336 TAP_DEBUG_PRE(sc);
2337 switch (sc->sc_tap_state) {
2338 case TAP_STATE_INITIAL:
2339 case TAP_STATE_TAPPED:
2340 case TAP_STATE_DRAGGING_UP:
2341 /* Spurious interrupt: fingers are already off. */
2342 ok = false;
2343 break;
2344
2345 case TAP_STATE_TAPPING:
2346 temporary_release = false;
2347 non_tapped_transition = &tap_transition_initial;
2348 goto maybe_tap;
2349
2350 case TAP_STATE_DOUBLE_TAPPING:
2351 temporary_release = true;
2352 non_tapped_transition = &tap_transition_dragging_up;
2353 goto maybe_tap;
2354
2355 case TAP_STATE_TAPPING_IN_DRAG:
2356 temporary_release = false;
2357 non_tapped_transition = &tap_transition_dragging_up;
2358 goto maybe_tap;
2359
2360 maybe_tap:
2361 getmicrouptime(&now);
2362 timersub(&now, &sc->sc_tap_timer, &diff);
2363 uatp_tap_limit(sc, &limit);
2364 if (timercmp(&diff, &limit, <=) &&
2365 (sc->sc_track_distance <=
2366 sc->sc_knobs.tap_track_distance_limit)) {
2367 if (temporary_release) {
2368 /*
2369 * XXX Kludge: Temporarily transition
2370 * to a tap state that uatp_input will
2371 * interpret as `no buttons tapped',
2372 * saving the tapping fingers. There
2373 * should instead be a separate routine
2374 * uatp_input_untapped.
2375 */
2376 unsigned int fingers = sc->sc_tapping_fingers;
2377 tap_transition_initial(sc);
2378 uatp_input(sc, 0, 0, 0, 0, 0);
2379 sc->sc_tapping_fingers = fingers;
2380 }
2381 tap_transition_tapped(sc, &now);
2382 } else {
2383 (*non_tapped_transition)(sc);
2384 }
2385 ok = true;
2386 break;
2387
2388 case TAP_STATE_DRAGGING_DOWN:
2389 tap_transition_dragging_up(sc);
2390 ok = true;
2391 break;
2392
2393 default:
2394 aprint_error_dev(uatp_dev(sc), "%s: invalid tap state: %d\n",
2395 __func__, sc->sc_tap_state);
2396 tap_transition_initial(sc);
2397 ok = false;
2398 break;
2399 }
2400 TAP_DEBUG_POST(sc);
2401 mutex_exit(&sc->sc_tap_mutex);
2402 return ok;
2403 }
2404
2405 /* Untapping: Releasing the button after a tap */
2407
2408 static void
2409 schedule_untap(struct uatp_softc *sc)
2410 {
2411 unsigned int ms = sc->sc_knobs.double_tap_limit_msec;
2412 if (ms <= 1000)
2413 callout_schedule(&sc->sc_untap_callout, mstohz(ms));
2414 else /* XXX Reject bogus values in sysctl. */
2415 aprint_error_dev(uatp_dev(sc),
2416 "double-tap delay too long: %ums\n", ms);
2417 }
2418
2419 static void
2420 untap_callout(void *arg)
2421 {
2422 struct uatp_softc *sc = arg;
2423
2424 mutex_enter(&sc->sc_tap_mutex);
2425 TAP_DEBUG_PRE(sc);
2426 switch (sc->sc_tap_state) {
2427 case TAP_STATE_TAPPED:
2428 tap_transition_initial(sc);
2429 /*
2430 * XXX Kludge: Call uatp_input after the state transition
2431 * to make sure that it will actually release the button.
2432 */
2433 uatp_input(sc, 0, 0, 0, 0, 0);
2434
2435 case TAP_STATE_INITIAL:
2436 case TAP_STATE_TAPPING:
2437 case TAP_STATE_DOUBLE_TAPPING:
2438 case TAP_STATE_DRAGGING_UP:
2439 case TAP_STATE_DRAGGING_DOWN:
2440 case TAP_STATE_TAPPING_IN_DRAG:
2441 /*
2442 * Somebody else got in and changed the state before we
2443 * untapped. Let them take over; do nothing here.
2444 */
2445 break;
2446
2447 default:
2448 aprint_error_dev(uatp_dev(sc), "%s: invalid tap state: %d\n",
2449 __func__, sc->sc_tap_state);
2450 tap_transition_initial(sc);
2451 /* XXX Just in case...? */
2452 uatp_input(sc, 0, 0, 0, 0, 0);
2453 break;
2454 }
2455 TAP_DEBUG_POST(sc);
2456 /* XXX Broadcast only if state was TAPPED? */
2457 cv_broadcast(&sc->sc_tap_cv);
2458 mutex_exit(&sc->sc_tap_mutex);
2459 }
2460
2461 /*
2463 * Emulate different buttons if the user holds down n fingers while
2464 * pressing the physical button. (This is unrelated to tapping.)
2465 */
2466
2467 static uint32_t
2468 emulated_buttons(struct uatp_softc *sc, unsigned int fingers)
2469 {
2470 CHECK((1 < fingers), return 0);
2471
2472 switch (fingers) {
2473 case 2:
2474 DPRINTF(sc, UATP_DEBUG_EMUL_BUTTON,
2475 ("2-finger emulated button: %"PRIx32"\n",
2476 sc->sc_knobs.two_finger_buttons));
2477 return sc->sc_knobs.two_finger_buttons;
2478
2479 case 3:
2480 default:
2481 DPRINTF(sc, UATP_DEBUG_EMUL_BUTTON,
2482 ("3-finger emulated button: %"PRIx32"\n",
2483 sc->sc_knobs.three_finger_buttons));
2484 return sc->sc_knobs.three_finger_buttons;
2485 }
2486 }
2487
2488 /*
2490 * Update the position known to the driver based on the position and
2491 * number of fingers. dx, dy, dz, and dw are expected to hold zero;
2492 * update_position may store nonzero changes in position in them.
2493 */
2494
2495 static void
2496 update_position(struct uatp_softc *sc, unsigned int fingers,
2497 unsigned int x_raw, unsigned int y_raw,
2498 int *dx, int *dy, int *dz, int *dw)
2499 {
2500 CHECK((0 < fingers), return);
2501
2502 if ((fingers == 1) || (sc->sc_knobs.multifinger_track == 1))
2503 move_mouse(sc, x_raw, y_raw, dx, dy);
2504 else if (sc->sc_knobs.multifinger_track == 2)
2505 scroll_wheel(sc, x_raw, y_raw, dz, dw);
2506 }
2507
2508 /*
2509 * XXX Scrolling needs to use a totally different motion model.
2510 */
2511
2512 static void
2513 move_mouse(struct uatp_softc *sc, unsigned int x_raw, unsigned int y_raw,
2514 int *dx, int *dy)
2515 {
2516 move(sc, "mouse", x_raw, y_raw, &sc->sc_x_raw, &sc->sc_y_raw,
2517 &sc->sc_x_smoothed, &sc->sc_y_smoothed,
2518 &sc->sc_x_remainder, &sc->sc_y_remainder,
2519 dx, dy);
2520 }
2521
2522 static void
2523 scroll_wheel(struct uatp_softc *sc, unsigned int x_raw, unsigned int y_raw,
2524 int *dz, int *dw)
2525 {
2526 move(sc, "scroll", x_raw, y_raw, &sc->sc_z_raw, &sc->sc_w_raw,
2527 &sc->sc_z_smoothed, &sc->sc_w_smoothed,
2528 &sc->sc_z_remainder, &sc->sc_w_remainder,
2529 dz, dw);
2530 }
2531
2532 static void
2534 move(struct uatp_softc *sc, const char *ctx, unsigned int a, unsigned int b,
2535 int *a_raw, int *b_raw,
2536 int *a_smoothed, int *b_smoothed,
2537 unsigned int *a_remainder, unsigned int *b_remainder,
2538 int *da, int *db)
2539 {
2540 #define CHECK_(condition) CHECK(condition, return)
2541
2542 int old_a_raw = *a_raw, old_a_smoothed = *a_smoothed;
2543 int old_b_raw = *b_raw, old_b_smoothed = *b_smoothed;
2544 unsigned int a_dist, b_dist, dist_squared;
2545 bool a_fast, b_fast;
2546
2547 /*
2548 * Make sure the quadratics in motion_below_threshold and
2549 * tracking distance don't overflow int arithmetic.
2550 */
2551 __CTASSERT(0x12000000 == (2 * UATP_MAX_POSITION * UATP_MAX_POSITION));
2552
2553 CHECK_(a <= UATP_MAX_POSITION);
2554 CHECK_(b <= UATP_MAX_POSITION);
2555 *a_raw = a;
2556 *b_raw = b;
2557 if ((old_a_raw < 0) || (old_b_raw < 0)) {
2558 DPRINTF(sc, UATP_DEBUG_MOVE,
2559 ("initialize %s position (%d, %d) -> (%d, %d)\n", ctx,
2560 old_a_raw, old_b_raw, a, b));
2561 return;
2562 }
2563
2564 if ((old_a_smoothed < 0) || (old_b_smoothed < 0)) {
2565 /* XXX Does this make sense? */
2566 old_a_smoothed = old_a_raw;
2567 old_b_smoothed = old_b_raw;
2568 }
2569
2570 CHECK_(0 <= old_a_raw);
2571 CHECK_(0 <= old_b_raw);
2572 CHECK_(old_a_raw <= UATP_MAX_POSITION);
2573 CHECK_(old_b_raw <= UATP_MAX_POSITION);
2574 CHECK_(0 <= old_a_smoothed);
2575 CHECK_(0 <= old_b_smoothed);
2576 CHECK_(old_a_smoothed <= UATP_MAX_POSITION);
2577 CHECK_(old_b_smoothed <= UATP_MAX_POSITION);
2578 CHECK_(0 <= *a_raw);
2579 CHECK_(0 <= *b_raw);
2580 CHECK_(*a_raw <= UATP_MAX_POSITION);
2581 CHECK_(*b_raw <= UATP_MAX_POSITION);
2582 *a_smoothed = smooth(sc, old_a_raw, old_a_smoothed, *a_raw);
2583 *b_smoothed = smooth(sc, old_b_raw, old_b_smoothed, *b_raw);
2584 CHECK_(0 <= *a_smoothed);
2585 CHECK_(0 <= *b_smoothed);
2586 CHECK_(*a_smoothed <= UATP_MAX_POSITION);
2587 CHECK_(*b_smoothed <= UATP_MAX_POSITION);
2588
2589 if (sc->sc_motion_timer < sc->sc_knobs.motion_delay) {
2591 DPRINTF(sc, UATP_DEBUG_MOVE, ("delay motion %u\n",
2592 sc->sc_motion_timer));
2593 sc->sc_motion_timer += 1;
2594 return;
2595 }
2596
2597 /* XXX Use raw distances or smoothed distances? Acceleration? */
2598 if (*a_smoothed < old_a_smoothed)
2599 a_dist = old_a_smoothed - *a_smoothed;
2600 else
2601 a_dist = *a_smoothed - old_a_smoothed;
2602
2603 if (*b_smoothed < old_b_smoothed)
2604 b_dist = old_b_smoothed - *b_smoothed;
2605 else
2606 b_dist = *b_smoothed - old_b_smoothed;
2607
2608 dist_squared = (a_dist * a_dist) + (b_dist * b_dist);
2609 if (dist_squared < ((2 * UATP_MAX_POSITION * UATP_MAX_POSITION)
2610 - sc->sc_track_distance))
2611 sc->sc_track_distance += dist_squared;
2612 else
2613 sc->sc_track_distance = (2 * UATP_MAX_POSITION *
2614 UATP_MAX_POSITION);
2615 DPRINTF(sc, UATP_DEBUG_TRACK_DIST, ("finger has tracked %u units^2\n",
2616 sc->sc_track_distance));
2617
2618 /*
2619 * The checks above guarantee that the differences here are at
2620 * most UATP_MAX_POSITION in magnitude, since both minuend and
2621 * subtrahend are nonnegative and at most UATP_MAX_POSITION.
2622 */
2623 if (motion_below_threshold(sc, sc->sc_knobs.motion_threshold,
2624 (int)(*a_smoothed - old_a_smoothed),
2625 (int)(*b_smoothed - old_b_smoothed))) {
2626 DPRINTF(sc, UATP_DEBUG_MOVE,
2627 ("%s motion too small: (%d, %d) -> (%d, %d)\n", ctx,
2628 old_a_smoothed, old_b_smoothed,
2629 *a_smoothed, *b_smoothed));
2630 return;
2631 }
2632 if (sc->sc_knobs.fast_per_direction == 0) {
2633 a_fast = b_fast = !motion_below_threshold(sc,
2634 sc->sc_knobs.fast_motion_threshold,
2635 (int)(*a_smoothed - old_a_smoothed),
2636 (int)(*b_smoothed - old_b_smoothed));
2637 } else {
2638 a_fast = !motion_below_threshold(sc,
2639 sc->sc_knobs.fast_motion_threshold,
2640 (int)(*a_smoothed - old_a_smoothed),
2641 0);
2642 b_fast = !motion_below_threshold(sc,
2643 sc->sc_knobs.fast_motion_threshold,
2644 0,
2645 (int)(*b_smoothed - old_b_smoothed));
2646 }
2647 *da = accelerate(sc, old_a_raw, *a_raw, old_a_smoothed, *a_smoothed,
2648 a_fast, a_remainder);
2649 *db = accelerate(sc, old_b_raw, *b_raw, old_b_smoothed, *b_smoothed,
2650 b_fast, b_remainder);
2651 DPRINTF(sc, UATP_DEBUG_MOVE,
2652 ("update %s position (%d, %d) -> (%d, %d), move by (%d, %d)\n",
2653 ctx, old_a_smoothed, old_b_smoothed, *a_smoothed, *b_smoothed,
2654 *da, *db));
2655
2656 #undef CHECK_
2657 }
2658
2659 static int
2661 smooth(struct uatp_softc *sc, unsigned int old_raw, unsigned int old_smoothed,
2662 unsigned int raw)
2663 {
2664 #define CHECK_(condition) CHECK(condition, return old_raw)
2665
2666 /*
2667 * Arithmetic bounds:
2668 * . the weights are at most UATP_MAX_WEIGHT;
2669 * . the positions are at most UATP_MAX_POSITION; and so
2670 * . the numerator of the average is at most
2671 * 3 * UATP_MAX_WEIGHT * UATP_MAX_POSITION,
2672 * which is #x477000, fitting comfortably in an int.
2673 */
2674 __CTASSERT(0x477000 == (3 * UATP_MAX_WEIGHT * UATP_MAX_POSITION));
2675 unsigned int old_raw_weight = uatp_old_raw_weight(sc);
2676 unsigned int old_smoothed_weight = uatp_old_smoothed_weight(sc);
2677 unsigned int new_raw_weight = uatp_new_raw_weight(sc);
2678 CHECK_(old_raw_weight <= UATP_MAX_WEIGHT);
2679 CHECK_(old_smoothed_weight <= UATP_MAX_WEIGHT);
2680 CHECK_(new_raw_weight <= UATP_MAX_WEIGHT);
2681 CHECK_(old_raw <= UATP_MAX_POSITION);
2682 CHECK_(old_smoothed <= UATP_MAX_POSITION);
2683 CHECK_(raw <= UATP_MAX_POSITION);
2684 return (((old_raw_weight * old_raw) +
2685 (old_smoothed_weight * old_smoothed) +
2686 (new_raw_weight * raw))
2687 / (old_raw_weight + old_smoothed_weight + new_raw_weight));
2688
2689 #undef CHECK_
2690 }
2691
2692 static bool
2693 motion_below_threshold(struct uatp_softc *sc, unsigned int threshold,
2694 int x, int y)
2695 {
2696 unsigned int x_squared, y_squared;
2697
2698 /* Caller guarantees the multiplication will not overflow. */
2699 KASSERT(-UATP_MAX_POSITION <= x);
2700 KASSERT(-UATP_MAX_POSITION <= y);
2701 KASSERT(x <= UATP_MAX_POSITION);
2702 KASSERT(y <= UATP_MAX_POSITION);
2703 __CTASSERT(0x12000000 == (2 * UATP_MAX_POSITION * UATP_MAX_POSITION));
2704
2705 x_squared = (x * x);
2706 y_squared = (y * y);
2707
2708 return ((x_squared + y_squared) < threshold);
2709 }
2710
2711 static int
2712 accelerate(struct uatp_softc *sc, unsigned int old_raw, unsigned int raw,
2713 unsigned int old_smoothed, unsigned int smoothed, bool fast,
2714 int *remainder)
2715 {
2716 #define CHECK_(condition) CHECK(condition, return 0)
2717
2718 /* Guarantee that the scaling won't overflow. */
2719 __CTASSERT(0x30000 ==
2720 (UATP_MAX_POSITION * UATP_MAX_MOTION_MULTIPLIER));
2721
2722 CHECK_(old_raw <= UATP_MAX_POSITION);
2723 CHECK_(raw <= UATP_MAX_POSITION);
2724 CHECK_(old_smoothed <= UATP_MAX_POSITION);
2725 CHECK_(smoothed <= UATP_MAX_POSITION);
2726
2727 return (fast ? uatp_scale_fast_motion : uatp_scale_motion)
2728 (sc, (((int) smoothed) - ((int) old_smoothed)), remainder);
2729
2730 #undef CHECK_
2731 }
2732