xref: /freebsd/sys/dev/usb/input/atp.c (revision e42fc368672e8c3f1d30fbbd7f1903e3baa69b7a)
1 /*-
2  * Copyright (c) 2009 Rohit Grover
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
33 #include <sys/malloc.h>
34 #include <sys/module.h>
35 #include <sys/lock.h>
36 #include <sys/mutex.h>
37 #include <sys/bus.h>
38 #include <sys/conf.h>
39 #include <sys/fcntl.h>
40 #include <sys/file.h>
41 #include <sys/selinfo.h>
42 #include <sys/poll.h>
43 #include <sys/sysctl.h>
44 #include <sys/uio.h>
45 
46 #include <dev/usb/usb.h>
47 #include <dev/usb/usbdi.h>
48 #include <dev/usb/usbdi_util.h>
49 #include <dev/usb/usbhid.h>
50 #include "usbdevs.h"
51 
52 #define USB_DEBUG_VAR atp_debug
53 #include <dev/usb/usb_debug.h>
54 
55 #include <sys/mouse.h>
56 
57 #define ATP_DRIVER_NAME "atp"
58 
59 /*
60  * Driver specific options: the following options may be set by
61  * `options' statements in the kernel configuration file.
62  */
63 
64 /* The multiplier used to translate sensor reported positions to mickeys. */
65 #ifndef ATP_SCALE_FACTOR
66 #define ATP_SCALE_FACTOR 48
67 #endif
68 
69 /*
70  * This is the age (in microseconds) beyond which a touch is
71  * considered to be a slide; and therefore a tap event isn't registered.
72  */
73 #ifndef ATP_TOUCH_TIMEOUT
74 #define ATP_TOUCH_TIMEOUT 125000
75 #endif
76 
77 /*
78  * A double-tap followed by a single-finger slide is treated as a
79  * special gesture. The driver responds to this gesture by assuming a
80  * virtual button-press for the lifetime of the slide. The following
81  * threshold is the maximum time gap (in microseconds) between the two
82  * tap events preceding the slide for such a gesture.
83  */
84 #ifndef ATP_DOUBLE_TAP_N_DRAG_THRESHOLD
85 #define ATP_DOUBLE_TAP_N_DRAG_THRESHOLD 200000
86 #endif
87 
88 /*
89  * The device provides us only with pressure readings from an array of
90  * X and Y sensors; for our algorithms, we need to interpret groups
91  * (typically pairs) of X and Y readings as being related to a single
92  * finger stroke. We can relate X and Y readings based on their times
93  * of incidence. The coincidence window should be at least 10000us
94  * since it is used against values from getmicrotime(), which has a
95  * precision of around 10ms.
96  */
97 #ifndef ATP_COINCIDENCE_THRESHOLD
98 #define ATP_COINCIDENCE_THRESHOLD  40000 /* unit: microseconds */
99 #if ATP_COINCIDENCE_THRESHOLD > 100000
100 #error "ATP_COINCIDENCE_THRESHOLD too large"
101 #endif
102 #endif /* #ifndef ATP_COINCIDENCE_THRESHOLD */
103 
104 /*
105  * The wait duration (in microseconds) after losing a touch contact
106  * before zombied strokes are reaped and turned into button events.
107  */
108 #define ATP_ZOMBIE_STROKE_REAP_WINDOW   50000
109 #if ATP_ZOMBIE_STROKE_REAP_WINDOW > 100000
110 #error "ATP_ZOMBIE_STROKE_REAP_WINDOW too large"
111 #endif
112 
113 /* end of driver specific options */
114 
115 
116 /* Tunables */
117 SYSCTL_NODE(_hw_usb, OID_AUTO, atp, CTLFLAG_RW, 0, "USB atp");
118 
119 #if USB_DEBUG
120 enum atp_log_level {
121 	ATP_LLEVEL_DISABLED = 0,
122 	ATP_LLEVEL_ERROR,
123 	ATP_LLEVEL_DEBUG,       /* for troubleshooting */
124 	ATP_LLEVEL_INFO,        /* for diagnostics */
125 };
126 static int atp_debug = ATP_LLEVEL_ERROR; /* the default is to only log errors */
127 SYSCTL_INT(_hw_usb_atp, OID_AUTO, debug, CTLFLAG_RW,
128     &atp_debug, ATP_LLEVEL_ERROR, "ATP debug level");
129 #endif /* #if USB_DEBUG */
130 
131 static u_int atp_touch_timeout = ATP_TOUCH_TIMEOUT;
132 SYSCTL_INT(_hw_usb_atp, OID_AUTO, touch_timeout, CTLFLAG_RW, &atp_touch_timeout,
133     125000, "age threshold (in micros) for a touch");
134 
135 static u_int atp_double_tap_threshold = ATP_DOUBLE_TAP_N_DRAG_THRESHOLD;
136 SYSCTL_INT(_hw_usb_atp, OID_AUTO, double_tap_threshold, CTLFLAG_RW,
137     &atp_double_tap_threshold, ATP_DOUBLE_TAP_N_DRAG_THRESHOLD,
138     "maximum time (in micros) between a double-tap");
139 
140 static u_int atp_mickeys_scale_factor = ATP_SCALE_FACTOR;
141 static int atp_sysctl_scale_factor_handler(SYSCTL_HANDLER_ARGS);
142 SYSCTL_PROC(_hw_usb_atp, OID_AUTO, scale_factor, CTLTYPE_UINT | CTLFLAG_RW,
143     &atp_mickeys_scale_factor, sizeof(atp_mickeys_scale_factor),
144     atp_sysctl_scale_factor_handler, "IU", "movement scale factor");
145 
146 static u_int atp_small_movement_threshold = ATP_SCALE_FACTOR >> 3;
147 SYSCTL_UINT(_hw_usb_atp, OID_AUTO, small_movement, CTLFLAG_RW,
148     &atp_small_movement_threshold, ATP_SCALE_FACTOR >> 3,
149     "the small movement black-hole for filtering noise");
150 /*
151  * The movement threshold for a stroke; this is the maximum difference
152  * in position which will be resolved as a continuation of a stroke
153  * component.
154  */
155 static u_int atp_max_delta_mickeys = ((3 * ATP_SCALE_FACTOR) >> 1);
156 SYSCTL_UINT(_hw_usb_atp, OID_AUTO, max_delta_mickeys, CTLFLAG_RW,
157     &atp_max_delta_mickeys, ((3 * ATP_SCALE_FACTOR) >> 1),
158     "max. mickeys-delta which will match against an existing stroke");
159 /*
160  * Strokes which accumulate at least this amount of absolute movement
161  * from the aggregate of their components are considered as
162  * slides. Unit: mickeys.
163  */
164 static u_int atp_slide_min_movement = (ATP_SCALE_FACTOR >> 3);
165 SYSCTL_UINT(_hw_usb_atp, OID_AUTO, slide_min_movement, CTLFLAG_RW,
166     &atp_slide_min_movement, (ATP_SCALE_FACTOR >> 3),
167     "strokes with at least this amt. of movement are considered slides");
168 
169 /*
170  * The minimum age of a stroke for it to be considered mature; this
171  * helps filter movements (noise) from immature strokes. Units: interrupts.
172  */
173 static u_int atp_stroke_maturity_threshold = 2;
174 SYSCTL_UINT(_hw_usb_atp, OID_AUTO, stroke_maturity_threshold, CTLFLAG_RW,
175     &atp_stroke_maturity_threshold, 2,
176     "the minimum age of a stroke for it to be considered mature");
177 
178 /* Accept pressure readings from sensors only if above this value. */
179 static u_int atp_sensor_noise_threshold = 2;
180 SYSCTL_UINT(_hw_usb_atp, OID_AUTO, sensor_noise_threshold, CTLFLAG_RW,
181     &atp_sensor_noise_threshold, 2,
182     "accept pressure readings from sensors only if above this value");
183 
184 /* Ignore pressure spans with cumulative press. below this value. */
185 static u_int atp_pspan_min_cum_pressure = 10;
186 SYSCTL_UINT(_hw_usb_atp, OID_AUTO, pspan_min_cum_pressure, CTLFLAG_RW,
187     &atp_pspan_min_cum_pressure, 10,
188     "ignore pressure spans with cumulative press. below this value");
189 
190 /* Maximum allowed width for pressure-spans.*/
191 static u_int atp_pspan_max_width = 4;
192 SYSCTL_UINT(_hw_usb_atp, OID_AUTO, pspan_max_width, CTLFLAG_RW,
193     &atp_pspan_max_width, 4,
194     "maximum allowed width (in sensors) for pressure-spans");
195 
196 /* We support three payload protocols */
197 typedef enum {
198 	ATP_PROT_GEYSER1,
199 	ATP_PROT_GEYSER2,
200 	ATP_PROT_GEYSER3,
201 } atp_protocol;
202 
203 /* Define the various flavours of devices supported by this driver. */
204 enum {
205 	ATP_DEV_PARAMS_0,
206 	ATP_DEV_PARAMS_PBOOK,
207 	ATP_DEV_PARAMS_PBOOK_15A,
208 	ATP_DEV_PARAMS_PBOOK_17,
209 	ATP_N_DEV_PARAMS
210 };
211 struct atp_dev_params {
212 	u_int            data_len;   /* for sensor data */
213 	u_int            n_xsensors;
214 	u_int            n_ysensors;
215 	atp_protocol     prot;
216 } atp_dev_params[ATP_N_DEV_PARAMS] = {
217 	[ATP_DEV_PARAMS_0] = {
218 		.data_len   = 64,
219 		.n_xsensors = 20,
220 		.n_ysensors = 10,
221 		.prot       = ATP_PROT_GEYSER3
222 	},
223 	[ATP_DEV_PARAMS_PBOOK] = {
224 		.data_len   = 81,
225 		.n_xsensors = 16,
226 		.n_ysensors = 16,
227 		.prot       = ATP_PROT_GEYSER1
228 	},
229 	[ATP_DEV_PARAMS_PBOOK_15A] = {
230 		.data_len   = 64,
231 		.n_xsensors = 15,
232 		.n_ysensors = 9,
233 		.prot       = ATP_PROT_GEYSER2
234 	},
235 	[ATP_DEV_PARAMS_PBOOK_17] = {
236 		.data_len   = 81,
237 		.n_xsensors = 26,
238 		.n_ysensors = 16,
239 		.prot       = ATP_PROT_GEYSER1
240 	},
241 };
242 
243 static const struct usb_device_id atp_devs[] = {
244 	/* Core Duo MacBook & MacBook Pro */
245 	{ USB_VPI(USB_VENDOR_APPLE, 0x0217, ATP_DEV_PARAMS_0) },
246 	{ USB_VPI(USB_VENDOR_APPLE, 0x0218, ATP_DEV_PARAMS_0) },
247 	{ USB_VPI(USB_VENDOR_APPLE, 0x0219, ATP_DEV_PARAMS_0) },
248 
249 	/* Core2 Duo MacBook & MacBook Pro */
250 	{ USB_VPI(USB_VENDOR_APPLE, 0x021a, ATP_DEV_PARAMS_0) },
251 	{ USB_VPI(USB_VENDOR_APPLE, 0x021b, ATP_DEV_PARAMS_0) },
252 	{ USB_VPI(USB_VENDOR_APPLE, 0x021c, ATP_DEV_PARAMS_0) },
253 
254 	/* Core2 Duo MacBook3,1 */
255 	{ USB_VPI(USB_VENDOR_APPLE, 0x0229, ATP_DEV_PARAMS_0) },
256 	{ USB_VPI(USB_VENDOR_APPLE, 0x022a, ATP_DEV_PARAMS_0) },
257 	{ USB_VPI(USB_VENDOR_APPLE, 0x022b, ATP_DEV_PARAMS_0) },
258 
259 	/* 12 inch PowerBook and iBook */
260 	{ USB_VPI(USB_VENDOR_APPLE, 0x030a, ATP_DEV_PARAMS_PBOOK) },
261 	{ USB_VPI(USB_VENDOR_APPLE, 0x030b, ATP_DEV_PARAMS_PBOOK) },
262 
263 	/* 15 inch PowerBook */
264 	{ USB_VPI(USB_VENDOR_APPLE, 0x020e, ATP_DEV_PARAMS_PBOOK) },
265 	{ USB_VPI(USB_VENDOR_APPLE, 0x020f, ATP_DEV_PARAMS_PBOOK) },
266 	{ USB_VPI(USB_VENDOR_APPLE, 0x0215, ATP_DEV_PARAMS_PBOOK_15A) },
267 
268 	/* 17 inch PowerBook */
269 	{ USB_VPI(USB_VENDOR_APPLE, 0x020d, ATP_DEV_PARAMS_PBOOK_17) },
270 
271 };
272 
273 /*
274  * The following structure captures the state of a pressure span along
275  * an axis. Each contact with the touchpad results in separate
276  * pressure spans along the two axes.
277  */
278 typedef struct atp_pspan {
279 	u_int width;   /* in units of sensors */
280 	u_int cum;     /* cumulative compression (from all sensors) */
281 	u_int cog;     /* center of gravity */
282 	u_int loc;     /* location (scaled using the mickeys factor) */
283 	boolean_t matched; /* to track pspans as they match against strokes. */
284 } atp_pspan;
285 
286 typedef enum atp_stroke_type {
287 	ATP_STROKE_TOUCH,
288 	ATP_STROKE_SLIDE,
289 } atp_stroke_type;
290 
291 #define ATP_MAX_PSPANS_PER_AXIS 3
292 
293 typedef struct atp_stroke_component {
294 	/* Fields encapsulating the pressure-span. */
295 	u_int loc;              /* location (scaled) */
296 	u_int cum_pressure;     /* cumulative compression */
297 	u_int max_cum_pressure; /* max cumulative compression */
298 	boolean_t matched; /*to track components as they match against pspans.*/
299 
300 	/* Fields containing information about movement. */
301 	int   delta_mickeys;    /* change in location (un-smoothened movement)*/
302 	int   pending;          /* cum. of pending short movements */
303 	int   movement;         /* current smoothened movement */
304 } atp_stroke_component;
305 
306 typedef enum atp_axis {
307 	X = 0,
308 	Y = 1
309 } atp_axis;
310 
311 #define ATP_MAX_STROKES         (2 * ATP_MAX_PSPANS_PER_AXIS)
312 
313 /*
314  * The following structure captures a finger contact with the
315  * touchpad. A stroke comprises two p-span components and some state.
316  */
317 typedef struct atp_stroke {
318 	atp_stroke_type      type;
319 	struct timeval       ctime; /* create time; for coincident siblings. */
320 	u_int                age;   /*
321 				     * Unit: interrupts; we maintain
322 				     * this value in addition to
323 				     * 'ctime' in order to avoid the
324 				     * expensive call to microtime()
325 				     * at every interrupt.
326 				     */
327 
328 	atp_stroke_component components[2];
329 	u_int                velocity_squared; /*
330 						* Average magnitude (squared)
331 						* of recent velocity.
332 						*/
333 	u_int                cum_movement; /* cum. absolute movement so far */
334 
335 	uint32_t             flags;  /* the state of this stroke */
336 #define ATSF_ZOMBIE          0x1
337 } atp_stroke;
338 
339 #define ATP_FIFO_BUF_SIZE        8 /* bytes */
340 #define ATP_FIFO_QUEUE_MAXLEN   50 /* units */
341 
342 enum {
343 	ATP_INTR_DT,
344 	ATP_N_TRANSFER,
345 };
346 
347 struct atp_softc {
348 	device_t               sc_dev;
349 	struct usb_device     *sc_usb_device;
350 #define MODE_LENGTH 8
351 	char                   sc_mode_bytes[MODE_LENGTH]; /* device mode */
352 	struct mtx             sc_mutex; /* for synchronization */
353 	struct usb_xfer       *sc_xfer[ATP_N_TRANSFER];
354 	struct usb_fifo_sc     sc_fifo;
355 
356 	struct atp_dev_params *sc_params;
357 
358 	mousehw_t              sc_hw;
359 	mousemode_t            sc_mode;
360 	u_int                  sc_pollrate;
361 	mousestatus_t          sc_status;
362 	u_int                  sc_state;
363 #define ATP_ENABLED            0x01
364 #define ATP_ZOMBIES_EXIST      0x02
365 #define ATP_DOUBLE_TAP_DRAG    0x04
366 #define ATP_VALID              0x08
367 
368 	u_int                  sc_left_margin;
369 	u_int                  sc_right_margin;
370 
371 	atp_stroke             sc_strokes[ATP_MAX_STROKES];
372 	u_int                  sc_n_strokes;
373 
374 	int8_t                *sensor_data; /* from interrupt packet */
375 	int                   *base_x;      /* base sensor readings */
376 	int                   *base_y;
377 	int                   *cur_x;       /* current sensor readings */
378 	int                   *cur_y;
379 	int                   *pressure_x;  /* computed pressures */
380 	int                   *pressure_y;
381 
382 	u_int                  sc_idlecount; /* preceding idle interrupts */
383 #define ATP_IDLENESS_THRESHOLD 10
384 
385 	struct timeval         sc_reap_time;
386 	struct timeval         sc_reap_ctime; /*ctime of siblings to be reaped*/
387 };
388 
389 /*
390  * The last byte of the sensor data contains status bits; the
391  * following values define the meanings of these bits.
392  */
393 enum atp_status_bits {
394 	ATP_STATUS_BUTTON      = (uint8_t)0x01, /* The button was pressed */
395 	ATP_STATUS_BASE_UPDATE = (uint8_t)0x04, /* Data from an untouched pad.*/
396 };
397 
398 typedef enum interface_mode {
399 	RAW_SENSOR_MODE = (uint8_t)0x04,
400 	HID_MODE        = (uint8_t)0x08
401 } interface_mode;
402 
403 /*
404  * function prototypes
405  */
406 static usb_fifo_cmd_t   atp_start_read;
407 static usb_fifo_cmd_t   atp_stop_read;
408 static usb_fifo_open_t  atp_open;
409 static usb_fifo_close_t atp_close;
410 static usb_fifo_ioctl_t atp_ioctl;
411 
412 static struct usb_fifo_methods atp_fifo_methods = {
413 	.f_open       = &atp_open,
414 	.f_close      = &atp_close,
415 	.f_ioctl      = &atp_ioctl,
416 	.f_start_read = &atp_start_read,
417 	.f_stop_read  = &atp_stop_read,
418 	.basename[0]  = ATP_DRIVER_NAME,
419 };
420 
421 /* device initialization and shutdown */
422 static usb_error_t   atp_req_get_report(struct usb_device *udev, void *data);
423 static int           atp_set_device_mode(device_t dev, interface_mode mode);
424 static int           atp_enable(struct atp_softc *sc);
425 static void          atp_disable(struct atp_softc *sc);
426 static int           atp_softc_populate(struct atp_softc *);
427 static void          atp_softc_unpopulate(struct atp_softc *);
428 
429 /* sensor interpretation */
430 static __inline void atp_interpret_sensor_data(const int8_t *, u_int, atp_axis,
431 			 int *, atp_protocol);
432 static __inline void atp_get_pressures(int *, const int *, const int *, int);
433 static void          atp_detect_pspans(int *, u_int, u_int, atp_pspan *,
434 			 u_int *);
435 
436 /* movement detection */
437 static boolean_t     atp_match_stroke_component(atp_stroke_component *,
438 			 const atp_pspan *);
439 static void          atp_match_strokes_against_pspans(struct atp_softc *,
440 			 atp_axis, atp_pspan *, u_int, u_int);
441 static boolean_t     atp_update_strokes(struct atp_softc *,
442 			 atp_pspan *, u_int, atp_pspan *, u_int);
443 static __inline void atp_add_stroke(struct atp_softc *, const atp_pspan *,
444 			 const atp_pspan *);
445 static void          atp_add_new_strokes(struct atp_softc *, atp_pspan *,
446 			 u_int, atp_pspan *, u_int);
447 static void          atp_advance_stroke_state(struct atp_softc *,
448 			 atp_stroke *, boolean_t *);
449 static void          atp_terminate_stroke(struct atp_softc *, u_int);
450 static __inline boolean_t atp_stroke_has_small_movement(const atp_stroke *);
451 static __inline void atp_update_pending_mickeys(atp_stroke_component *);
452 static void          atp_compute_smoothening_scale_ratio(atp_stroke *, int *,
453 			 int *);
454 static boolean_t     atp_compute_stroke_movement(atp_stroke *);
455 
456 /* tap detection */
457 static __inline void atp_setup_reap_time(struct atp_softc *, struct timeval *);
458 static void          atp_reap_zombies(struct atp_softc *, u_int *, u_int *);
459 
460 /* updating fifo */
461 static void          atp_reset_buf(struct atp_softc *sc);
462 static void          atp_add_to_queue(struct atp_softc *, int, int, uint32_t);
463 
464 
465 usb_error_t
466 atp_req_get_report(struct usb_device *udev, void *data)
467 {
468 	struct usb_device_request req;
469 
470 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
471 	req.bRequest = UR_GET_REPORT;
472 	USETW2(req.wValue, (uint8_t)0x03 /* type */, (uint8_t)0x00 /* id */);
473 	USETW(req.wIndex, 0);
474 	USETW(req.wLength, MODE_LENGTH);
475 
476 	return (usbd_do_request(udev, NULL /* mutex */, &req, data));
477 }
478 
479 static int
480 atp_set_device_mode(device_t dev, interface_mode mode)
481 {
482 	struct atp_softc     *sc;
483 	usb_device_request_t  req;
484 	usb_error_t           err;
485 
486 	if ((mode != RAW_SENSOR_MODE) && (mode != HID_MODE))
487 		return (ENXIO);
488 
489 	sc = device_get_softc(dev);
490 
491 	sc->sc_mode_bytes[0] = mode;
492 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
493 	req.bRequest = UR_SET_REPORT;
494 	USETW2(req.wValue, (uint8_t)0x03 /* type */, (uint8_t)0x00 /* id */);
495 	USETW(req.wIndex, 0);
496 	USETW(req.wLength, MODE_LENGTH);
497 	err = usbd_do_request(sc->sc_usb_device, NULL, &req, sc->sc_mode_bytes);
498 	if (err != USB_ERR_NORMAL_COMPLETION)
499 		return (ENXIO);
500 
501 	return (0);
502 }
503 
504 static int
505 atp_enable(struct atp_softc *sc)
506 {
507 	/* Allocate the dynamic buffers */
508 	if (atp_softc_populate(sc) != 0) {
509 		atp_softc_unpopulate(sc);
510 		return (ENOMEM);
511 	}
512 
513 	/* reset status */
514 	memset(sc->sc_strokes, 0, sizeof(sc->sc_strokes));
515 	sc->sc_n_strokes = 0;
516 	memset(&sc->sc_status, 0, sizeof(sc->sc_status));
517 	sc->sc_idlecount = 0;
518 	sc->sc_state |= ATP_ENABLED;
519 
520 	DPRINTFN(ATP_LLEVEL_INFO, "enabled atp\n");
521 	return (0);
522 }
523 
524 static void
525 atp_disable(struct atp_softc *sc)
526 {
527 	atp_softc_unpopulate(sc);
528 
529 	sc->sc_state &= ~(ATP_ENABLED | ATP_VALID);
530 	DPRINTFN(ATP_LLEVEL_INFO, "disabled atp\n");
531 }
532 
533 /* Allocate dynamic memory for some fields in softc. */
534 static int
535 atp_softc_populate(struct atp_softc *sc)
536 {
537 	const struct atp_dev_params *params = sc->sc_params;
538 
539 	if (params == NULL) {
540 		DPRINTF("params uninitialized!\n");
541 		return (ENXIO);
542 	}
543 	if (params->data_len) {
544 		sc->sensor_data = malloc(params->data_len * sizeof(int8_t),
545 		    M_USB, M_WAITOK);
546 		if (sc->sensor_data == NULL) {
547 			DPRINTF("mem for sensor_data\n");
548 			return (ENXIO);
549 		}
550 	}
551 
552 	if (params->n_xsensors != 0) {
553 		sc->base_x = malloc(params->n_xsensors * sizeof(*(sc->base_x)),
554 		    M_USB, M_WAITOK);
555 		if (sc->base_x == NULL) {
556 			DPRINTF("mem for sc->base_x\n");
557 			return (ENXIO);
558 		}
559 
560 		sc->cur_x = malloc(params->n_xsensors * sizeof(*(sc->cur_x)),
561 		    M_USB, M_WAITOK);
562 		if (sc->cur_x == NULL) {
563 			DPRINTF("mem for sc->cur_x\n");
564 			return (ENXIO);
565 		}
566 
567 		sc->pressure_x =
568 			malloc(params->n_xsensors * sizeof(*(sc->pressure_x)),
569 			    M_USB, M_WAITOK);
570 		if (sc->pressure_x == NULL) {
571 			DPRINTF("mem. for pressure_x\n");
572 			return (ENXIO);
573 		}
574 	}
575 
576 	if (params->n_ysensors != 0) {
577 		sc->base_y = malloc(params->n_ysensors * sizeof(*(sc->base_y)),
578 		    M_USB, M_WAITOK);
579 		if (sc->base_y == NULL) {
580 			DPRINTF("mem for base_y\n");
581 			return (ENXIO);
582 		}
583 
584 		sc->cur_y = malloc(params->n_ysensors * sizeof(*(sc->cur_y)),
585 		    M_USB, M_WAITOK);
586 		if (sc->cur_y == NULL) {
587 			DPRINTF("mem for cur_y\n");
588 			return (ENXIO);
589 		}
590 
591 		sc->pressure_y =
592 			malloc(params->n_ysensors * sizeof(*(sc->pressure_y)),
593 			    M_USB, M_WAITOK);
594 		if (sc->pressure_y == NULL) {
595 			DPRINTF("mem. for pressure_y\n");
596 			return (ENXIO);
597 		}
598 	}
599 
600 	return (0);
601 }
602 
603 /* Free dynamic memory allocated for some fields in softc. */
604 static void
605 atp_softc_unpopulate(struct atp_softc *sc)
606 {
607 	const struct atp_dev_params *params = sc->sc_params;
608 
609 	if (params == NULL) {
610 		return;
611 	}
612 	if (params->n_xsensors != 0) {
613 		if (sc->base_x != NULL) {
614 			free(sc->base_x, M_USB);
615 			sc->base_x = NULL;
616 		}
617 
618 		if (sc->cur_x != NULL) {
619 			free(sc->cur_x, M_USB);
620 			sc->cur_x = NULL;
621 		}
622 
623 		if (sc->pressure_x != NULL) {
624 			free(sc->pressure_x, M_USB);
625 			sc->pressure_x = NULL;
626 		}
627 	}
628 	if (params->n_ysensors != 0) {
629 		if (sc->base_y != NULL) {
630 			free(sc->base_y, M_USB);
631 			sc->base_y = NULL;
632 		}
633 
634 		if (sc->cur_y != NULL) {
635 			free(sc->cur_y, M_USB);
636 			sc->cur_y = NULL;
637 		}
638 
639 		if (sc->pressure_y != NULL) {
640 			free(sc->pressure_y, M_USB);
641 			sc->pressure_y = NULL;
642 		}
643 	}
644 	if (sc->sensor_data != NULL) {
645 		free(sc->sensor_data, M_USB);
646 		sc->sensor_data = NULL;
647 	}
648 }
649 
650 /*
651  * Interpret the data from the X and Y pressure sensors. This function
652  * is called separately for the X and Y sensor arrays. The data in the
653  * USB packet is laid out in the following manner:
654  *
655  * sensor_data:
656  *            --,--,Y1,Y2,--,Y3,Y4,--,Y5,...,Y10, ... X1,X2,--,X3,X4
657  *  indices:   0  1  2  3  4  5  6  7  8 ...  15  ... 20 21 22 23 24
658  *
659  * '--' (in the above) indicates that the value is unimportant.
660  *
661  * Information about the above layout was obtained from the
662  * implementation of the AppleTouch driver in Linux.
663  *
664  * parameters:
665  *   sensor_data
666  *       raw sensor data from the USB packet.
667  *   num
668  *       The number of elements in the array 'arr'.
669  *   axis
670  *       Axis of data to fetch
671  *   arr
672  *       The array to be initialized with the readings.
673  *   prot
674  *       The protocol to use to interpret the data
675  */
676 static __inline void
677 atp_interpret_sensor_data(const int8_t *sensor_data, u_int num, atp_axis axis,
678     int	*arr, atp_protocol prot)
679 {
680 	u_int i;
681 	u_int di;   /* index into sensor data */
682 
683 	switch (prot) {
684 	case ATP_PROT_GEYSER1:
685 		/*
686 		 * For Geyser 1, the sensors are laid out in pairs
687 		 * every 5 bytes.
688 		 */
689 		for (i = 0, di = (axis == Y) ? 1 : 2; i < 8; di += 5, i++) {
690 			arr[i] = sensor_data[di];
691 			arr[i+8] = sensor_data[di+2];
692 			if (axis == X && num > 16)
693 				arr[i+16] = sensor_data[di+40];
694 		}
695 
696 		break;
697 	case ATP_PROT_GEYSER2:
698 	case ATP_PROT_GEYSER3:
699 		for (i = 0, di = (axis == Y) ? 2 : 20; i < num; /* empty */ ) {
700 			arr[i++] = sensor_data[di++];
701 			arr[i++] = sensor_data[di++];
702 			di++;
703 		}
704 		break;
705 	}
706 }
707 
708 static __inline void
709 atp_get_pressures(int *p, const int *cur, const int *base, int n)
710 {
711 	int i;
712 
713 	for (i = 0; i < n; i++) {
714 		p[i] = cur[i] - base[i];
715 		if (p[i] > 127)
716 			p[i] -= 256;
717 		if (p[i] < -127)
718 			p[i] += 256;
719 		if (p[i] < 0)
720 			p[i] = 0;
721 
722 		/*
723 		 * Shave off pressures below the noise-pressure
724 		 * threshold; this will reduce the contribution from
725 		 * lower pressure readings.
726 		 */
727 		if (p[i] <= atp_sensor_noise_threshold)
728 			p[i] = 0; /* filter away noise */
729 		else
730 			p[i] -= atp_sensor_noise_threshold;
731 	}
732 }
733 
734 static void
735 atp_detect_pspans(int *p, u_int num_sensors,
736     u_int       max_spans, /* max # of pspans permitted */
737     atp_pspan  *spans,     /* finger spans */
738     u_int      *nspans_p)  /* num spans detected */
739 {
740 	u_int i;
741 	int   maxp;             /* max pressure seen within a span */
742 	u_int num_spans = 0;
743 
744 	enum atp_pspan_state {
745 		ATP_PSPAN_INACTIVE,
746 		ATP_PSPAN_INCREASING,
747 		ATP_PSPAN_DECREASING,
748 	} state; /* state of the pressure span */
749 
750 	/*
751 	 * The following is a simple state machine to track
752 	 * the phase of the pressure span.
753 	 */
754 	memset(spans, 0, max_spans * sizeof(atp_pspan));
755 	maxp = 0;
756 	state = ATP_PSPAN_INACTIVE;
757 	for (i = 0; i < num_sensors; i++) {
758 		if (num_spans >= max_spans)
759 			break;
760 
761 		if (p[i] == 0) {
762 			if (state == ATP_PSPAN_INACTIVE) {
763 				/*
764 				 * There is no pressure information for this
765 				 * sensor, and we aren't tracking a finger.
766 				 */
767 				continue;
768 			} else {
769 				state = ATP_PSPAN_INACTIVE;
770 				maxp = 0;
771 				num_spans++;
772 			}
773 		} else {
774 			switch (state) {
775 			case ATP_PSPAN_INACTIVE:
776 				state = ATP_PSPAN_INCREASING;
777 				maxp  = p[i];
778 				break;
779 
780 			case ATP_PSPAN_INCREASING:
781 				if (p[i] > maxp)
782 					maxp = p[i];
783 				else if (p[i] <= (maxp >> 1))
784 					state = ATP_PSPAN_DECREASING;
785 				break;
786 
787 			case ATP_PSPAN_DECREASING:
788 				if (p[i] > p[i - 1]) {
789 					/*
790 					 * This is the beginning of
791 					 * another span; change state
792 					 * to give the appearance that
793 					 * we're starting from an
794 					 * inactive span, and then
795 					 * re-process this reading in
796 					 * the next iteration.
797 					 */
798 					num_spans++;
799 					state = ATP_PSPAN_INACTIVE;
800 					maxp  = 0;
801 					i--;
802 					continue;
803 				}
804 				break;
805 			}
806 
807 			/* Update the finger span with this reading. */
808 			spans[num_spans].width++;
809 			spans[num_spans].cum += p[i];
810 			spans[num_spans].cog += p[i] * (i + 1);
811 		}
812 	}
813 	if (state != ATP_PSPAN_INACTIVE)
814 		num_spans++;    /* close the last finger span */
815 
816 	/* post-process the spans */
817 	for (i = 0; i < num_spans; i++) {
818 		/* filter away unwanted pressure spans */
819 		if ((spans[i].cum < atp_pspan_min_cum_pressure) ||
820 		    (spans[i].width > atp_pspan_max_width)) {
821 			if ((i + 1) < num_spans) {
822 				memcpy(&spans[i], &spans[i + 1],
823 				    (num_spans - i - 1) * sizeof(atp_pspan));
824 				i--;
825 			}
826 			num_spans--;
827 			continue;
828 		}
829 
830 		/* compute this span's representative location */
831 		spans[i].loc = spans[i].cog * atp_mickeys_scale_factor /
832 			spans[i].cum;
833 
834 		spans[i].matched = FALSE; /* not yet matched against a stroke */
835 	}
836 
837 	*nspans_p = num_spans;
838 }
839 
840 /*
841  * Match a pressure-span against a stroke-component. If there is a
842  * match, update the component's state and return TRUE.
843  */
844 static boolean_t
845 atp_match_stroke_component(atp_stroke_component *component,
846     const atp_pspan *pspan)
847 {
848 	int delta_mickeys = pspan->loc - component->loc;
849 
850 	if (abs(delta_mickeys) > atp_max_delta_mickeys)
851 		return (FALSE); /* the finger span is too far out; no match */
852 
853 	component->loc          = pspan->loc;
854 	component->cum_pressure = pspan->cum;
855 	if (pspan->cum > component->max_cum_pressure)
856 		component->max_cum_pressure = pspan->cum;
857 
858 	/*
859 	 * If the cumulative pressure drops below a quarter of the max,
860 	 * then disregard the component's movement.
861 	 */
862 	if (component->cum_pressure < (component->max_cum_pressure >> 2))
863 		delta_mickeys = 0;
864 
865 	component->delta_mickeys = delta_mickeys;
866 	return (TRUE);
867 }
868 
869 static void
870 atp_match_strokes_against_pspans(struct atp_softc *sc, atp_axis axis,
871     atp_pspan *pspans, u_int n_pspans, u_int repeat_count)
872 {
873 	u_int i, j;
874 	u_int repeat_index = 0;
875 
876 	/* Determine the index of the multi-span. */
877 	if (repeat_count) {
878 		u_int cum = 0;
879 		for (i = 0; i < n_pspans; i++) {
880 			if (pspans[i].cum > cum) {
881 				repeat_index = i;
882 				cum = pspans[i].cum;
883 			}
884 		}
885 	}
886 
887 	for (i = 0; i < sc->sc_n_strokes; i++) {
888 		atp_stroke *stroke  = &sc->sc_strokes[i];
889 		if (stroke->components[axis].matched)
890 			continue; /* skip matched components */
891 
892 		for (j = 0; j < n_pspans; j++) {
893 			if (pspans[j].matched)
894 				continue; /* skip matched pspans */
895 
896 			if (atp_match_stroke_component(
897 				    &stroke->components[axis], &pspans[j])) {
898 				/* There is a match. */
899 				stroke->components[axis].matched = TRUE;
900 
901 				/* Take care to repeat at the multi-span. */
902 				if ((repeat_count > 0) && (j == repeat_index))
903 					repeat_count--;
904 				else
905 					pspans[j].matched = TRUE;
906 
907 				break; /* skip to the next stroke */
908 			}
909 		} /* loop over pspans */
910 	} /* loop over strokes */
911 }
912 
913 /*
914  * Update strokes by matching against current pressure-spans.
915  * Return TRUE if any movement is detected.
916  */
917 static boolean_t
918 atp_update_strokes(struct atp_softc *sc, atp_pspan *pspans_x,
919     u_int n_xpspans, atp_pspan *pspans_y, u_int n_ypspans)
920 {
921 	u_int       i, j;
922 	atp_stroke *stroke;
923 	boolean_t   movement = FALSE;
924 	u_int       repeat_count = 0;
925 
926 	/* Reset X and Y components of all strokes as unmatched. */
927 	for (i = 0; i < sc->sc_n_strokes; i++) {
928 		stroke = &sc->sc_strokes[i];
929 		stroke->components[X].matched = FALSE;
930 		stroke->components[Y].matched = FALSE;
931 	}
932 
933 	/*
934 	 * Usually, the X and Y pspans come in pairs (the common case
935 	 * being a single pair). It is possible, however, that
936 	 * multiple contacts resolve to a single pspan along an
937 	 * axis, as illustrated in the following:
938 	 *
939 	 *   F = finger-contact
940 	 *
941 	 *                pspan  pspan
942 	 *        +-----------------------+
943 	 *        |         .      .      |
944 	 *        |         .      .      |
945 	 *        |         .      .      |
946 	 *        |         .      .      |
947 	 *  pspan |.........F......F      |
948 	 *        |                       |
949 	 *        |                       |
950 	 *        |                       |
951 	 *        +-----------------------+
952 	 *
953 	 *
954 	 * The above case can be detected by a difference in the
955 	 * number of X and Y pspans. When this happens, X and Y pspans
956 	 * aren't easy to pair or match against strokes.
957 	 *
958 	 * When X and Y pspans differ in number, the axis with the
959 	 * smaller number of pspans is regarded as having a repeating
960 	 * pspan (or a multi-pspan)--in the above illustration, the
961 	 * Y-axis has a repeating pspan. Our approach is to try to
962 	 * match the multi-pspan repeatedly against strokes. The
963 	 * difference between the number of X and Y pspans gives us a
964 	 * crude repeat_count for matching multi-pspans--i.e. the
965 	 * multi-pspan along the Y axis (above) has a repeat_count of 1.
966 	 */
967 	repeat_count = abs(n_xpspans - n_ypspans);
968 
969 	atp_match_strokes_against_pspans(sc, X, pspans_x, n_xpspans,
970 	    (((repeat_count != 0) && ((n_xpspans < n_ypspans))) ?
971 		repeat_count : 0));
972 	atp_match_strokes_against_pspans(sc, Y, pspans_y, n_ypspans,
973 	    (((repeat_count != 0) && (n_ypspans < n_xpspans)) ?
974 		repeat_count : 0));
975 
976 	/* Update the state of strokes based on the above pspan matches. */
977 	for (i = 0; i < sc->sc_n_strokes; i++) {
978 		stroke = &sc->sc_strokes[i];
979 		if (stroke->components[X].matched &&
980 		    stroke->components[Y].matched) {
981 			atp_advance_stroke_state(sc, stroke, &movement);
982 		} else {
983 			/*
984 			 * At least one component of this stroke
985 			 * didn't match against current pspans;
986 			 * terminate it.
987 			 */
988 			atp_terminate_stroke(sc, i);
989 		}
990 	}
991 
992 	/* Add new strokes for pairs of unmatched pspans */
993 	for (i = 0; i < n_xpspans; i++) {
994 		if (pspans_x[i].matched == FALSE) break;
995 	}
996 	for (j = 0; j < n_ypspans; j++) {
997 		if (pspans_y[j].matched == FALSE) break;
998 	}
999 	if ((i < n_xpspans) && (j < n_ypspans)) {
1000 #if USB_DEBUG
1001 		if (atp_debug >= ATP_LLEVEL_INFO) {
1002 			printf("unmatched pspans:");
1003 			for (; i < n_xpspans; i++) {
1004 				if (pspans_x[i].matched)
1005 					continue;
1006 				printf(" X:[loc:%u,cum:%u]",
1007 				    pspans_x[i].loc, pspans_x[i].cum);
1008 			}
1009 			for (; j < n_ypspans; j++) {
1010 				if (pspans_y[j].matched)
1011 					continue;
1012 				printf(" Y:[loc:%u,cum:%u]",
1013 				    pspans_y[j].loc, pspans_y[j].cum);
1014 			}
1015 			printf("\n");
1016 		}
1017 #endif /* #if USB_DEBUG */
1018 		if ((n_xpspans == 1) && (n_ypspans == 1))
1019 			/* The common case of a single pair of new pspans. */
1020 			atp_add_stroke(sc, &pspans_x[0], &pspans_y[0]);
1021 		else
1022 			atp_add_new_strokes(sc,
1023 			    pspans_x, n_xpspans,
1024 			    pspans_y, n_ypspans);
1025 	}
1026 
1027 #if USB_DEBUG
1028 	if (atp_debug >= ATP_LLEVEL_INFO) {
1029 		for (i = 0; i < sc->sc_n_strokes; i++) {
1030 			atp_stroke *stroke = &sc->sc_strokes[i];
1031 
1032 			printf(" %s%clc:%u,dm:%d,pnd:%d,mv:%d%c"
1033 			    ",%clc:%u,dm:%d,pnd:%d,mv:%d%c",
1034 			    (stroke->flags & ATSF_ZOMBIE) ? "zomb:" : "",
1035 			    (stroke->type == ATP_STROKE_TOUCH) ? '[' : '<',
1036 			    stroke->components[X].loc,
1037 			    stroke->components[X].delta_mickeys,
1038 			    stroke->components[X].pending,
1039 			    stroke->components[X].movement,
1040 			    (stroke->type == ATP_STROKE_TOUCH) ? ']' : '>',
1041 			    (stroke->type == ATP_STROKE_TOUCH) ? '[' : '<',
1042 			    stroke->components[Y].loc,
1043 			    stroke->components[Y].delta_mickeys,
1044 			    stroke->components[Y].pending,
1045 			    stroke->components[Y].movement,
1046 			    (stroke->type == ATP_STROKE_TOUCH) ? ']' : '>');
1047 		}
1048 		if (sc->sc_n_strokes)
1049 			printf("\n");
1050 	}
1051 #endif /* #if USB_DEBUG */
1052 
1053 	return (movement);
1054 }
1055 
1056 /* Initialize a stroke using a pressure-span. */
1057 static __inline void
1058 atp_add_stroke(struct atp_softc *sc, const atp_pspan *pspan_x,
1059     const atp_pspan *pspan_y)
1060 {
1061 	atp_stroke *stroke;
1062 
1063 	if (sc->sc_n_strokes >= ATP_MAX_STROKES)
1064 		return;
1065 	stroke = &sc->sc_strokes[sc->sc_n_strokes];
1066 
1067 	memset(stroke, 0, sizeof(atp_stroke));
1068 
1069 	/*
1070 	 * Strokes begin as potential touches. If a stroke survives
1071 	 * longer than a threshold, or if it records significant
1072 	 * cumulative movement, then it is considered a 'slide'.
1073 	 */
1074 	stroke->type = ATP_STROKE_TOUCH;
1075 	microtime(&stroke->ctime);
1076 	stroke->age  = 1;       /* Unit: interrupts */
1077 
1078 	stroke->components[X].loc              = pspan_x->loc;
1079 	stroke->components[X].cum_pressure     = pspan_x->cum;
1080 	stroke->components[X].max_cum_pressure = pspan_x->cum;
1081 	stroke->components[X].matched          = TRUE;
1082 
1083 	stroke->components[Y].loc              = pspan_y->loc;
1084 	stroke->components[Y].cum_pressure     = pspan_y->cum;
1085 	stroke->components[Y].max_cum_pressure = pspan_y->cum;
1086 	stroke->components[Y].matched          = TRUE;
1087 
1088 	sc->sc_n_strokes++;
1089 	if (sc->sc_n_strokes > 1) {
1090 		/* Reset double-tap-n-drag if we have more than one strokes. */
1091 		sc->sc_state &= ~ATP_DOUBLE_TAP_DRAG;
1092 	}
1093 
1094 	DPRINTFN(ATP_LLEVEL_INFO, "[%u,%u], time: %u,%ld\n",
1095 	    stroke->components[X].loc,
1096 	    stroke->components[Y].loc,
1097 	    (unsigned int)stroke->ctime.tv_sec,
1098 	    (unsigned long int)stroke->ctime.tv_usec);
1099 }
1100 
1101 static void
1102 atp_add_new_strokes(struct atp_softc *sc, atp_pspan *pspans_x,
1103     u_int n_xpspans, atp_pspan *pspans_y, u_int n_ypspans)
1104 {
1105 	int       i, j;
1106 	atp_pspan spans[2][ATP_MAX_PSPANS_PER_AXIS];
1107 	u_int     nspans[2];
1108 
1109 	/* Copy unmatched pspans into the local arrays. */
1110 	for (i = 0, nspans[X] = 0; i < n_xpspans; i++) {
1111 		if (pspans_x[i].matched == FALSE) {
1112 			spans[X][nspans[X]] = pspans_x[i];
1113 			nspans[X]++;
1114 		}
1115 	}
1116 	for (j = 0, nspans[Y] = 0; j < n_ypspans; j++) {
1117 		if (pspans_y[j].matched == FALSE) {
1118 			spans[Y][nspans[Y]] = pspans_y[j];
1119 			nspans[Y]++;
1120 		}
1121 	}
1122 
1123 	if (nspans[X] == nspans[Y]) {
1124 		/* Create new strokes from pairs of unmatched pspans */
1125 		for (i = 0, j = 0; (i < nspans[X]) && (j < nspans[Y]); i++, j++)
1126 			atp_add_stroke(sc, &spans[X][i], &spans[Y][j]);
1127 	} else {
1128 		u_int    cum = 0;
1129 		atp_axis repeat_axis;      /* axis with multi-pspans */
1130 		u_int    repeat_count;     /* repeat count for the multi-pspan*/
1131 		u_int    repeat_index = 0; /* index of the multi-span */
1132 
1133 		repeat_axis  = (nspans[X] > nspans[Y]) ? Y : X;
1134 		repeat_count = abs(nspans[X] - nspans[Y]);
1135 		for (i = 0; i < nspans[repeat_axis]; i++) {
1136 			if (spans[repeat_axis][i].cum > cum) {
1137 				repeat_index = i;
1138 				cum = spans[repeat_axis][i].cum;
1139 			}
1140 		}
1141 
1142 		/* Create new strokes from pairs of unmatched pspans */
1143 		i = 0, j = 0;
1144 		for (; (i < nspans[X]) && (j < nspans[Y]); i++, j++) {
1145 			atp_add_stroke(sc, &spans[X][i], &spans[Y][j]);
1146 
1147 			/* Take care to repeat at the multi-pspan. */
1148 			if (repeat_count > 0) {
1149 				if ((repeat_axis == X) &&
1150 				    (repeat_index == i)) {
1151 					i--; /* counter loop increment */
1152 					repeat_count--;
1153 				} else if ((repeat_axis == Y) &&
1154 				    (repeat_index == j)) {
1155 					j--; /* counter loop increment */
1156 					repeat_count--;
1157 				}
1158 			}
1159 		}
1160 	}
1161 }
1162 
1163 /*
1164  * Advance the state of this stroke--and update the out-parameter
1165  * 'movement' as a side-effect.
1166  */
1167 void
1168 atp_advance_stroke_state(struct atp_softc *sc, atp_stroke *stroke,
1169     boolean_t *movement)
1170 {
1171 	stroke->age++;
1172 	if (stroke->age <= atp_stroke_maturity_threshold) {
1173 		/* Avoid noise from immature strokes. */
1174 		stroke->components[X].delta_mickeys = 0;
1175 		stroke->components[Y].delta_mickeys = 0;
1176 	}
1177 
1178 	/* Revitalize stroke if it had previously been marked as a zombie. */
1179 	if (stroke->flags & ATSF_ZOMBIE)
1180 		stroke->flags &= ~ATSF_ZOMBIE;
1181 
1182 	if (atp_compute_stroke_movement(stroke))
1183 		*movement = TRUE;
1184 
1185 	/* Convert touch strokes to slides upon detecting movement or age. */
1186 	if (stroke->type == ATP_STROKE_TOUCH) {
1187 		struct timeval tdiff;
1188 
1189 		/* Compute the stroke's age. */
1190 		getmicrotime(&tdiff);
1191 		if (timevalcmp(&tdiff, &stroke->ctime, >))
1192 			timevalsub(&tdiff, &stroke->ctime);
1193 		else {
1194 			/*
1195 			 * If we are here, it is because getmicrotime
1196 			 * reported the current time as being behind
1197 			 * the stroke's start time; getmicrotime can
1198 			 * be imprecise.
1199 			 */
1200 			tdiff.tv_sec  = 0;
1201 			tdiff.tv_usec = 0;
1202 		}
1203 
1204 		if ((tdiff.tv_sec > (atp_touch_timeout / 1000000)) ||
1205 		    ((tdiff.tv_sec == (atp_touch_timeout / 1000000)) &&
1206 			(tdiff.tv_usec > atp_touch_timeout)) ||
1207 		    (stroke->cum_movement >= atp_slide_min_movement)) {
1208 			/* Switch this stroke to being a slide. */
1209 			stroke->type = ATP_STROKE_SLIDE;
1210 
1211 			/* Are we at the beginning of a double-click-n-drag? */
1212 			if ((sc->sc_n_strokes == 1) &&
1213 			    ((sc->sc_state & ATP_ZOMBIES_EXIST) == 0) &&
1214 			    timevalcmp(&stroke->ctime, &sc->sc_reap_time, >)) {
1215 				struct timeval delta;
1216 				struct timeval window = {
1217 					atp_double_tap_threshold / 1000000,
1218 					atp_double_tap_threshold % 1000000
1219 				};
1220 
1221 				delta = stroke->ctime;
1222 				timevalsub(&delta, &sc->sc_reap_time);
1223 				if (timevalcmp(&delta, &window, <=))
1224 					sc->sc_state |= ATP_DOUBLE_TAP_DRAG;
1225 			}
1226 		}
1227 	}
1228 }
1229 
1230 /*
1231  * Terminate a stroke. While SLIDE strokes are dropped, TOUCH strokes
1232  * are retained as zombies so as to reap all their siblings together;
1233  * this helps establish the number of fingers involved in the tap.
1234  */
1235 static void
1236 atp_terminate_stroke(struct atp_softc *sc,
1237     u_int index) /* index of the stroke to be terminated */
1238 {
1239 	atp_stroke *s = &sc->sc_strokes[index];
1240 
1241 	if (s->flags & ATSF_ZOMBIE) {
1242 		return;
1243 	}
1244 
1245 	if ((s->type == ATP_STROKE_TOUCH) &&
1246 	    (s->age > atp_stroke_maturity_threshold)) {
1247 		s->flags |= ATSF_ZOMBIE;
1248 
1249 		/* If no zombies exist, then prepare to reap zombies later. */
1250 		if ((sc->sc_state & ATP_ZOMBIES_EXIST) == 0) {
1251 			atp_setup_reap_time(sc, &s->ctime);
1252 			sc->sc_state |= ATP_ZOMBIES_EXIST;
1253 		}
1254 	} else {
1255 		/* Drop this stroke. */
1256 		memcpy(&sc->sc_strokes[index], &sc->sc_strokes[index + 1],
1257 		    (sc->sc_n_strokes - index - 1) * sizeof(atp_stroke));
1258 		sc->sc_n_strokes--;
1259 
1260 		/*
1261 		 * Reset the double-click-n-drag at the termination of
1262 		 * any slide stroke.
1263 		 */
1264 		sc->sc_state &= ~ATP_DOUBLE_TAP_DRAG;
1265 	}
1266 }
1267 
1268 static __inline boolean_t
1269 atp_stroke_has_small_movement(const atp_stroke *stroke)
1270 {
1271 	return ((abs(stroke->components[X].delta_mickeys) <=
1272 		atp_small_movement_threshold) &&
1273 	    (abs(stroke->components[Y].delta_mickeys) <=
1274 		atp_small_movement_threshold));
1275 }
1276 
1277 /*
1278  * Accumulate delta_mickeys into the component's 'pending' bucket; if
1279  * the aggregate exceeds the small_movement_threshold, then retain
1280  * delta_mickeys for later.
1281  */
1282 static __inline void
1283 atp_update_pending_mickeys(atp_stroke_component *component)
1284 {
1285 	component->pending += component->delta_mickeys;
1286 	if (abs(component->pending) <= atp_small_movement_threshold)
1287 		component->delta_mickeys = 0;
1288 	else {
1289 		/*
1290 		 * Penalise pending mickeys for having accumulated
1291 		 * over short deltas. This operation has the effect of
1292 		 * scaling down the cumulative contribution of short
1293 		 * movements.
1294 		 */
1295 		component->pending -= (component->delta_mickeys << 1);
1296 	}
1297 }
1298 
1299 
1300 static void
1301 atp_compute_smoothening_scale_ratio(atp_stroke *stroke, int *numerator,
1302     int *denominator)
1303 {
1304 	int   dxdt;
1305 	int   dydt;
1306 	u_int vel_squared; /* Square of the velocity vector's magnitude. */
1307 	u_int vel_squared_smooth;
1308 
1309 	/* Table holding (10 * sqrt(x)) for x between 1 and 256. */
1310 	static uint8_t sqrt_table[256] = {
1311 		10, 14, 17, 20, 22, 24, 26, 28,
1312 		30, 31, 33, 34, 36, 37, 38, 40,
1313 		41, 42, 43, 44, 45, 46, 47, 48,
1314 		50, 50, 51, 52, 53, 54, 55, 56,
1315 		57, 58, 59, 60, 60, 61, 62, 63,
1316 		64, 64, 65, 66, 67, 67, 68, 69,
1317 		70, 70, 71, 72, 72, 73, 74, 74,
1318 		75, 76, 76, 77, 78, 78, 79, 80,
1319 		80, 81, 81, 82, 83, 83, 84, 84,
1320 		85, 86, 86, 87, 87, 88, 88, 89,
1321 		90, 90, 91, 91, 92, 92, 93, 93,
1322 		94, 94, 95, 95, 96, 96, 97, 97,
1323 		98, 98, 99, 100, 100, 100, 101, 101,
1324 		102, 102, 103, 103, 104, 104, 105, 105,
1325 		106, 106, 107, 107, 108, 108, 109, 109,
1326 		110, 110, 110, 111, 111, 112, 112, 113,
1327 		113, 114, 114, 114, 115, 115, 116, 116,
1328 		117, 117, 117, 118, 118, 119, 119, 120,
1329 		120, 120, 121, 121, 122, 122, 122, 123,
1330 		123, 124, 124, 124, 125, 125, 126, 126,
1331 		126, 127, 127, 128, 128, 128, 129, 129,
1332 		130, 130, 130, 131, 131, 131, 132, 132,
1333 		133, 133, 133, 134, 134, 134, 135, 135,
1334 		136, 136, 136, 137, 137, 137, 138, 138,
1335 		138, 139, 139, 140, 140, 140, 141, 141,
1336 		141, 142, 142, 142, 143, 143, 143, 144,
1337 		144, 144, 145, 145, 145, 146, 146, 146,
1338 		147, 147, 147, 148, 148, 148, 149, 149,
1339 		150, 150, 150, 150, 151, 151, 151, 152,
1340 		152, 152, 153, 153, 153, 154, 154, 154,
1341 		155, 155, 155, 156, 156, 156, 157, 157,
1342 		157, 158, 158, 158, 159, 159, 159, 160
1343 	};
1344 	const u_int N = sizeof(sqrt_table) / sizeof(sqrt_table[0]);
1345 
1346 	dxdt = stroke->components[X].delta_mickeys;
1347 	dydt = stroke->components[Y].delta_mickeys;
1348 
1349 	*numerator = 0, *denominator = 0; /* default values. */
1350 
1351 	/* Compute a smoothened magnitude_squared of the stroke's velocity. */
1352 	vel_squared = dxdt * dxdt + dydt * dydt;
1353 	vel_squared_smooth = (3 * stroke->velocity_squared + vel_squared) >> 2;
1354 	stroke->velocity_squared = vel_squared_smooth; /* retained as history */
1355 	if ((vel_squared == 0) || (vel_squared_smooth == 0))
1356 		return; /* returning (numerator == 0) will imply zero movement*/
1357 
1358 	/*
1359 	 * In order to determine the overall movement scale factor,
1360 	 * we're actually interested in the effect of smoothening upon
1361 	 * the *magnitude* of velocity; i.e. we need to compute the
1362 	 * square-root of (vel_squared_smooth / vel_squared) in the
1363 	 * form of a numerator and denominator.
1364 	 */
1365 
1366 	/* Keep within the bounds of the square-root table. */
1367 	while ((vel_squared > N) || (vel_squared_smooth > N)) {
1368 		/* Dividing uniformly by 2 won't disturb the final ratio. */
1369 		vel_squared        >>= 1;
1370 		vel_squared_smooth >>= 1;
1371 	}
1372 
1373 	*numerator   = sqrt_table[vel_squared_smooth - 1];
1374 	*denominator = sqrt_table[vel_squared - 1];
1375 }
1376 
1377 /*
1378  * Compute a smoothened value for the stroke's movement from
1379  * delta_mickeys in the X and Y components.
1380  */
1381 static boolean_t
1382 atp_compute_stroke_movement(atp_stroke *stroke)
1383 {
1384 	int   num;              /* numerator of scale ratio */
1385 	int   denom;            /* denominator of scale ratio */
1386 
1387 	/*
1388 	 * Short movements are added first to the 'pending' bucket,
1389 	 * and then acted upon only when their aggregate exceeds a
1390 	 * threshold. This has the effect of filtering away movement
1391 	 * noise.
1392 	 */
1393 	if (atp_stroke_has_small_movement(stroke)) {
1394 		atp_update_pending_mickeys(&stroke->components[X]);
1395 		atp_update_pending_mickeys(&stroke->components[Y]);
1396 	} else {                /* large movement */
1397 		/* clear away any pending mickeys if there are large movements*/
1398 		stroke->components[X].pending = 0;
1399 		stroke->components[Y].pending = 0;
1400 	}
1401 
1402 	/* Get the scale ratio and smoothen movement. */
1403 	atp_compute_smoothening_scale_ratio(stroke, &num, &denom);
1404 	if ((num == 0) || (denom == 0)) {
1405 		stroke->components[X].movement = 0;
1406 		stroke->components[Y].movement = 0;
1407 		stroke->velocity_squared >>= 1; /* Erode velocity_squared. */
1408 	} else {
1409 		stroke->components[X].movement =
1410 			(stroke->components[X].delta_mickeys * num) / denom;
1411 		stroke->components[Y].movement =
1412 			(stroke->components[Y].delta_mickeys * num) / denom;
1413 
1414 		stroke->cum_movement +=
1415 			abs(stroke->components[X].movement) +
1416 			abs(stroke->components[Y].movement);
1417 	}
1418 
1419 	return ((stroke->components[X].movement != 0) ||
1420 	    (stroke->components[Y].movement != 0));
1421 }
1422 
1423 static __inline void
1424 atp_setup_reap_time(struct atp_softc *sc, struct timeval *tvp)
1425 {
1426 	struct timeval reap_window = {
1427 		ATP_ZOMBIE_STROKE_REAP_WINDOW / 1000000,
1428 		ATP_ZOMBIE_STROKE_REAP_WINDOW % 1000000
1429 	};
1430 
1431 	microtime(&sc->sc_reap_time);
1432 	timevaladd(&sc->sc_reap_time, &reap_window);
1433 
1434 	sc->sc_reap_ctime = *tvp; /* ctime to reap */
1435 }
1436 
1437 static void
1438 atp_reap_zombies(struct atp_softc *sc, u_int *n_reaped, u_int *reaped_xlocs)
1439 {
1440 	u_int       i;
1441 	atp_stroke *stroke;
1442 
1443 	*n_reaped = 0;
1444 	for (i = 0; i < sc->sc_n_strokes; i++) {
1445 		struct timeval  tdiff;
1446 
1447 		stroke = &sc->sc_strokes[i];
1448 
1449 		if ((stroke->flags & ATSF_ZOMBIE) == 0)
1450 			continue;
1451 
1452 		/* Compare this stroke's ctime with the ctime being reaped. */
1453 		if (timevalcmp(&stroke->ctime, &sc->sc_reap_ctime, >=)) {
1454 			tdiff = stroke->ctime;
1455 			timevalsub(&tdiff, &sc->sc_reap_ctime);
1456 		} else {
1457 			tdiff = sc->sc_reap_ctime;
1458 			timevalsub(&tdiff, &stroke->ctime);
1459 		}
1460 
1461 		if ((tdiff.tv_sec > (ATP_COINCIDENCE_THRESHOLD / 1000000)) ||
1462 		    ((tdiff.tv_sec == (ATP_COINCIDENCE_THRESHOLD / 1000000)) &&
1463 		     (tdiff.tv_usec > (ATP_COINCIDENCE_THRESHOLD % 1000000)))) {
1464 			continue; /* Skip non-siblings. */
1465 		}
1466 
1467 		/*
1468 		 * Reap this sibling zombie stroke.
1469 		 */
1470 
1471 		if (reaped_xlocs != NULL)
1472 			reaped_xlocs[*n_reaped] = stroke->components[X].loc;
1473 
1474 		/* Erase the stroke from the sc. */
1475 		memcpy(&stroke[i], &stroke[i + 1],
1476 		    (sc->sc_n_strokes - i - 1) * sizeof(atp_stroke));
1477 		sc->sc_n_strokes--;
1478 
1479 		*n_reaped += 1;
1480 		--i; /* Decr. i to keep it unchanged for the next iteration */
1481 	}
1482 
1483 	DPRINTFN(ATP_LLEVEL_INFO, "reaped %u zombies\n", *n_reaped);
1484 
1485 	/* There could still be zombies remaining in the system. */
1486 	for (i = 0; i < sc->sc_n_strokes; i++) {
1487 		stroke = &sc->sc_strokes[i];
1488 		if (stroke->flags & ATSF_ZOMBIE) {
1489 			DPRINTFN(ATP_LLEVEL_INFO, "zombies remain!\n");
1490 			atp_setup_reap_time(sc, &stroke->ctime);
1491 			return;
1492 		}
1493 	}
1494 
1495 	/* If we reach here, then no more zombies remain. */
1496 	sc->sc_state &= ~ATP_ZOMBIES_EXIST;
1497 }
1498 
1499 
1500 /* Device methods. */
1501 static device_probe_t  atp_probe;
1502 static device_attach_t atp_attach;
1503 static device_detach_t atp_detach;
1504 static usb_callback_t  atp_intr;
1505 
1506 static const struct usb_config atp_config[ATP_N_TRANSFER] = {
1507 	[ATP_INTR_DT] = {
1508 		.type      = UE_INTERRUPT,
1509 		.endpoint  = UE_ADDR_ANY,
1510 		.direction = UE_DIR_IN,
1511 		.flags = {
1512 			.pipe_bof = 1,
1513 			.short_xfer_ok = 1,
1514 		},
1515 		.bufsize   = 0, /* use wMaxPacketSize */
1516 		.callback  = &atp_intr,
1517 	},
1518 };
1519 
1520 static int
1521 atp_probe(device_t self)
1522 {
1523 	struct usb_attach_arg *uaa = device_get_ivars(self);
1524 
1525 	if (uaa->usb_mode != USB_MODE_HOST)
1526 		return (ENXIO);
1527 
1528 	if ((uaa->info.bInterfaceClass != UICLASS_HID) ||
1529 	    (uaa->info.bInterfaceProtocol != UIPROTO_MOUSE))
1530 		return (ENXIO);
1531 
1532 	if (usbd_lookup_id_by_uaa(atp_devs, sizeof(atp_devs), uaa) == 0)
1533 		return BUS_PROBE_SPECIFIC;
1534 	else
1535 		return ENXIO;
1536 }
1537 
1538 static int
1539 atp_attach(device_t dev)
1540 {
1541 	struct atp_softc      *sc = device_get_softc(dev);
1542 	struct usb_attach_arg *uaa = device_get_ivars(dev);
1543 	usb_error_t            err;
1544 
1545 	/* ensure that the probe was successful */
1546 	if (uaa->driver_info >= ATP_N_DEV_PARAMS) {
1547 		DPRINTF("device probe returned bad id: %lu\n",
1548 		    uaa->driver_info);
1549 		return (ENXIO);
1550 	}
1551 	DPRINTFN(ATP_LLEVEL_INFO, "sc=%p\n", sc);
1552 
1553 	sc->sc_dev        = dev;
1554 	sc->sc_usb_device = uaa->device;
1555 
1556 	/*
1557 	 * By default the touchpad behaves like an HID device, sending
1558 	 * packets with reportID = 2. Such reports contain only
1559 	 * limited information--they encode movement deltas and button
1560 	 * events,--but do not include data from the pressure
1561 	 * sensors. The device input mode can be switched from HID
1562 	 * reports to raw sensor data using vendor-specific USB
1563 	 * control commands; but first the mode must be read.
1564 	 */
1565 	err = atp_req_get_report(sc->sc_usb_device, sc->sc_mode_bytes);
1566 	if (err != USB_ERR_NORMAL_COMPLETION) {
1567 		DPRINTF("failed to read device mode (%d)\n", err);
1568 		return (ENXIO);
1569 	}
1570 
1571 	if (atp_set_device_mode(dev, RAW_SENSOR_MODE) != 0) {
1572 		DPRINTF("failed to set mode to 'RAW_SENSOR' (%d)\n", err);
1573 		return (ENXIO);
1574 	}
1575 
1576 	mtx_init(&sc->sc_mutex, "atpmtx", NULL, MTX_DEF | MTX_RECURSE);
1577 
1578 	err = usbd_transfer_setup(uaa->device,
1579 	    &uaa->info.bIfaceIndex, sc->sc_xfer, atp_config,
1580 	    ATP_N_TRANSFER, sc, &sc->sc_mutex);
1581 
1582 	if (err) {
1583 		DPRINTF("error=%s\n", usbd_errstr(err));
1584 		goto detach;
1585 	}
1586 
1587 	if (usb_fifo_attach(sc->sc_usb_device, sc, &sc->sc_mutex,
1588 		&atp_fifo_methods, &sc->sc_fifo,
1589 		device_get_unit(dev), 0 - 1, uaa->info.bIfaceIndex,
1590 		UID_ROOT, GID_OPERATOR, 0644)) {
1591 		goto detach;
1592 	}
1593 
1594 	device_set_usb_desc(dev);
1595 
1596 	sc->sc_params           = &atp_dev_params[uaa->driver_info];
1597 
1598 	sc->sc_hw.buttons       = 3;
1599 	sc->sc_hw.iftype        = MOUSE_IF_USB;
1600 	sc->sc_hw.type          = MOUSE_PAD;
1601 	sc->sc_hw.model         = MOUSE_MODEL_GENERIC;
1602 	sc->sc_hw.hwid          = 0;
1603 	sc->sc_mode.protocol    = MOUSE_PROTO_MSC;
1604 	sc->sc_mode.rate        = -1;
1605 	sc->sc_mode.resolution  = MOUSE_RES_UNKNOWN;
1606 	sc->sc_mode.accelfactor = 0;
1607 	sc->sc_mode.level       = 0;
1608 	sc->sc_mode.packetsize  = MOUSE_MSC_PACKETSIZE;
1609 	sc->sc_mode.syncmask[0] = MOUSE_MSC_SYNCMASK;
1610 	sc->sc_mode.syncmask[1] = MOUSE_MSC_SYNC;
1611 
1612 	sc->sc_state            = 0;
1613 
1614 	sc->sc_left_margin  = atp_mickeys_scale_factor;
1615 	sc->sc_right_margin = (sc->sc_params->n_xsensors - 1) *
1616 		atp_mickeys_scale_factor;
1617 
1618 	return (0);
1619 
1620 detach:
1621 	atp_detach(dev);
1622 	return (ENOMEM);
1623 }
1624 
1625 static int
1626 atp_detach(device_t dev)
1627 {
1628 	struct atp_softc *sc;
1629 	int err;
1630 
1631 	sc = device_get_softc(dev);
1632 	if (sc->sc_state & ATP_ENABLED) {
1633 		mtx_lock(&sc->sc_mutex);
1634 		atp_disable(sc);
1635 		mtx_unlock(&sc->sc_mutex);
1636 	}
1637 
1638 	usb_fifo_detach(&sc->sc_fifo);
1639 
1640 	usbd_transfer_unsetup(sc->sc_xfer, ATP_N_TRANSFER);
1641 
1642 	mtx_destroy(&sc->sc_mutex);
1643 
1644 	err = atp_set_device_mode(dev, HID_MODE);
1645 	if (err != 0) {
1646 		DPRINTF("failed to reset mode to 'HID' (%d)\n", err);
1647 		return (err);
1648 	}
1649 
1650 	return (0);
1651 }
1652 
1653 static void
1654 atp_intr(struct usb_xfer *xfer, usb_error_t error)
1655 {
1656 	struct atp_softc      *sc = usbd_xfer_softc(xfer);
1657 	int                    len;
1658 	struct usb_page_cache *pc;
1659 	uint8_t                status_bits;
1660 	atp_pspan  pspans_x[ATP_MAX_PSPANS_PER_AXIS];
1661 	atp_pspan  pspans_y[ATP_MAX_PSPANS_PER_AXIS];
1662 	u_int      n_xpspans = 0, n_ypspans = 0;
1663 	u_int      reaped_xlocs[ATP_MAX_STROKES];
1664 	u_int      tap_fingers = 0;
1665 
1666 	usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
1667 
1668 	switch (USB_GET_STATE(xfer)) {
1669 	case USB_ST_TRANSFERRED:
1670 		if (len > sc->sc_params->data_len) {
1671 			DPRINTFN(ATP_LLEVEL_ERROR,
1672 			    "truncating large packet from %u to %u bytes\n",
1673 			    len, sc->sc_params->data_len);
1674 			len = sc->sc_params->data_len;
1675 		}
1676 		if (len < sc->sc_params->data_len)
1677 			goto tr_setup;
1678 
1679 		pc = usbd_xfer_get_frame(xfer, 0);
1680 		usbd_copy_out(pc, 0, sc->sensor_data, sc->sc_params->data_len);
1681 
1682 		/* Interpret sensor data */
1683 		atp_interpret_sensor_data(sc->sensor_data,
1684 		    sc->sc_params->n_xsensors, X, sc->cur_x,
1685 		    sc->sc_params->prot);
1686 		atp_interpret_sensor_data(sc->sensor_data,
1687 		    sc->sc_params->n_ysensors, Y,  sc->cur_y,
1688 		    sc->sc_params->prot);
1689 
1690 		/*
1691 		 * If this is the initial update (from an untouched
1692 		 * pad), we should set the base values for the sensor
1693 		 * data; deltas with respect to these base values can
1694 		 * be used as pressure readings subsequently.
1695 		 */
1696 		status_bits = sc->sensor_data[sc->sc_params->data_len - 1];
1697 		if ((sc->sc_params->prot == ATP_PROT_GEYSER3 &&
1698 		    (status_bits & ATP_STATUS_BASE_UPDATE)) ||
1699 		    !(sc->sc_state & ATP_VALID)) {
1700 			memcpy(sc->base_x, sc->cur_x,
1701 			    sc->sc_params->n_xsensors * sizeof(*(sc->base_x)));
1702 			memcpy(sc->base_y, sc->cur_y,
1703 			    sc->sc_params->n_ysensors * sizeof(*(sc->base_y)));
1704 			sc->sc_state |= ATP_VALID;
1705 			goto tr_setup;
1706 		}
1707 
1708 		/* Get pressure readings and detect p-spans for both axes. */
1709 		atp_get_pressures(sc->pressure_x, sc->cur_x, sc->base_x,
1710 		    sc->sc_params->n_xsensors);
1711 		atp_detect_pspans(sc->pressure_x, sc->sc_params->n_xsensors,
1712 		    ATP_MAX_PSPANS_PER_AXIS,
1713 		    pspans_x, &n_xpspans);
1714 		atp_get_pressures(sc->pressure_y, sc->cur_y, sc->base_y,
1715 		    sc->sc_params->n_ysensors);
1716 		atp_detect_pspans(sc->pressure_y, sc->sc_params->n_ysensors,
1717 		    ATP_MAX_PSPANS_PER_AXIS,
1718 		    pspans_y, &n_ypspans);
1719 
1720 		/* Update strokes with new pspans to detect movements. */
1721 		sc->sc_status.flags &= ~MOUSE_POSCHANGED;
1722 		if (atp_update_strokes(sc,
1723 			pspans_x, n_xpspans,
1724 			pspans_y, n_ypspans))
1725 			sc->sc_status.flags |= MOUSE_POSCHANGED;
1726 
1727 		/* Reap zombies if it is time. */
1728 		if (sc->sc_state & ATP_ZOMBIES_EXIST) {
1729 			struct timeval now;
1730 
1731 			getmicrotime(&now);
1732 			if (timevalcmp(&now, &sc->sc_reap_time, >=))
1733 				atp_reap_zombies(sc, &tap_fingers,
1734 				    reaped_xlocs);
1735 		}
1736 
1737 		sc->sc_status.flags &= ~MOUSE_STDBUTTONSCHANGED;
1738 		sc->sc_status.obutton = sc->sc_status.button;
1739 
1740 		/* Get the state of the physical buttton. */
1741 		sc->sc_status.button = (status_bits & ATP_STATUS_BUTTON) ?
1742 			MOUSE_BUTTON1DOWN : 0;
1743 		if (sc->sc_status.button != 0) {
1744 			/* Reset DOUBLE_TAP_N_DRAG if the button is pressed. */
1745 			sc->sc_state &= ~ATP_DOUBLE_TAP_DRAG;
1746 		} else if (sc->sc_state & ATP_DOUBLE_TAP_DRAG) {
1747 			/* Assume a button-press with DOUBLE_TAP_N_DRAG. */
1748 			sc->sc_status.button = MOUSE_BUTTON1DOWN;
1749 		}
1750 
1751 		sc->sc_status.flags |=
1752 			sc->sc_status.button ^ sc->sc_status.obutton;
1753 		if (sc->sc_status.flags & MOUSE_STDBUTTONSCHANGED) {
1754 			DPRINTFN(ATP_LLEVEL_INFO, "button %s\n",
1755 			    ((sc->sc_status.button & MOUSE_BUTTON1DOWN) ?
1756 				"pressed" : "released"));
1757 		} else if ((sc->sc_status.obutton == 0) &&
1758 		    (sc->sc_status.button == 0) &&
1759 		    (tap_fingers != 0)) {
1760 			/* Ignore single-finger taps at the edges. */
1761 			if ((tap_fingers == 1) &&
1762 			    ((reaped_xlocs[0] <= sc->sc_left_margin) ||
1763 				(reaped_xlocs[0] > sc->sc_right_margin))) {
1764 				tap_fingers = 0;
1765 			}
1766 			DPRINTFN(ATP_LLEVEL_INFO,
1767 			    "tap_fingers: %u\n", tap_fingers);
1768 		}
1769 
1770 		if (sc->sc_status.flags &
1771 		    (MOUSE_POSCHANGED | MOUSE_STDBUTTONSCHANGED)) {
1772 			int   dx, dy;
1773 			u_int n_movements;
1774 
1775 			dx = 0, dy = 0, n_movements = 0;
1776 			for (u_int i = 0; i < sc->sc_n_strokes; i++) {
1777 				atp_stroke *stroke = &sc->sc_strokes[i];
1778 
1779 				if ((stroke->components[X].movement) ||
1780 				    (stroke->components[Y].movement)) {
1781 					dx += stroke->components[X].movement;
1782 					dy += stroke->components[Y].movement;
1783 					n_movements++;
1784 				}
1785 			}
1786 			/*
1787 			 * Disregard movement if multiple
1788 			 * strokes record motion.
1789 			 */
1790 			if (n_movements != 1)
1791 				dx = 0, dy = 0;
1792 
1793 			sc->sc_status.dx += dx;
1794 			sc->sc_status.dy += dy;
1795 			atp_add_to_queue(sc, dx, -dy, sc->sc_status.button);
1796 		}
1797 
1798 		if (tap_fingers != 0) {
1799 			/* Add a pair of events (button-down and button-up). */
1800 			switch (tap_fingers) {
1801 			case 1: atp_add_to_queue(sc, 0, 0, MOUSE_BUTTON1DOWN);
1802 				break;
1803 			case 2: atp_add_to_queue(sc, 0, 0, MOUSE_BUTTON2DOWN);
1804 				break;
1805 			case 3: atp_add_to_queue(sc, 0, 0, MOUSE_BUTTON3DOWN);
1806 				break;
1807 			default: break;/* handle taps of only up to 3 fingers */
1808 			}
1809 			atp_add_to_queue(sc, 0, 0, 0); /* button release */
1810 		}
1811 
1812 		/*
1813 		 * The device continues to trigger interrupts at a
1814 		 * fast rate even after touchpad activity has
1815 		 * stopped. Upon detecting that the device has
1816 		 * remained idle beyond a threshold, we reinitialize
1817 		 * it to silence the interrupts.
1818 		 */
1819 		if ((sc->sc_status.flags  == 0) &&
1820 		    (sc->sc_n_strokes     == 0) &&
1821 		    (sc->sc_status.button == 0)) {
1822 			sc->sc_idlecount++;
1823 			if (sc->sc_idlecount >= ATP_IDLENESS_THRESHOLD) {
1824 				DPRINTFN(ATP_LLEVEL_INFO, "idle\n");
1825 				sc->sc_idlecount = 0;
1826 
1827 				mtx_unlock(&sc->sc_mutex);
1828 				atp_set_device_mode(sc->sc_dev,RAW_SENSOR_MODE);
1829 				mtx_lock(&sc->sc_mutex);
1830 			}
1831 		} else {
1832 			sc->sc_idlecount = 0;
1833 		}
1834 
1835 	case USB_ST_SETUP:
1836 	tr_setup:
1837 		/* check if we can put more data into the FIFO */
1838 		if (usb_fifo_put_bytes_max(
1839 			    sc->sc_fifo.fp[USB_FIFO_RX]) != 0) {
1840 			usbd_xfer_set_frame_len(xfer, 0,
1841 			    sc->sc_params->data_len);
1842 			usbd_transfer_submit(xfer);
1843 		}
1844 		break;
1845 
1846 	default:                        /* Error */
1847 		if (error != USB_ERR_CANCELLED) {
1848 			/* try clear stall first */
1849 			usbd_xfer_set_stall(xfer);
1850 			goto tr_setup;
1851 		}
1852 		break;
1853 	}
1854 
1855 	return;
1856 }
1857 
1858 static void
1859 atp_add_to_queue(struct atp_softc *sc, int dx, int dy, uint32_t buttons_in)
1860 {
1861 	uint32_t buttons_out;
1862 	uint8_t  buf[8];
1863 
1864 	dx = imin(dx,  254); dx = imax(dx, -256);
1865 	dy = imin(dy,  254); dy = imax(dy, -256);
1866 
1867 	buttons_out = MOUSE_MSC_BUTTONS;
1868 	if (buttons_in & MOUSE_BUTTON1DOWN)
1869 		buttons_out &= ~MOUSE_MSC_BUTTON1UP;
1870 	else if (buttons_in & MOUSE_BUTTON2DOWN)
1871 		buttons_out &= ~MOUSE_MSC_BUTTON2UP;
1872 	else if (buttons_in & MOUSE_BUTTON3DOWN)
1873 		buttons_out &= ~MOUSE_MSC_BUTTON3UP;
1874 
1875 	DPRINTFN(ATP_LLEVEL_INFO, "dx=%d, dy=%d, buttons=%x\n",
1876 	    dx, dy, buttons_out);
1877 
1878 	/* Encode the mouse data in standard format; refer to mouse(4) */
1879 	buf[0] = sc->sc_mode.syncmask[1];
1880 	buf[0] |= buttons_out;
1881 	buf[1] = dx >> 1;
1882 	buf[2] = dy >> 1;
1883 	buf[3] = dx - (dx >> 1);
1884 	buf[4] = dy - (dy >> 1);
1885 	/* Encode extra bytes for level 1 */
1886 	if (sc->sc_mode.level == 1) {
1887 		buf[5] = 0;                    /* dz */
1888 		buf[6] = 0;                    /* dz - (dz / 2) */
1889 		buf[7] = MOUSE_SYS_EXTBUTTONS; /* Extra buttons all up. */
1890 	}
1891 
1892 	usb_fifo_put_data_linear(sc->sc_fifo.fp[USB_FIFO_RX], buf,
1893 	    sc->sc_mode.packetsize, 1);
1894 }
1895 
1896 static void
1897 atp_reset_buf(struct atp_softc *sc)
1898 {
1899 	/* reset read queue */
1900 	usb_fifo_reset(sc->sc_fifo.fp[USB_FIFO_RX]);
1901 }
1902 
1903 static void
1904 atp_start_read(struct usb_fifo *fifo)
1905 {
1906 	struct atp_softc *sc = usb_fifo_softc(fifo);
1907 	int rate;
1908 
1909 	/* Check if we should override the default polling interval */
1910 	rate = sc->sc_pollrate;
1911 	/* Range check rate */
1912 	if (rate > 1000)
1913 		rate = 1000;
1914 	/* Check for set rate */
1915 	if ((rate > 0) && (sc->sc_xfer[ATP_INTR_DT] != NULL)) {
1916 		/* Stop current transfer, if any */
1917 		usbd_transfer_stop(sc->sc_xfer[ATP_INTR_DT]);
1918 		/* Set new interval */
1919 		usbd_xfer_set_interval(sc->sc_xfer[ATP_INTR_DT], 1000 / rate);
1920 		/* Only set pollrate once */
1921 		sc->sc_pollrate = 0;
1922 	}
1923 
1924 	usbd_transfer_start(sc->sc_xfer[ATP_INTR_DT]);
1925 }
1926 
1927 static void
1928 atp_stop_read(struct usb_fifo *fifo)
1929 {
1930 	struct atp_softc *sc = usb_fifo_softc(fifo);
1931 
1932 	usbd_transfer_stop(sc->sc_xfer[ATP_INTR_DT]);
1933 }
1934 
1935 
1936 static int
1937 atp_open(struct usb_fifo *fifo, int fflags)
1938 {
1939 	DPRINTFN(ATP_LLEVEL_INFO, "\n");
1940 
1941 	if (fflags & FREAD) {
1942 		struct atp_softc *sc = usb_fifo_softc(fifo);
1943 		int rc;
1944 
1945 		if (sc->sc_state & ATP_ENABLED)
1946 			return (EBUSY);
1947 
1948 		if (usb_fifo_alloc_buffer(fifo,
1949 			ATP_FIFO_BUF_SIZE, ATP_FIFO_QUEUE_MAXLEN)) {
1950 			return (ENOMEM);
1951 		}
1952 
1953 		rc = atp_enable(sc);
1954 		if (rc != 0) {
1955 			usb_fifo_free_buffer(fifo);
1956 			return (rc);
1957 		}
1958 	}
1959 
1960 	return (0);
1961 }
1962 
1963 static void
1964 atp_close(struct usb_fifo *fifo, int fflags)
1965 {
1966 	if (fflags & FREAD) {
1967 		struct atp_softc *sc = usb_fifo_softc(fifo);
1968 
1969 		atp_disable(sc);
1970 		usb_fifo_free_buffer(fifo);
1971 	}
1972 }
1973 
1974 int
1975 atp_ioctl(struct usb_fifo *fifo, u_long cmd, void *addr, int fflags)
1976 {
1977 	struct atp_softc *sc = usb_fifo_softc(fifo);
1978 	mousemode_t mode;
1979 	int error = 0;
1980 
1981 	mtx_lock(&sc->sc_mutex);
1982 
1983 	switch(cmd) {
1984 	case MOUSE_GETHWINFO:
1985 		*(mousehw_t *)addr = sc->sc_hw;
1986 		break;
1987 	case MOUSE_GETMODE:
1988 		*(mousemode_t *)addr = sc->sc_mode;
1989 		break;
1990 	case MOUSE_SETMODE:
1991 		mode = *(mousemode_t *)addr;
1992 
1993 		if (mode.level == -1)
1994 			/* Don't change the current setting */
1995 			;
1996 		else if ((mode.level < 0) || (mode.level > 1)) {
1997 			error = EINVAL;
1998 			goto done;
1999 		}
2000 		sc->sc_mode.level = mode.level;
2001 		sc->sc_pollrate   = mode.rate;
2002 		sc->sc_hw.buttons = 3;
2003 
2004 		if (sc->sc_mode.level == 0) {
2005 			sc->sc_mode.protocol = MOUSE_PROTO_MSC;
2006 			sc->sc_mode.packetsize = MOUSE_MSC_PACKETSIZE;
2007 			sc->sc_mode.syncmask[0] = MOUSE_MSC_SYNCMASK;
2008 			sc->sc_mode.syncmask[1] = MOUSE_MSC_SYNC;
2009 		} else if (sc->sc_mode.level == 1) {
2010 			sc->sc_mode.protocol = MOUSE_PROTO_SYSMOUSE;
2011 			sc->sc_mode.packetsize = MOUSE_SYS_PACKETSIZE;
2012 			sc->sc_mode.syncmask[0] = MOUSE_SYS_SYNCMASK;
2013 			sc->sc_mode.syncmask[1] = MOUSE_SYS_SYNC;
2014 		}
2015 		atp_reset_buf(sc);
2016 		break;
2017 	case MOUSE_GETLEVEL:
2018 		*(int *)addr = sc->sc_mode.level;
2019 		break;
2020 	case MOUSE_SETLEVEL:
2021 		if (*(int *)addr < 0 || *(int *)addr > 1) {
2022 			error = EINVAL;
2023 			goto done;
2024 		}
2025 		sc->sc_mode.level = *(int *)addr;
2026 		sc->sc_hw.buttons = 3;
2027 
2028 		if (sc->sc_mode.level == 0) {
2029 			sc->sc_mode.protocol = MOUSE_PROTO_MSC;
2030 			sc->sc_mode.packetsize = MOUSE_MSC_PACKETSIZE;
2031 			sc->sc_mode.syncmask[0] = MOUSE_MSC_SYNCMASK;
2032 			sc->sc_mode.syncmask[1] = MOUSE_MSC_SYNC;
2033 		} else if (sc->sc_mode.level == 1) {
2034 			sc->sc_mode.protocol = MOUSE_PROTO_SYSMOUSE;
2035 			sc->sc_mode.packetsize = MOUSE_SYS_PACKETSIZE;
2036 			sc->sc_mode.syncmask[0] = MOUSE_SYS_SYNCMASK;
2037 			sc->sc_mode.syncmask[1] = MOUSE_SYS_SYNC;
2038 		}
2039 		atp_reset_buf(sc);
2040 		break;
2041 	case MOUSE_GETSTATUS: {
2042 		mousestatus_t *status = (mousestatus_t *)addr;
2043 
2044 		*status = sc->sc_status;
2045 		sc->sc_status.obutton = sc->sc_status.button;
2046 		sc->sc_status.button  = 0;
2047 		sc->sc_status.dx = 0;
2048 		sc->sc_status.dy = 0;
2049 		sc->sc_status.dz = 0;
2050 
2051 		if (status->dx || status->dy || status->dz)
2052 			status->flags |= MOUSE_POSCHANGED;
2053 		if (status->button != status->obutton)
2054 			status->flags |= MOUSE_BUTTONSCHANGED;
2055 		break;
2056 	}
2057 	default:
2058 		error = ENOTTY;
2059 	}
2060 
2061 done:
2062 	mtx_unlock(&sc->sc_mutex);
2063 	return (error);
2064 }
2065 
2066 static int
2067 atp_sysctl_scale_factor_handler(SYSCTL_HANDLER_ARGS)
2068 {
2069 	int error;
2070 	u_int tmp;
2071 	u_int prev_mickeys_scale_factor;
2072 
2073 	prev_mickeys_scale_factor = atp_mickeys_scale_factor;
2074 
2075 	tmp = atp_mickeys_scale_factor;
2076 	error = sysctl_handle_int(oidp, &tmp, 0, req);
2077 	if (error != 0 || req->newptr == NULL)
2078 		return (error);
2079 
2080 	if (tmp == prev_mickeys_scale_factor)
2081 		return (0);     /* no change */
2082 
2083 	atp_mickeys_scale_factor = tmp;
2084 	DPRINTFN(ATP_LLEVEL_INFO, "%s: resetting mickeys_scale_factor to %u\n",
2085 	    ATP_DRIVER_NAME, tmp);
2086 
2087 	/* Update dependent thresholds. */
2088 	if (atp_small_movement_threshold == (prev_mickeys_scale_factor >> 3))
2089 		atp_small_movement_threshold = atp_mickeys_scale_factor >> 3;
2090 	if (atp_max_delta_mickeys == ((3 * prev_mickeys_scale_factor) >> 1))
2091 		atp_max_delta_mickeys = ((3 * atp_mickeys_scale_factor) >>1);
2092 	if (atp_slide_min_movement == (prev_mickeys_scale_factor >> 3))
2093 		atp_slide_min_movement = atp_mickeys_scale_factor >> 3;
2094 
2095 	return (0);
2096 }
2097 
2098 static device_method_t atp_methods[] = {
2099 	/* Device interface */
2100 	DEVMETHOD(device_probe,  atp_probe),
2101 	DEVMETHOD(device_attach, atp_attach),
2102 	DEVMETHOD(device_detach, atp_detach),
2103 	{ 0, 0 }
2104 };
2105 
2106 static driver_t atp_driver = {
2107 	ATP_DRIVER_NAME,
2108 	atp_methods,
2109 	sizeof(struct atp_softc)
2110 };
2111 
2112 static devclass_t atp_devclass;
2113 
2114 DRIVER_MODULE(atp, uhub, atp_driver, atp_devclass, NULL, 0);
2115 MODULE_DEPEND(atp, usb, 1, 1, 1);
2116