1// SPDX-License-Identifier: GPL-2.0-or-later
2/*
3 * SQ905 subdriver
4 *
5 * Copyright (C) 2008, 2009 Adam Baker and Theodore Kilgore
6 */
7
8/*
9 * History and Acknowledgments
10 *
11 * The original Linux driver for SQ905 based cameras was written by
12 * Marcell Lengyel and further developed by many other contributors
13 * and is available from http://sourceforge.net/projects/sqcam/
14 *
15 * This driver takes advantage of the reverse engineering work done for
16 * that driver and for libgphoto2 but shares no code with them.
17 *
18 * This driver has used as a base the finepix driver and other gspca
19 * based drivers and may still contain code fragments taken from those
20 * drivers.
21 */
22
23#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
24
25#define MODULE_NAME "sq905"
26
27#include <linux/workqueue.h>
28#include <linux/slab.h>
29#include "gspca.h"
30
31MODULE_AUTHOR("Adam Baker <linux@baker-net.org.uk>, Theodore Kilgore <kilgota@auburn.edu>");
32MODULE_DESCRIPTION("GSPCA/SQ905 USB Camera Driver");
33MODULE_LICENSE("GPL");
34
35/* Default timeouts, in ms */
36#define SQ905_CMD_TIMEOUT 500
37#define SQ905_DATA_TIMEOUT 1000
38
39/* Maximum transfer size to use. */
40#define SQ905_MAX_TRANSFER 0x8000
41#define FRAME_HEADER_LEN 64
42
43/* The known modes, or registers. These go in the "value" slot. */
44
45/* 00 is "none" obviously */
46
47#define SQ905_BULK_READ	0x03	/* precedes any bulk read */
48#define SQ905_COMMAND	0x06	/* precedes the command codes below */
49#define SQ905_PING	0x07	/* when reading an "idling" command */
50#define SQ905_READ_DONE 0xc0    /* ack bulk read completed */
51
52/* Any non-zero value in the bottom 2 bits of the 2nd byte of
53 * the ID appears to indicate the camera can do 640*480. If the
54 * LSB of that byte is set the image is just upside down, otherwise
55 * it is rotated 180 degrees. */
56#define SQ905_HIRES_MASK	0x00000300
57#define SQ905_ORIENTATION_MASK	0x00000100
58
59/* Some command codes. These go in the "index" slot. */
60
61#define SQ905_ID      0xf0	/* asks for model string */
62#define SQ905_CONFIG  0x20	/* gets photo alloc. table, not used here */
63#define SQ905_DATA    0x30	/* accesses photo data, not used here */
64#define SQ905_CLEAR   0xa0	/* clear everything */
65#define SQ905_CAPTURE_LOW  0x60	/* Starts capture at 160x120 */
66#define SQ905_CAPTURE_MED  0x61	/* Starts capture at 320x240 */
67#define SQ905_CAPTURE_HIGH 0x62	/* Starts capture at 640x480 (some cams only) */
68/* note that the capture command also controls the output dimensions */
69
70/* Structure to hold all of our device specific stuff */
71struct sd {
72	struct gspca_dev gspca_dev;	/* !! must be the first item */
73
74	/*
75	 * Driver stuff
76	 */
77	struct work_struct work_struct;
78	struct workqueue_struct *work_thread;
79};
80
81static struct v4l2_pix_format sq905_mode[] = {
82	{ 160, 120, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
83		.bytesperline = 160,
84		.sizeimage = 160 * 120,
85		.colorspace = V4L2_COLORSPACE_SRGB,
86		.priv = 0},
87	{ 320, 240, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
88		.bytesperline = 320,
89		.sizeimage = 320 * 240,
90		.colorspace = V4L2_COLORSPACE_SRGB,
91		.priv = 0},
92	{ 640, 480, V4L2_PIX_FMT_SBGGR8, V4L2_FIELD_NONE,
93		.bytesperline = 640,
94		.sizeimage = 640 * 480,
95		.colorspace = V4L2_COLORSPACE_SRGB,
96		.priv = 0}
97};
98
99/*
100 * Send a command to the camera.
101 */
102static int sq905_command(struct gspca_dev *gspca_dev, u16 index)
103{
104	int ret;
105
106	gspca_dev->usb_buf[0] = '\0';
107	ret = usb_control_msg(gspca_dev->dev,
108			      usb_sndctrlpipe(gspca_dev->dev, 0),
109			      USB_REQ_SYNCH_FRAME,                /* request */
110			      USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
111			      SQ905_COMMAND, index, gspca_dev->usb_buf, 1,
112			      SQ905_CMD_TIMEOUT);
113	if (ret < 0) {
114		pr_err("%s: usb_control_msg failed (%d)\n", __func__, ret);
115		return ret;
116	}
117
118	ret = usb_control_msg(gspca_dev->dev,
119			      usb_rcvctrlpipe(gspca_dev->dev, 0),
120			      USB_REQ_SYNCH_FRAME,                /* request */
121			      USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
122			      SQ905_PING, 0, gspca_dev->usb_buf, 1,
123			      SQ905_CMD_TIMEOUT);
124	if (ret < 0) {
125		pr_err("%s: usb_control_msg failed 2 (%d)\n", __func__, ret);
126		return ret;
127	}
128
129	return 0;
130}
131
132/*
133 * Acknowledge the end of a frame - see warning on sq905_command.
134 */
135static int sq905_ack_frame(struct gspca_dev *gspca_dev)
136{
137	int ret;
138
139	gspca_dev->usb_buf[0] = '\0';
140	ret = usb_control_msg(gspca_dev->dev,
141			      usb_sndctrlpipe(gspca_dev->dev, 0),
142			      USB_REQ_SYNCH_FRAME,                /* request */
143			      USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
144			      SQ905_READ_DONE, 0, gspca_dev->usb_buf, 1,
145			      SQ905_CMD_TIMEOUT);
146	if (ret < 0) {
147		pr_err("%s: usb_control_msg failed (%d)\n", __func__, ret);
148		return ret;
149	}
150
151	return 0;
152}
153
154/*
155 *  request and read a block of data - see warning on sq905_command.
156 */
157static int
158sq905_read_data(struct gspca_dev *gspca_dev, u8 *data, int size, int need_lock)
159{
160	int ret;
161	int act_len = 0;
162
163	gspca_dev->usb_buf[0] = '\0';
164	if (need_lock)
165		mutex_lock(&gspca_dev->usb_lock);
166	ret = usb_control_msg(gspca_dev->dev,
167			      usb_sndctrlpipe(gspca_dev->dev, 0),
168			      USB_REQ_SYNCH_FRAME,                /* request */
169			      USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
170			      SQ905_BULK_READ, size, gspca_dev->usb_buf,
171			      1, SQ905_CMD_TIMEOUT);
172	if (need_lock)
173		mutex_unlock(&gspca_dev->usb_lock);
174	if (ret < 0) {
175		pr_err("%s: usb_control_msg failed (%d)\n", __func__, ret);
176		return ret;
177	}
178	ret = usb_bulk_msg(gspca_dev->dev,
179			   usb_rcvbulkpipe(gspca_dev->dev, 0x81),
180			   data, size, &act_len, SQ905_DATA_TIMEOUT);
181
182	/* successful, it returns 0, otherwise  negative */
183	if (ret < 0 || act_len != size) {
184		pr_err("bulk read fail (%d) len %d/%d\n", ret, act_len, size);
185		return -EIO;
186	}
187	return 0;
188}
189
190/*
191 * This function is called as a workqueue function and runs whenever the camera
192 * is streaming data. Because it is a workqueue function it is allowed to sleep
193 * so we can use synchronous USB calls. To avoid possible collisions with other
194 * threads attempting to use gspca_dev->usb_buf we take the usb_lock when
195 * performing USB operations using it. In practice we don't really need this
196 * as the camera doesn't provide any controls.
197 */
198static void sq905_dostream(struct work_struct *work)
199{
200	struct sd *dev = container_of(work, struct sd, work_struct);
201	struct gspca_dev *gspca_dev = &dev->gspca_dev;
202	int bytes_left; /* bytes remaining in current frame. */
203	int data_len;   /* size to use for the next read. */
204	int header_read; /* true if we have already read the frame header. */
205	int packet_type;
206	int frame_sz;
207	int ret;
208	u8 *data;
209	u8 *buffer;
210
211	buffer = kmalloc(SQ905_MAX_TRANSFER, GFP_KERNEL);
212	if (!buffer) {
213		pr_err("Couldn't allocate USB buffer\n");
214		goto quit_stream;
215	}
216
217	frame_sz = gspca_dev->cam.cam_mode[gspca_dev->curr_mode].sizeimage
218			+ FRAME_HEADER_LEN;
219
220	while (gspca_dev->present && gspca_dev->streaming) {
221#ifdef CONFIG_PM
222		if (gspca_dev->frozen)
223			break;
224#endif
225		/* request some data and then read it until we have
226		 * a complete frame. */
227		bytes_left = frame_sz;
228		header_read = 0;
229
230		/* Note we do not check for gspca_dev->streaming here, as
231		   we must finish reading an entire frame, otherwise the
232		   next time we stream we start reading in the middle of a
233		   frame. */
234		while (bytes_left > 0 && gspca_dev->present) {
235			data_len = bytes_left > SQ905_MAX_TRANSFER ?
236				SQ905_MAX_TRANSFER : bytes_left;
237			ret = sq905_read_data(gspca_dev, buffer, data_len, 1);
238			if (ret < 0)
239				goto quit_stream;
240			gspca_dbg(gspca_dev, D_PACK,
241				  "Got %d bytes out of %d for frame\n",
242				  data_len, bytes_left);
243			bytes_left -= data_len;
244			data = buffer;
245			if (!header_read) {
246				packet_type = FIRST_PACKET;
247				/* The first 64 bytes of each frame are
248				 * a header full of FF 00 bytes */
249				data += FRAME_HEADER_LEN;
250				data_len -= FRAME_HEADER_LEN;
251				header_read = 1;
252			} else if (bytes_left == 0) {
253				packet_type = LAST_PACKET;
254			} else {
255				packet_type = INTER_PACKET;
256			}
257			gspca_frame_add(gspca_dev, packet_type,
258					data, data_len);
259			/* If entire frame fits in one packet we still
260			   need to add a LAST_PACKET */
261			if (packet_type == FIRST_PACKET &&
262			    bytes_left == 0)
263				gspca_frame_add(gspca_dev, LAST_PACKET,
264						NULL, 0);
265		}
266		if (gspca_dev->present) {
267			/* acknowledge the frame */
268			mutex_lock(&gspca_dev->usb_lock);
269			ret = sq905_ack_frame(gspca_dev);
270			mutex_unlock(&gspca_dev->usb_lock);
271			if (ret < 0)
272				goto quit_stream;
273		}
274	}
275quit_stream:
276	if (gspca_dev->present) {
277		mutex_lock(&gspca_dev->usb_lock);
278		sq905_command(gspca_dev, SQ905_CLEAR);
279		mutex_unlock(&gspca_dev->usb_lock);
280	}
281	kfree(buffer);
282}
283
284/* This function is called at probe time just before sd_init */
285static int sd_config(struct gspca_dev *gspca_dev,
286		const struct usb_device_id *id)
287{
288	struct cam *cam = &gspca_dev->cam;
289	struct sd *dev = (struct sd *) gspca_dev;
290
291	/* We don't use the buffer gspca allocates so make it small. */
292	cam->bulk = 1;
293	cam->bulk_size = 64;
294
295	INIT_WORK(&dev->work_struct, sq905_dostream);
296
297	return 0;
298}
299
300/* called on streamoff with alt==0 and on disconnect */
301/* the usb_lock is held at entry - restore on exit */
302static void sd_stop0(struct gspca_dev *gspca_dev)
303{
304	struct sd *dev = (struct sd *) gspca_dev;
305
306	/* wait for the work queue to terminate */
307	mutex_unlock(&gspca_dev->usb_lock);
308	/* This waits for sq905_dostream to finish */
309	destroy_workqueue(dev->work_thread);
310	dev->work_thread = NULL;
311	mutex_lock(&gspca_dev->usb_lock);
312}
313
314/* this function is called at probe and resume time */
315static int sd_init(struct gspca_dev *gspca_dev)
316{
317	u32 ident;
318	int ret;
319
320	/* connect to the camera and read
321	 * the model ID and process that and put it away.
322	 */
323	ret = sq905_command(gspca_dev, SQ905_CLEAR);
324	if (ret < 0)
325		return ret;
326	ret = sq905_command(gspca_dev, SQ905_ID);
327	if (ret < 0)
328		return ret;
329	ret = sq905_read_data(gspca_dev, gspca_dev->usb_buf, 4, 0);
330	if (ret < 0)
331		return ret;
332	/* usb_buf is allocated with kmalloc so is aligned.
333	 * Camera model number is the right way round if we assume this
334	 * reverse engineered ID is supposed to be big endian. */
335	ident = be32_to_cpup((__be32 *)gspca_dev->usb_buf);
336	ret = sq905_command(gspca_dev, SQ905_CLEAR);
337	if (ret < 0)
338		return ret;
339	gspca_dbg(gspca_dev, D_CONF, "SQ905 camera ID %08x detected\n", ident);
340	gspca_dev->cam.cam_mode = sq905_mode;
341	gspca_dev->cam.nmodes = ARRAY_SIZE(sq905_mode);
342	if (!(ident & SQ905_HIRES_MASK))
343		gspca_dev->cam.nmodes--;
344
345	if (ident & SQ905_ORIENTATION_MASK)
346		gspca_dev->cam.input_flags = V4L2_IN_ST_VFLIP;
347	else
348		gspca_dev->cam.input_flags = V4L2_IN_ST_VFLIP |
349					     V4L2_IN_ST_HFLIP;
350	return 0;
351}
352
353/* Set up for getting frames. */
354static int sd_start(struct gspca_dev *gspca_dev)
355{
356	struct sd *dev = (struct sd *) gspca_dev;
357	int ret;
358
359	/* "Open the shutter" and set size, to start capture */
360	switch (gspca_dev->curr_mode) {
361	default:
362/*	case 2: */
363		gspca_dbg(gspca_dev, D_STREAM, "Start streaming at high resolution\n");
364		ret = sq905_command(&dev->gspca_dev, SQ905_CAPTURE_HIGH);
365		break;
366	case 1:
367		gspca_dbg(gspca_dev, D_STREAM, "Start streaming at medium resolution\n");
368		ret = sq905_command(&dev->gspca_dev, SQ905_CAPTURE_MED);
369		break;
370	case 0:
371		gspca_dbg(gspca_dev, D_STREAM, "Start streaming at low resolution\n");
372		ret = sq905_command(&dev->gspca_dev, SQ905_CAPTURE_LOW);
373	}
374
375	if (ret < 0) {
376		gspca_err(gspca_dev, "Start streaming command failed\n");
377		return ret;
378	}
379	/* Start the workqueue function to do the streaming */
380	dev->work_thread = create_singlethread_workqueue(MODULE_NAME);
381	if (!dev->work_thread)
382		return -ENOMEM;
383
384	queue_work(dev->work_thread, &dev->work_struct);
385
386	return 0;
387}
388
389/* Table of supported USB devices */
390static const struct usb_device_id device_table[] = {
391	{USB_DEVICE(0x2770, 0x9120)},
392	{}
393};
394
395MODULE_DEVICE_TABLE(usb, device_table);
396
397/* sub-driver description */
398static const struct sd_desc sd_desc = {
399	.name   = MODULE_NAME,
400	.config = sd_config,
401	.init   = sd_init,
402	.start  = sd_start,
403	.stop0  = sd_stop0,
404};
405
406/* -- device connect -- */
407static int sd_probe(struct usb_interface *intf,
408		const struct usb_device_id *id)
409{
410	return gspca_dev_probe(intf, id,
411			&sd_desc,
412			sizeof(struct sd),
413			THIS_MODULE);
414}
415
416static struct usb_driver sd_driver = {
417	.name       = MODULE_NAME,
418	.id_table   = device_table,
419	.probe      = sd_probe,
420	.disconnect = gspca_disconnect,
421#ifdef CONFIG_PM
422	.suspend = gspca_suspend,
423	.resume  = gspca_resume,
424	.reset_resume = gspca_resume,
425#endif
426};
427
428module_usb_driver(sd_driver);
429