GNU Linux-libre 4.19.286-gnu1
[releases.git] / drivers / input / touchscreen / sur40.c
1 /*
2  * Surface2.0/SUR40/PixelSense input driver
3  *
4  * Copyright (c) 2014 by Florian 'floe' Echtler <floe@butterbrot.org>
5  *
6  * Derived from the USB Skeleton driver 1.1,
7  * Copyright (c) 2003 Greg Kroah-Hartman (greg@kroah.com)
8  *
9  * and from the Apple USB BCM5974 multitouch driver,
10  * Copyright (c) 2008 Henrik Rydberg (rydberg@euromail.se)
11  *
12  * and from the generic hid-multitouch driver,
13  * Copyright (c) 2010-2012 Stephane Chatty <chatty@enac.fr>
14  *
15  * and from the v4l2-pci-skeleton driver,
16  * Copyright (c) Copyright 2014 Cisco Systems, Inc.
17  *
18  * This program is free software; you can redistribute it and/or
19  * modify it under the terms of the GNU General Public License as
20  * published by the Free Software Foundation; either version 2 of
21  * the License, or (at your option) any later version.
22  */
23
24 #include <linux/kernel.h>
25 #include <linux/errno.h>
26 #include <linux/delay.h>
27 #include <linux/init.h>
28 #include <linux/slab.h>
29 #include <linux/module.h>
30 #include <linux/completion.h>
31 #include <linux/uaccess.h>
32 #include <linux/usb.h>
33 #include <linux/printk.h>
34 #include <linux/input-polldev.h>
35 #include <linux/input/mt.h>
36 #include <linux/usb/input.h>
37 #include <linux/videodev2.h>
38 #include <media/v4l2-device.h>
39 #include <media/v4l2-dev.h>
40 #include <media/v4l2-ioctl.h>
41 #include <media/v4l2-ctrls.h>
42 #include <media/videobuf2-v4l2.h>
43 #include <media/videobuf2-dma-sg.h>
44
45 /* read 512 bytes from endpoint 0x86 -> get header + blobs */
46 struct sur40_header {
47
48         __le16 type;       /* always 0x0001 */
49         __le16 count;      /* count of blobs (if 0: continue prev. packet) */
50
51         __le32 packet_id;  /* unique ID for all packets in one frame */
52
53         __le32 timestamp;  /* milliseconds (inc. by 16 or 17 each frame) */
54         __le32 unknown;    /* "epoch?" always 02/03 00 00 00 */
55
56 } __packed;
57
58 struct sur40_blob {
59
60         __le16 blob_id;
61
62         u8 action;         /* 0x02 = enter/exit, 0x03 = update (?) */
63         u8 type;           /* bitmask (0x01 blob,  0x02 touch, 0x04 tag) */
64
65         __le16 bb_pos_x;   /* upper left corner of bounding box */
66         __le16 bb_pos_y;
67
68         __le16 bb_size_x;  /* size of bounding box */
69         __le16 bb_size_y;
70
71         __le16 pos_x;      /* finger tip position */
72         __le16 pos_y;
73
74         __le16 ctr_x;      /* centroid position */
75         __le16 ctr_y;
76
77         __le16 axis_x;     /* somehow related to major/minor axis, mostly: */
78         __le16 axis_y;     /* axis_x == bb_size_y && axis_y == bb_size_x */
79
80         __le32 angle;      /* orientation in radians relative to x axis -
81                               actually an IEEE754 float, don't use in kernel */
82
83         __le32 area;       /* size in pixels/pressure (?) */
84
85         u8 padding[24];
86
87         __le32 tag_id;     /* valid when type == 0x04 (SUR40_TAG) */
88         __le32 unknown;
89
90 } __packed;
91
92 /* combined header/blob data */
93 struct sur40_data {
94         struct sur40_header header;
95         struct sur40_blob   blobs[];
96 } __packed;
97
98 /* read 512 bytes from endpoint 0x82 -> get header below
99  * continue reading 16k blocks until header.size bytes read */
100 struct sur40_image_header {
101         __le32 magic;     /* "SUBF" */
102         __le32 packet_id;
103         __le32 size;      /* always 0x0007e900 = 960x540 */
104         __le32 timestamp; /* milliseconds (increases by 16 or 17 each frame) */
105         __le32 unknown;   /* "epoch?" always 02/03 00 00 00 */
106 } __packed;
107
108 /* version information */
109 #define DRIVER_SHORT   "sur40"
110 #define DRIVER_LONG    "Samsung SUR40"
111 #define DRIVER_AUTHOR  "Florian 'floe' Echtler <floe@butterbrot.org>"
112 #define DRIVER_DESC    "Surface2.0/SUR40/PixelSense input driver"
113
114 /* vendor and device IDs */
115 #define ID_MICROSOFT 0x045e
116 #define ID_SUR40     0x0775
117
118 /* sensor resolution */
119 #define SENSOR_RES_X 1920
120 #define SENSOR_RES_Y 1080
121
122 /* touch data endpoint */
123 #define TOUCH_ENDPOINT 0x86
124
125 /* video data endpoint */
126 #define VIDEO_ENDPOINT 0x82
127
128 /* video header fields */
129 #define VIDEO_HEADER_MAGIC 0x46425553
130 #define VIDEO_PACKET_SIZE  16384
131
132 /* polling interval (ms) */
133 #define POLL_INTERVAL 1
134
135 /* maximum number of contacts FIXME: this is a guess? */
136 #define MAX_CONTACTS 64
137
138 /* control commands */
139 #define SUR40_GET_VERSION 0xb0 /* 12 bytes string    */
140 #define SUR40_ACCEL_CAPS  0xb3 /*  5 bytes           */
141 #define SUR40_SENSOR_CAPS 0xc1 /* 24 bytes           */
142
143 #define SUR40_POKE        0xc5 /* poke register byte */
144 #define SUR40_PEEK        0xc4 /* 48 bytes registers */
145
146 #define SUR40_GET_STATE   0xc5 /*  4 bytes state (?) */
147 #define SUR40_GET_SENSORS 0xb1 /*  8 bytes sensors   */
148
149 #define SUR40_BLOB      0x01
150 #define SUR40_TOUCH     0x02
151 #define SUR40_TAG       0x04
152
153 /* video controls */
154 #define SUR40_BRIGHTNESS_MAX 0xff
155 #define SUR40_BRIGHTNESS_MIN 0x00
156 #define SUR40_BRIGHTNESS_DEF 0xff
157
158 #define SUR40_CONTRAST_MAX 0x0f
159 #define SUR40_CONTRAST_MIN 0x00
160 #define SUR40_CONTRAST_DEF 0x0a
161
162 #define SUR40_GAIN_MAX 0x09
163 #define SUR40_GAIN_MIN 0x00
164 #define SUR40_GAIN_DEF 0x08
165
166 #define SUR40_BACKLIGHT_MAX 0x01
167 #define SUR40_BACKLIGHT_MIN 0x00
168 #define SUR40_BACKLIGHT_DEF 0x01
169
170 #define sur40_str(s) #s
171 #define SUR40_PARAM_RANGE(lo, hi) " (range " sur40_str(lo) "-" sur40_str(hi) ")"
172
173 /* module parameters */
174 static uint brightness = SUR40_BRIGHTNESS_DEF;
175 module_param(brightness, uint, 0644);
176 MODULE_PARM_DESC(brightness, "set initial brightness"
177         SUR40_PARAM_RANGE(SUR40_BRIGHTNESS_MIN, SUR40_BRIGHTNESS_MAX));
178 static uint contrast = SUR40_CONTRAST_DEF;
179 module_param(contrast, uint, 0644);
180 MODULE_PARM_DESC(contrast, "set initial contrast"
181         SUR40_PARAM_RANGE(SUR40_CONTRAST_MIN, SUR40_CONTRAST_MAX));
182 static uint gain = SUR40_GAIN_DEF;
183 module_param(gain, uint, 0644);
184 MODULE_PARM_DESC(gain, "set initial gain"
185         SUR40_PARAM_RANGE(SUR40_GAIN_MIN, SUR40_GAIN_MAX));
186
187 static const struct v4l2_pix_format sur40_pix_format[] = {
188         {
189                 .pixelformat = V4L2_TCH_FMT_TU08,
190                 .width  = SENSOR_RES_X / 2,
191                 .height = SENSOR_RES_Y / 2,
192                 .field = V4L2_FIELD_NONE,
193                 .colorspace = V4L2_COLORSPACE_SRGB,
194                 .bytesperline = SENSOR_RES_X / 2,
195                 .sizeimage = (SENSOR_RES_X/2) * (SENSOR_RES_Y/2),
196         },
197         {
198                 .pixelformat = V4L2_PIX_FMT_GREY,
199                 .width  = SENSOR_RES_X / 2,
200                 .height = SENSOR_RES_Y / 2,
201                 .field = V4L2_FIELD_NONE,
202                 .colorspace = V4L2_COLORSPACE_SRGB,
203                 .bytesperline = SENSOR_RES_X / 2,
204                 .sizeimage = (SENSOR_RES_X/2) * (SENSOR_RES_Y/2),
205         }
206 };
207
208 /* master device state */
209 struct sur40_state {
210
211         struct usb_device *usbdev;
212         struct device *dev;
213         struct input_polled_dev *input;
214
215         struct v4l2_device v4l2;
216         struct video_device vdev;
217         struct mutex lock;
218         struct v4l2_pix_format pix_fmt;
219         struct v4l2_ctrl_handler hdl;
220
221         struct vb2_queue queue;
222         struct list_head buf_list;
223         spinlock_t qlock;
224         int sequence;
225
226         struct sur40_data *bulk_in_buffer;
227         size_t bulk_in_size;
228         u8 bulk_in_epaddr;
229         u8 vsvideo;
230
231         char phys[64];
232 };
233
234 struct sur40_buffer {
235         struct vb2_v4l2_buffer vb;
236         struct list_head list;
237 };
238
239 /* forward declarations */
240 static const struct video_device sur40_video_device;
241 static const struct vb2_queue sur40_queue;
242 static void sur40_process_video(struct sur40_state *sur40);
243 static int sur40_s_ctrl(struct v4l2_ctrl *ctrl);
244
245 static const struct v4l2_ctrl_ops sur40_ctrl_ops = {
246         .s_ctrl = sur40_s_ctrl,
247 };
248
249 /*
250  * Note: an earlier, non-public version of this driver used USB_RECIP_ENDPOINT
251  * here by mistake which is very likely to have corrupted the firmware EEPROM
252  * on two separate SUR40 devices. Thanks to Alan Stern who spotted this bug.
253  * Should you ever run into a similar problem, the background story to this
254  * incident and instructions on how to fix the corrupted EEPROM are available
255  * at https://floe.butterbrot.org/matrix/hacking/surface/brick.html
256 */
257
258 /* command wrapper */
259 static int sur40_command(struct sur40_state *dev,
260                          u8 command, u16 index, void *buffer, u16 size)
261 {
262         return usb_control_msg(dev->usbdev, usb_rcvctrlpipe(dev->usbdev, 0),
263                                command,
264                                USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
265                                0x00, index, buffer, size, 1000);
266 }
267
268 /* poke a byte in the panel register space */
269 static int sur40_poke(struct sur40_state *dev, u8 offset, u8 value)
270 {
271         int result;
272         u8 index = 0x96; // 0xae for permanent write
273
274         result = usb_control_msg(dev->usbdev, usb_sndctrlpipe(dev->usbdev, 0),
275                 SUR40_POKE, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT,
276                 0x32, index, NULL, 0, 1000);
277         if (result < 0)
278                 goto error;
279         msleep(5);
280
281         result = usb_control_msg(dev->usbdev, usb_sndctrlpipe(dev->usbdev, 0),
282                 SUR40_POKE, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT,
283                 0x72, offset, NULL, 0, 1000);
284         if (result < 0)
285                 goto error;
286         msleep(5);
287
288         result = usb_control_msg(dev->usbdev, usb_sndctrlpipe(dev->usbdev, 0),
289                 SUR40_POKE, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT,
290                 0xb2, value, NULL, 0, 1000);
291         if (result < 0)
292                 goto error;
293         msleep(5);
294
295 error:
296         return result;
297 }
298
299 static int sur40_set_preprocessor(struct sur40_state *dev, u8 value)
300 {
301         u8 setting_07[2] = { 0x01, 0x00 };
302         u8 setting_17[2] = { 0x85, 0x80 };
303         int result;
304
305         if (value > 1)
306                 return -ERANGE;
307
308         result = usb_control_msg(dev->usbdev, usb_sndctrlpipe(dev->usbdev, 0),
309                 SUR40_POKE, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT,
310                 0x07, setting_07[value], NULL, 0, 1000);
311         if (result < 0)
312                 goto error;
313         msleep(5);
314
315         result = usb_control_msg(dev->usbdev, usb_sndctrlpipe(dev->usbdev, 0),
316                 SUR40_POKE, USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT,
317                 0x17, setting_17[value], NULL, 0, 1000);
318         if (result < 0)
319                 goto error;
320         msleep(5);
321
322 error:
323         return result;
324 }
325
326 static void sur40_set_vsvideo(struct sur40_state *handle, u8 value)
327 {
328         int i;
329
330         for (i = 0; i < 4; i++)
331                 sur40_poke(handle, 0x1c+i, value);
332         handle->vsvideo = value;
333 }
334
335 static void sur40_set_irlevel(struct sur40_state *handle, u8 value)
336 {
337         int i;
338
339         for (i = 0; i < 8; i++)
340                 sur40_poke(handle, 0x08+(2*i), value);
341 }
342
343 /* Initialization routine, called from sur40_open */
344 static int sur40_init(struct sur40_state *dev)
345 {
346         int result;
347         u8 *buffer;
348
349         buffer = kmalloc(24, GFP_KERNEL);
350         if (!buffer) {
351                 result = -ENOMEM;
352                 goto error;
353         }
354
355         /* stupidly replay the original MS driver init sequence */
356         result = sur40_command(dev, SUR40_GET_VERSION, 0x00, buffer, 12);
357         if (result < 0)
358                 goto error;
359
360         result = sur40_command(dev, SUR40_GET_VERSION, 0x01, buffer, 12);
361         if (result < 0)
362                 goto error;
363
364         result = sur40_command(dev, SUR40_GET_VERSION, 0x02, buffer, 12);
365         if (result < 0)
366                 goto error;
367
368         result = sur40_command(dev, SUR40_SENSOR_CAPS, 0x00, buffer, 24);
369         if (result < 0)
370                 goto error;
371
372         result = sur40_command(dev, SUR40_ACCEL_CAPS, 0x00, buffer, 5);
373         if (result < 0)
374                 goto error;
375
376         result = sur40_command(dev, SUR40_GET_VERSION, 0x03, buffer, 12);
377
378         /*
379          * Discard the result buffer - no known data inside except
380          * some version strings, maybe extract these sometime...
381          */
382 error:
383         kfree(buffer);
384         return result;
385 }
386
387 /*
388  * Callback routines from input_polled_dev
389  */
390
391 /* Enable the device, polling will now start. */
392 static void sur40_open(struct input_polled_dev *polldev)
393 {
394         struct sur40_state *sur40 = polldev->private;
395
396         dev_dbg(sur40->dev, "open\n");
397         sur40_init(sur40);
398 }
399
400 /* Disable device, polling has stopped. */
401 static void sur40_close(struct input_polled_dev *polldev)
402 {
403         struct sur40_state *sur40 = polldev->private;
404
405         dev_dbg(sur40->dev, "close\n");
406         /*
407          * There is no known way to stop the device, so we simply
408          * stop polling.
409          */
410 }
411
412 /*
413  * This function is called when a whole contact has been processed,
414  * so that it can assign it to a slot and store the data there.
415  */
416 static void sur40_report_blob(struct sur40_blob *blob, struct input_dev *input)
417 {
418         int wide, major, minor;
419         int bb_size_x, bb_size_y, pos_x, pos_y, ctr_x, ctr_y, slotnum;
420
421         if (blob->type != SUR40_TOUCH)
422                 return;
423
424         slotnum = input_mt_get_slot_by_key(input, blob->blob_id);
425         if (slotnum < 0 || slotnum >= MAX_CONTACTS)
426                 return;
427
428         bb_size_x = le16_to_cpu(blob->bb_size_x);
429         bb_size_y = le16_to_cpu(blob->bb_size_y);
430
431         pos_x = le16_to_cpu(blob->pos_x);
432         pos_y = le16_to_cpu(blob->pos_y);
433
434         ctr_x = le16_to_cpu(blob->ctr_x);
435         ctr_y = le16_to_cpu(blob->ctr_y);
436
437         input_mt_slot(input, slotnum);
438         input_mt_report_slot_state(input, MT_TOOL_FINGER, 1);
439         wide = (bb_size_x > bb_size_y);
440         major = max(bb_size_x, bb_size_y);
441         minor = min(bb_size_x, bb_size_y);
442
443         input_report_abs(input, ABS_MT_POSITION_X, pos_x);
444         input_report_abs(input, ABS_MT_POSITION_Y, pos_y);
445         input_report_abs(input, ABS_MT_TOOL_X, ctr_x);
446         input_report_abs(input, ABS_MT_TOOL_Y, ctr_y);
447
448         /* TODO: use a better orientation measure */
449         input_report_abs(input, ABS_MT_ORIENTATION, wide);
450         input_report_abs(input, ABS_MT_TOUCH_MAJOR, major);
451         input_report_abs(input, ABS_MT_TOUCH_MINOR, minor);
452 }
453
454 /* core function: poll for new input data */
455 static void sur40_poll(struct input_polled_dev *polldev)
456 {
457         struct sur40_state *sur40 = polldev->private;
458         struct input_dev *input = polldev->input;
459         int result, bulk_read, need_blobs, packet_blobs, i;
460         u32 uninitialized_var(packet_id);
461
462         struct sur40_header *header = &sur40->bulk_in_buffer->header;
463         struct sur40_blob *inblob = &sur40->bulk_in_buffer->blobs[0];
464
465         dev_dbg(sur40->dev, "poll\n");
466
467         need_blobs = -1;
468
469         do {
470
471                 /* perform a blocking bulk read to get data from the device */
472                 result = usb_bulk_msg(sur40->usbdev,
473                         usb_rcvbulkpipe(sur40->usbdev, sur40->bulk_in_epaddr),
474                         sur40->bulk_in_buffer, sur40->bulk_in_size,
475                         &bulk_read, 1000);
476
477                 dev_dbg(sur40->dev, "received %d bytes\n", bulk_read);
478
479                 if (result < 0) {
480                         dev_err(sur40->dev, "error in usb_bulk_read\n");
481                         return;
482                 }
483
484                 result = bulk_read - sizeof(struct sur40_header);
485
486                 if (result % sizeof(struct sur40_blob) != 0) {
487                         dev_err(sur40->dev, "transfer size mismatch\n");
488                         return;
489                 }
490
491                 /* first packet? */
492                 if (need_blobs == -1) {
493                         need_blobs = le16_to_cpu(header->count);
494                         dev_dbg(sur40->dev, "need %d blobs\n", need_blobs);
495                         packet_id = le32_to_cpu(header->packet_id);
496                 }
497
498                 /*
499                  * Sanity check. when video data is also being retrieved, the
500                  * packet ID will usually increase in the middle of a series
501                  * instead of at the end. However, the data is still consistent,
502                  * so the packet ID is probably just valid for the first packet
503                  * in a series.
504
505                 if (packet_id != le32_to_cpu(header->packet_id))
506                         dev_dbg(sur40->dev, "packet ID mismatch\n");
507                  */
508
509                 packet_blobs = result / sizeof(struct sur40_blob);
510                 dev_dbg(sur40->dev, "received %d blobs\n", packet_blobs);
511
512                 /* packets always contain at least 4 blobs, even if empty */
513                 if (packet_blobs > need_blobs)
514                         packet_blobs = need_blobs;
515
516                 for (i = 0; i < packet_blobs; i++) {
517                         need_blobs--;
518                         dev_dbg(sur40->dev, "processing blob\n");
519                         sur40_report_blob(&(inblob[i]), input);
520                 }
521
522         } while (need_blobs > 0);
523
524         input_mt_sync_frame(input);
525         input_sync(input);
526
527         sur40_process_video(sur40);
528 }
529
530 /* deal with video data */
531 static void sur40_process_video(struct sur40_state *sur40)
532 {
533
534         struct sur40_image_header *img = (void *)(sur40->bulk_in_buffer);
535         struct sur40_buffer *new_buf;
536         struct usb_sg_request sgr;
537         struct sg_table *sgt;
538         int result, bulk_read;
539
540         if (!vb2_start_streaming_called(&sur40->queue))
541                 return;
542
543         /* get a new buffer from the list */
544         spin_lock(&sur40->qlock);
545         if (list_empty(&sur40->buf_list)) {
546                 dev_dbg(sur40->dev, "buffer queue empty\n");
547                 spin_unlock(&sur40->qlock);
548                 return;
549         }
550         new_buf = list_entry(sur40->buf_list.next, struct sur40_buffer, list);
551         list_del(&new_buf->list);
552         spin_unlock(&sur40->qlock);
553
554         dev_dbg(sur40->dev, "buffer acquired\n");
555
556         /* retrieve data via bulk read */
557         result = usb_bulk_msg(sur40->usbdev,
558                         usb_rcvbulkpipe(sur40->usbdev, VIDEO_ENDPOINT),
559                         sur40->bulk_in_buffer, sur40->bulk_in_size,
560                         &bulk_read, 1000);
561
562         if (result < 0) {
563                 dev_err(sur40->dev, "error in usb_bulk_read\n");
564                 goto err_poll;
565         }
566
567         if (bulk_read != sizeof(struct sur40_image_header)) {
568                 dev_err(sur40->dev, "received %d bytes (%zd expected)\n",
569                         bulk_read, sizeof(struct sur40_image_header));
570                 goto err_poll;
571         }
572
573         if (le32_to_cpu(img->magic) != VIDEO_HEADER_MAGIC) {
574                 dev_err(sur40->dev, "image magic mismatch\n");
575                 goto err_poll;
576         }
577
578         if (le32_to_cpu(img->size) != sur40->pix_fmt.sizeimage) {
579                 dev_err(sur40->dev, "image size mismatch\n");
580                 goto err_poll;
581         }
582
583         dev_dbg(sur40->dev, "header acquired\n");
584
585         sgt = vb2_dma_sg_plane_desc(&new_buf->vb.vb2_buf, 0);
586
587         result = usb_sg_init(&sgr, sur40->usbdev,
588                 usb_rcvbulkpipe(sur40->usbdev, VIDEO_ENDPOINT), 0,
589                 sgt->sgl, sgt->nents, sur40->pix_fmt.sizeimage, 0);
590         if (result < 0) {
591                 dev_err(sur40->dev, "error %d in usb_sg_init\n", result);
592                 goto err_poll;
593         }
594
595         usb_sg_wait(&sgr);
596         if (sgr.status < 0) {
597                 dev_err(sur40->dev, "error %d in usb_sg_wait\n", sgr.status);
598                 goto err_poll;
599         }
600
601         dev_dbg(sur40->dev, "image acquired\n");
602
603         /* return error if streaming was stopped in the meantime */
604         if (sur40->sequence == -1)
605                 return;
606
607         /* mark as finished */
608         new_buf->vb.vb2_buf.timestamp = ktime_get_ns();
609         new_buf->vb.sequence = sur40->sequence++;
610         new_buf->vb.field = V4L2_FIELD_NONE;
611         vb2_buffer_done(&new_buf->vb.vb2_buf, VB2_BUF_STATE_DONE);
612         dev_dbg(sur40->dev, "buffer marked done\n");
613         return;
614
615 err_poll:
616         vb2_buffer_done(&new_buf->vb.vb2_buf, VB2_BUF_STATE_ERROR);
617 }
618
619 /* Initialize input device parameters. */
620 static void sur40_input_setup(struct input_dev *input_dev)
621 {
622         __set_bit(EV_KEY, input_dev->evbit);
623         __set_bit(EV_ABS, input_dev->evbit);
624
625         input_set_abs_params(input_dev, ABS_MT_POSITION_X,
626                              0, SENSOR_RES_X, 0, 0);
627         input_set_abs_params(input_dev, ABS_MT_POSITION_Y,
628                              0, SENSOR_RES_Y, 0, 0);
629
630         input_set_abs_params(input_dev, ABS_MT_TOOL_X,
631                              0, SENSOR_RES_X, 0, 0);
632         input_set_abs_params(input_dev, ABS_MT_TOOL_Y,
633                              0, SENSOR_RES_Y, 0, 0);
634
635         /* max value unknown, but major/minor axis
636          * can never be larger than screen */
637         input_set_abs_params(input_dev, ABS_MT_TOUCH_MAJOR,
638                              0, SENSOR_RES_X, 0, 0);
639         input_set_abs_params(input_dev, ABS_MT_TOUCH_MINOR,
640                              0, SENSOR_RES_Y, 0, 0);
641
642         input_set_abs_params(input_dev, ABS_MT_ORIENTATION, 0, 1, 0, 0);
643
644         input_mt_init_slots(input_dev, MAX_CONTACTS,
645                             INPUT_MT_DIRECT | INPUT_MT_DROP_UNUSED);
646 }
647
648 /* Check candidate USB interface. */
649 static int sur40_probe(struct usb_interface *interface,
650                        const struct usb_device_id *id)
651 {
652         struct usb_device *usbdev = interface_to_usbdev(interface);
653         struct sur40_state *sur40;
654         struct usb_host_interface *iface_desc;
655         struct usb_endpoint_descriptor *endpoint;
656         struct input_polled_dev *poll_dev;
657         int error;
658
659         /* Check if we really have the right interface. */
660         iface_desc = interface->cur_altsetting;
661         if (iface_desc->desc.bInterfaceClass != 0xFF)
662                 return -ENODEV;
663
664         if (iface_desc->desc.bNumEndpoints < 5)
665                 return -ENODEV;
666
667         /* Use endpoint #4 (0x86). */
668         endpoint = &iface_desc->endpoint[4].desc;
669         if (endpoint->bEndpointAddress != TOUCH_ENDPOINT)
670                 return -ENODEV;
671
672         /* Allocate memory for our device state and initialize it. */
673         sur40 = kzalloc(sizeof(struct sur40_state), GFP_KERNEL);
674         if (!sur40)
675                 return -ENOMEM;
676
677         poll_dev = input_allocate_polled_device();
678         if (!poll_dev) {
679                 error = -ENOMEM;
680                 goto err_free_dev;
681         }
682
683         /* initialize locks/lists */
684         INIT_LIST_HEAD(&sur40->buf_list);
685         spin_lock_init(&sur40->qlock);
686         mutex_init(&sur40->lock);
687
688         /* Set up polled input device control structure */
689         poll_dev->private = sur40;
690         poll_dev->poll_interval = POLL_INTERVAL;
691         poll_dev->open = sur40_open;
692         poll_dev->poll = sur40_poll;
693         poll_dev->close = sur40_close;
694
695         /* Set up regular input device structure */
696         sur40_input_setup(poll_dev->input);
697
698         poll_dev->input->name = DRIVER_LONG;
699         usb_to_input_id(usbdev, &poll_dev->input->id);
700         usb_make_path(usbdev, sur40->phys, sizeof(sur40->phys));
701         strlcat(sur40->phys, "/input0", sizeof(sur40->phys));
702         poll_dev->input->phys = sur40->phys;
703         poll_dev->input->dev.parent = &interface->dev;
704
705         sur40->usbdev = usbdev;
706         sur40->dev = &interface->dev;
707         sur40->input = poll_dev;
708
709         /* use the bulk-in endpoint tested above */
710         sur40->bulk_in_size = usb_endpoint_maxp(endpoint);
711         sur40->bulk_in_epaddr = endpoint->bEndpointAddress;
712         sur40->bulk_in_buffer = kmalloc(sur40->bulk_in_size, GFP_KERNEL);
713         if (!sur40->bulk_in_buffer) {
714                 dev_err(&interface->dev, "Unable to allocate input buffer.");
715                 error = -ENOMEM;
716                 goto err_free_polldev;
717         }
718
719         /* register the polled input device */
720         error = input_register_polled_device(poll_dev);
721         if (error) {
722                 dev_err(&interface->dev,
723                         "Unable to register polled input device.");
724                 goto err_free_buffer;
725         }
726
727         /* register the video master device */
728         snprintf(sur40->v4l2.name, sizeof(sur40->v4l2.name), "%s", DRIVER_LONG);
729         error = v4l2_device_register(sur40->dev, &sur40->v4l2);
730         if (error) {
731                 dev_err(&interface->dev,
732                         "Unable to register video master device.");
733                 goto err_unreg_v4l2;
734         }
735
736         /* initialize the lock and subdevice */
737         sur40->queue = sur40_queue;
738         sur40->queue.drv_priv = sur40;
739         sur40->queue.lock = &sur40->lock;
740         sur40->queue.dev = sur40->dev;
741
742         /* initialize the queue */
743         error = vb2_queue_init(&sur40->queue);
744         if (error)
745                 goto err_unreg_v4l2;
746
747         sur40->pix_fmt = sur40_pix_format[0];
748         sur40->vdev = sur40_video_device;
749         sur40->vdev.v4l2_dev = &sur40->v4l2;
750         sur40->vdev.lock = &sur40->lock;
751         sur40->vdev.queue = &sur40->queue;
752         video_set_drvdata(&sur40->vdev, sur40);
753
754         /* initialize the control handler for 4 controls */
755         v4l2_ctrl_handler_init(&sur40->hdl, 4);
756         sur40->v4l2.ctrl_handler = &sur40->hdl;
757         sur40->vsvideo = (SUR40_CONTRAST_DEF << 4) | SUR40_GAIN_DEF;
758
759         v4l2_ctrl_new_std(&sur40->hdl, &sur40_ctrl_ops, V4L2_CID_BRIGHTNESS,
760           SUR40_BRIGHTNESS_MIN, SUR40_BRIGHTNESS_MAX, 1, clamp(brightness,
761           (uint)SUR40_BRIGHTNESS_MIN, (uint)SUR40_BRIGHTNESS_MAX));
762
763         v4l2_ctrl_new_std(&sur40->hdl, &sur40_ctrl_ops, V4L2_CID_CONTRAST,
764           SUR40_CONTRAST_MIN, SUR40_CONTRAST_MAX, 1, clamp(contrast,
765           (uint)SUR40_CONTRAST_MIN, (uint)SUR40_CONTRAST_MAX));
766
767         v4l2_ctrl_new_std(&sur40->hdl, &sur40_ctrl_ops, V4L2_CID_GAIN,
768           SUR40_GAIN_MIN, SUR40_GAIN_MAX, 1, clamp(gain,
769           (uint)SUR40_GAIN_MIN, (uint)SUR40_GAIN_MAX));
770
771         v4l2_ctrl_new_std(&sur40->hdl, &sur40_ctrl_ops,
772           V4L2_CID_BACKLIGHT_COMPENSATION, SUR40_BACKLIGHT_MIN,
773           SUR40_BACKLIGHT_MAX, 1, SUR40_BACKLIGHT_DEF);
774
775         v4l2_ctrl_handler_setup(&sur40->hdl);
776
777         if (sur40->hdl.error) {
778                 dev_err(&interface->dev,
779                         "Unable to register video controls.");
780                 v4l2_ctrl_handler_free(&sur40->hdl);
781                 error = sur40->hdl.error;
782                 goto err_unreg_v4l2;
783         }
784
785         error = video_register_device(&sur40->vdev, VFL_TYPE_TOUCH, -1);
786         if (error) {
787                 dev_err(&interface->dev,
788                         "Unable to register video subdevice.");
789                 goto err_unreg_video;
790         }
791
792         /* we can register the device now, as it is ready */
793         usb_set_intfdata(interface, sur40);
794         dev_dbg(&interface->dev, "%s is now attached\n", DRIVER_DESC);
795
796         return 0;
797
798 err_unreg_video:
799         video_unregister_device(&sur40->vdev);
800 err_unreg_v4l2:
801         v4l2_device_unregister(&sur40->v4l2);
802 err_free_buffer:
803         kfree(sur40->bulk_in_buffer);
804 err_free_polldev:
805         input_free_polled_device(sur40->input);
806 err_free_dev:
807         kfree(sur40);
808
809         return error;
810 }
811
812 /* Unregister device & clean up. */
813 static void sur40_disconnect(struct usb_interface *interface)
814 {
815         struct sur40_state *sur40 = usb_get_intfdata(interface);
816
817         v4l2_ctrl_handler_free(&sur40->hdl);
818         video_unregister_device(&sur40->vdev);
819         v4l2_device_unregister(&sur40->v4l2);
820
821         input_unregister_polled_device(sur40->input);
822         input_free_polled_device(sur40->input);
823         kfree(sur40->bulk_in_buffer);
824         kfree(sur40);
825
826         usb_set_intfdata(interface, NULL);
827         dev_dbg(&interface->dev, "%s is now disconnected\n", DRIVER_DESC);
828 }
829
830 /*
831  * Setup the constraints of the queue: besides setting the number of planes
832  * per buffer and the size and allocation context of each plane, it also
833  * checks if sufficient buffers have been allocated. Usually 3 is a good
834  * minimum number: many DMA engines need a minimum of 2 buffers in the
835  * queue and you need to have another available for userspace processing.
836  */
837 static int sur40_queue_setup(struct vb2_queue *q,
838                        unsigned int *nbuffers, unsigned int *nplanes,
839                        unsigned int sizes[], struct device *alloc_devs[])
840 {
841         struct sur40_state *sur40 = vb2_get_drv_priv(q);
842
843         if (q->num_buffers + *nbuffers < 3)
844                 *nbuffers = 3 - q->num_buffers;
845
846         if (*nplanes)
847                 return sizes[0] < sur40->pix_fmt.sizeimage ? -EINVAL : 0;
848
849         *nplanes = 1;
850         sizes[0] = sur40->pix_fmt.sizeimage;
851
852         return 0;
853 }
854
855 /*
856  * Prepare the buffer for queueing to the DMA engine: check and set the
857  * payload size.
858  */
859 static int sur40_buffer_prepare(struct vb2_buffer *vb)
860 {
861         struct sur40_state *sur40 = vb2_get_drv_priv(vb->vb2_queue);
862         unsigned long size = sur40->pix_fmt.sizeimage;
863
864         if (vb2_plane_size(vb, 0) < size) {
865                 dev_err(&sur40->usbdev->dev, "buffer too small (%lu < %lu)\n",
866                          vb2_plane_size(vb, 0), size);
867                 return -EINVAL;
868         }
869
870         vb2_set_plane_payload(vb, 0, size);
871         return 0;
872 }
873
874 /*
875  * Queue this buffer to the DMA engine.
876  */
877 static void sur40_buffer_queue(struct vb2_buffer *vb)
878 {
879         struct sur40_state *sur40 = vb2_get_drv_priv(vb->vb2_queue);
880         struct sur40_buffer *buf = (struct sur40_buffer *)vb;
881
882         spin_lock(&sur40->qlock);
883         list_add_tail(&buf->list, &sur40->buf_list);
884         spin_unlock(&sur40->qlock);
885 }
886
887 static void return_all_buffers(struct sur40_state *sur40,
888                                enum vb2_buffer_state state)
889 {
890         struct sur40_buffer *buf, *node;
891
892         spin_lock(&sur40->qlock);
893         list_for_each_entry_safe(buf, node, &sur40->buf_list, list) {
894                 vb2_buffer_done(&buf->vb.vb2_buf, state);
895                 list_del(&buf->list);
896         }
897         spin_unlock(&sur40->qlock);
898 }
899
900 /*
901  * Start streaming. First check if the minimum number of buffers have been
902  * queued. If not, then return -ENOBUFS and the vb2 framework will call
903  * this function again the next time a buffer has been queued until enough
904  * buffers are available to actually start the DMA engine.
905  */
906 static int sur40_start_streaming(struct vb2_queue *vq, unsigned int count)
907 {
908         struct sur40_state *sur40 = vb2_get_drv_priv(vq);
909
910         sur40->sequence = 0;
911         return 0;
912 }
913
914 /*
915  * Stop the DMA engine. Any remaining buffers in the DMA queue are dequeued
916  * and passed on to the vb2 framework marked as STATE_ERROR.
917  */
918 static void sur40_stop_streaming(struct vb2_queue *vq)
919 {
920         struct sur40_state *sur40 = vb2_get_drv_priv(vq);
921         vb2_wait_for_all_buffers(vq);
922         sur40->sequence = -1;
923
924         /* Release all active buffers */
925         return_all_buffers(sur40, VB2_BUF_STATE_ERROR);
926 }
927
928 /* V4L ioctl */
929 static int sur40_vidioc_querycap(struct file *file, void *priv,
930                                  struct v4l2_capability *cap)
931 {
932         struct sur40_state *sur40 = video_drvdata(file);
933
934         strlcpy(cap->driver, DRIVER_SHORT, sizeof(cap->driver));
935         strlcpy(cap->card, DRIVER_LONG, sizeof(cap->card));
936         usb_make_path(sur40->usbdev, cap->bus_info, sizeof(cap->bus_info));
937         cap->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_TOUCH |
938                 V4L2_CAP_READWRITE |
939                 V4L2_CAP_STREAMING;
940         cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
941         return 0;
942 }
943
944 static int sur40_vidioc_enum_input(struct file *file, void *priv,
945                                    struct v4l2_input *i)
946 {
947         if (i->index != 0)
948                 return -EINVAL;
949         i->type = V4L2_INPUT_TYPE_TOUCH;
950         i->std = V4L2_STD_UNKNOWN;
951         strlcpy(i->name, "In-Cell Sensor", sizeof(i->name));
952         i->capabilities = 0;
953         return 0;
954 }
955
956 static int sur40_vidioc_s_input(struct file *file, void *priv, unsigned int i)
957 {
958         return (i == 0) ? 0 : -EINVAL;
959 }
960
961 static int sur40_vidioc_g_input(struct file *file, void *priv, unsigned int *i)
962 {
963         *i = 0;
964         return 0;
965 }
966
967 static int sur40_vidioc_try_fmt(struct file *file, void *priv,
968                             struct v4l2_format *f)
969 {
970         switch (f->fmt.pix.pixelformat) {
971         case V4L2_PIX_FMT_GREY:
972                 f->fmt.pix = sur40_pix_format[1];
973                 break;
974
975         default:
976                 f->fmt.pix = sur40_pix_format[0];
977                 break;
978         }
979
980         return 0;
981 }
982
983 static int sur40_vidioc_s_fmt(struct file *file, void *priv,
984                             struct v4l2_format *f)
985 {
986         struct sur40_state *sur40 = video_drvdata(file);
987
988         switch (f->fmt.pix.pixelformat) {
989         case V4L2_PIX_FMT_GREY:
990                 sur40->pix_fmt = sur40_pix_format[1];
991                 break;
992
993         default:
994                 sur40->pix_fmt = sur40_pix_format[0];
995                 break;
996         }
997
998         f->fmt.pix = sur40->pix_fmt;
999         return 0;
1000 }
1001
1002 static int sur40_vidioc_g_fmt(struct file *file, void *priv,
1003                             struct v4l2_format *f)
1004 {
1005         struct sur40_state *sur40 = video_drvdata(file);
1006
1007         f->fmt.pix = sur40->pix_fmt;
1008         return 0;
1009 }
1010
1011 static int sur40_s_ctrl(struct v4l2_ctrl *ctrl)
1012 {
1013         struct sur40_state *sur40  = container_of(ctrl->handler,
1014           struct sur40_state, hdl);
1015         u8 value = sur40->vsvideo;
1016
1017         switch (ctrl->id) {
1018         case V4L2_CID_BRIGHTNESS:
1019                 sur40_set_irlevel(sur40, ctrl->val);
1020                 break;
1021         case V4L2_CID_CONTRAST:
1022                 value = (value & 0x0f) | (ctrl->val << 4);
1023                 sur40_set_vsvideo(sur40, value);
1024                 break;
1025         case V4L2_CID_GAIN:
1026                 value = (value & 0xf0) | (ctrl->val);
1027                 sur40_set_vsvideo(sur40, value);
1028                 break;
1029         case V4L2_CID_BACKLIGHT_COMPENSATION:
1030                 sur40_set_preprocessor(sur40, ctrl->val);
1031                 break;
1032         }
1033         return 0;
1034 }
1035
1036 static int sur40_ioctl_parm(struct file *file, void *priv,
1037                             struct v4l2_streamparm *p)
1038 {
1039         if (p->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
1040                 return -EINVAL;
1041
1042         p->parm.capture.capability = V4L2_CAP_TIMEPERFRAME;
1043         p->parm.capture.timeperframe.numerator = 1;
1044         p->parm.capture.timeperframe.denominator = 60;
1045         p->parm.capture.readbuffers = 3;
1046         return 0;
1047 }
1048
1049 static int sur40_vidioc_enum_fmt(struct file *file, void *priv,
1050                                  struct v4l2_fmtdesc *f)
1051 {
1052         if (f->index >= ARRAY_SIZE(sur40_pix_format))
1053                 return -EINVAL;
1054
1055         f->pixelformat = sur40_pix_format[f->index].pixelformat;
1056         f->flags = 0;
1057         return 0;
1058 }
1059
1060 static int sur40_vidioc_enum_framesizes(struct file *file, void *priv,
1061                                         struct v4l2_frmsizeenum *f)
1062 {
1063         struct sur40_state *sur40 = video_drvdata(file);
1064
1065         if ((f->index != 0) || ((f->pixel_format != V4L2_TCH_FMT_TU08)
1066                 && (f->pixel_format != V4L2_PIX_FMT_GREY)))
1067                 return -EINVAL;
1068
1069         f->type = V4L2_FRMSIZE_TYPE_DISCRETE;
1070         f->discrete.width  = sur40->pix_fmt.width;
1071         f->discrete.height = sur40->pix_fmt.height;
1072         return 0;
1073 }
1074
1075 static int sur40_vidioc_enum_frameintervals(struct file *file, void *priv,
1076                                             struct v4l2_frmivalenum *f)
1077 {
1078         struct sur40_state *sur40 = video_drvdata(file);
1079
1080         if ((f->index > 0) || ((f->pixel_format != V4L2_TCH_FMT_TU08)
1081                 && (f->pixel_format != V4L2_PIX_FMT_GREY))
1082                 || (f->width  != sur40->pix_fmt.width)
1083                 || (f->height != sur40->pix_fmt.height))
1084                 return -EINVAL;
1085
1086         f->type = V4L2_FRMIVAL_TYPE_DISCRETE;
1087         f->discrete.denominator  = 60;
1088         f->discrete.numerator = 1;
1089         return 0;
1090 }
1091
1092
1093 static const struct usb_device_id sur40_table[] = {
1094         { USB_DEVICE(ID_MICROSOFT, ID_SUR40) },  /* Samsung SUR40 */
1095         { }                                      /* terminating null entry */
1096 };
1097 MODULE_DEVICE_TABLE(usb, sur40_table);
1098
1099 /* V4L2 structures */
1100 static const struct vb2_ops sur40_queue_ops = {
1101         .queue_setup            = sur40_queue_setup,
1102         .buf_prepare            = sur40_buffer_prepare,
1103         .buf_queue              = sur40_buffer_queue,
1104         .start_streaming        = sur40_start_streaming,
1105         .stop_streaming         = sur40_stop_streaming,
1106         .wait_prepare           = vb2_ops_wait_prepare,
1107         .wait_finish            = vb2_ops_wait_finish,
1108 };
1109
1110 static const struct vb2_queue sur40_queue = {
1111         .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
1112         /*
1113          * VB2_USERPTR in currently not enabled: passing a user pointer to
1114          * dma-sg will result in segment sizes that are not a multiple of
1115          * 512 bytes, which is required by the host controller.
1116         */
1117         .io_modes = VB2_MMAP | VB2_READ | VB2_DMABUF,
1118         .buf_struct_size = sizeof(struct sur40_buffer),
1119         .ops = &sur40_queue_ops,
1120         .mem_ops = &vb2_dma_sg_memops,
1121         .timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC,
1122         .min_buffers_needed = 3,
1123 };
1124
1125 static const struct v4l2_file_operations sur40_video_fops = {
1126         .owner = THIS_MODULE,
1127         .open = v4l2_fh_open,
1128         .release = vb2_fop_release,
1129         .unlocked_ioctl = video_ioctl2,
1130         .read = vb2_fop_read,
1131         .mmap = vb2_fop_mmap,
1132         .poll = vb2_fop_poll,
1133 };
1134
1135 static const struct v4l2_ioctl_ops sur40_video_ioctl_ops = {
1136
1137         .vidioc_querycap        = sur40_vidioc_querycap,
1138
1139         .vidioc_enum_fmt_vid_cap = sur40_vidioc_enum_fmt,
1140         .vidioc_try_fmt_vid_cap = sur40_vidioc_try_fmt,
1141         .vidioc_s_fmt_vid_cap   = sur40_vidioc_s_fmt,
1142         .vidioc_g_fmt_vid_cap   = sur40_vidioc_g_fmt,
1143
1144         .vidioc_enum_framesizes = sur40_vidioc_enum_framesizes,
1145         .vidioc_enum_frameintervals = sur40_vidioc_enum_frameintervals,
1146
1147         .vidioc_g_parm = sur40_ioctl_parm,
1148         .vidioc_s_parm = sur40_ioctl_parm,
1149
1150         .vidioc_enum_input      = sur40_vidioc_enum_input,
1151         .vidioc_g_input         = sur40_vidioc_g_input,
1152         .vidioc_s_input         = sur40_vidioc_s_input,
1153
1154         .vidioc_reqbufs         = vb2_ioctl_reqbufs,
1155         .vidioc_create_bufs     = vb2_ioctl_create_bufs,
1156         .vidioc_querybuf        = vb2_ioctl_querybuf,
1157         .vidioc_qbuf            = vb2_ioctl_qbuf,
1158         .vidioc_dqbuf           = vb2_ioctl_dqbuf,
1159         .vidioc_expbuf          = vb2_ioctl_expbuf,
1160
1161         .vidioc_streamon        = vb2_ioctl_streamon,
1162         .vidioc_streamoff       = vb2_ioctl_streamoff,
1163 };
1164
1165 static const struct video_device sur40_video_device = {
1166         .name = DRIVER_LONG,
1167         .fops = &sur40_video_fops,
1168         .ioctl_ops = &sur40_video_ioctl_ops,
1169         .release = video_device_release_empty,
1170 };
1171
1172 /* USB-specific object needed to register this driver with the USB subsystem. */
1173 static struct usb_driver sur40_driver = {
1174         .name = DRIVER_SHORT,
1175         .probe = sur40_probe,
1176         .disconnect = sur40_disconnect,
1177         .id_table = sur40_table,
1178 };
1179
1180 module_usb_driver(sur40_driver);
1181
1182 MODULE_AUTHOR(DRIVER_AUTHOR);
1183 MODULE_DESCRIPTION(DRIVER_DESC);
1184 MODULE_LICENSE("GPL");