cpia.c 112.1 KB
Newer Older
L
Linus Torvalds 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/*
 * cpia CPiA driver
 *
 * Supports CPiA based Video Camera's.
 *
 * (C) Copyright 1999-2000 Peter Pregler
 * (C) Copyright 1999-2000 Scott J. Bertin
 * (C) Copyright 1999-2000 Johannes Erdfelt <johannes@erdfelt.com>
 * (C) Copyright 2000 STMicroelectronics
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/* define _CPIA_DEBUG_ for verbose debug output (see cpia.h) */
27
/* #define _CPIA_DEBUG_  1 */
L
Linus Torvalds 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41

#include <linux/config.h>

#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
#include <linux/proc_fs.h>
#include <linux/ctype.h>
#include <linux/pagemap.h>
#include <linux/delay.h>
#include <asm/io.h>
42
#include <linux/mutex.h>
L
Linus Torvalds 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60

#ifdef CONFIG_KMOD
#include <linux/kmod.h>
#endif

#include "cpia.h"

#ifdef CONFIG_VIDEO_CPIA_PP
extern int cpia_pp_init(void);
#endif
#ifdef CONFIG_VIDEO_CPIA_USB
extern int cpia_usb_init(void);
#endif

static int video_nr = -1;

#ifdef MODULE
module_param(video_nr, int, 0);
61
MODULE_AUTHOR("Scott J. Bertin <sbertin@securenym.net> & Peter Pregler <Peter_Pregler@email.com> & Johannes Erdfelt <johannes@erdfelt.com>");
L
Linus Torvalds 已提交
62 63 64 65 66 67 68 69
MODULE_DESCRIPTION("V4L-driver for Vision CPiA based cameras");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("video");
#endif

static unsigned short colorspace_conv = 0;
module_param(colorspace_conv, ushort, 0444);
MODULE_PARM_DESC(colorspace_conv,
70 71 72 73 74
		 "\n<n> Colorspace conversion:"
		 "\n0 = disable"
		 "\n1 = enable"
		 "\nDefault value is 0"
		 "\n");
L
Linus Torvalds 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191

#define ABOUT "V4L-Driver for Vision CPiA based cameras"

#ifndef VID_HARDWARE_CPIA
#define VID_HARDWARE_CPIA 24    /* FIXME -> from linux/videodev.h */
#endif

#define CPIA_MODULE_CPIA			(0<<5)
#define CPIA_MODULE_SYSTEM			(1<<5)
#define CPIA_MODULE_VP_CTRL			(5<<5)
#define CPIA_MODULE_CAPTURE			(6<<5)
#define CPIA_MODULE_DEBUG			(7<<5)

#define INPUT (DATA_IN << 8)
#define OUTPUT (DATA_OUT << 8)

#define CPIA_COMMAND_GetCPIAVersion	(INPUT | CPIA_MODULE_CPIA | 1)
#define CPIA_COMMAND_GetPnPID		(INPUT | CPIA_MODULE_CPIA | 2)
#define CPIA_COMMAND_GetCameraStatus	(INPUT | CPIA_MODULE_CPIA | 3)
#define CPIA_COMMAND_GotoHiPower	(OUTPUT | CPIA_MODULE_CPIA | 4)
#define CPIA_COMMAND_GotoLoPower	(OUTPUT | CPIA_MODULE_CPIA | 5)
#define CPIA_COMMAND_GotoSuspend	(OUTPUT | CPIA_MODULE_CPIA | 7)
#define CPIA_COMMAND_GotoPassThrough	(OUTPUT | CPIA_MODULE_CPIA | 8)
#define CPIA_COMMAND_ModifyCameraStatus	(OUTPUT | CPIA_MODULE_CPIA | 10)

#define CPIA_COMMAND_ReadVCRegs		(INPUT | CPIA_MODULE_SYSTEM | 1)
#define CPIA_COMMAND_WriteVCReg		(OUTPUT | CPIA_MODULE_SYSTEM | 2)
#define CPIA_COMMAND_ReadMCPorts	(INPUT | CPIA_MODULE_SYSTEM | 3)
#define CPIA_COMMAND_WriteMCPort	(OUTPUT | CPIA_MODULE_SYSTEM | 4)
#define CPIA_COMMAND_SetBaudRate	(OUTPUT | CPIA_MODULE_SYSTEM | 5)
#define CPIA_COMMAND_SetECPTiming	(OUTPUT | CPIA_MODULE_SYSTEM | 6)
#define CPIA_COMMAND_ReadIDATA		(INPUT | CPIA_MODULE_SYSTEM | 7)
#define CPIA_COMMAND_WriteIDATA		(OUTPUT | CPIA_MODULE_SYSTEM | 8)
#define CPIA_COMMAND_GenericCall	(OUTPUT | CPIA_MODULE_SYSTEM | 9)
#define CPIA_COMMAND_I2CStart		(OUTPUT | CPIA_MODULE_SYSTEM | 10)
#define CPIA_COMMAND_I2CStop		(OUTPUT | CPIA_MODULE_SYSTEM | 11)
#define CPIA_COMMAND_I2CWrite		(OUTPUT | CPIA_MODULE_SYSTEM | 12)
#define CPIA_COMMAND_I2CRead		(INPUT | CPIA_MODULE_SYSTEM | 13)

#define CPIA_COMMAND_GetVPVersion	(INPUT | CPIA_MODULE_VP_CTRL | 1)
#define CPIA_COMMAND_ResetFrameCounter	(INPUT | CPIA_MODULE_VP_CTRL | 2)
#define CPIA_COMMAND_SetColourParams	(OUTPUT | CPIA_MODULE_VP_CTRL | 3)
#define CPIA_COMMAND_SetExposure	(OUTPUT | CPIA_MODULE_VP_CTRL | 4)
#define CPIA_COMMAND_SetColourBalance	(OUTPUT | CPIA_MODULE_VP_CTRL | 6)
#define CPIA_COMMAND_SetSensorFPS	(OUTPUT | CPIA_MODULE_VP_CTRL | 7)
#define CPIA_COMMAND_SetVPDefaults	(OUTPUT | CPIA_MODULE_VP_CTRL | 8)
#define CPIA_COMMAND_SetApcor		(OUTPUT | CPIA_MODULE_VP_CTRL | 9)
#define CPIA_COMMAND_SetFlickerCtrl	(OUTPUT | CPIA_MODULE_VP_CTRL | 10)
#define CPIA_COMMAND_SetVLOffset	(OUTPUT | CPIA_MODULE_VP_CTRL | 11)
#define CPIA_COMMAND_GetColourParams	(INPUT | CPIA_MODULE_VP_CTRL | 16)
#define CPIA_COMMAND_GetColourBalance	(INPUT | CPIA_MODULE_VP_CTRL | 17)
#define CPIA_COMMAND_GetExposure	(INPUT | CPIA_MODULE_VP_CTRL | 18)
#define CPIA_COMMAND_SetSensorMatrix	(OUTPUT | CPIA_MODULE_VP_CTRL | 19)
#define CPIA_COMMAND_ColourBars		(OUTPUT | CPIA_MODULE_VP_CTRL | 25)
#define CPIA_COMMAND_ReadVPRegs		(INPUT | CPIA_MODULE_VP_CTRL | 30)
#define CPIA_COMMAND_WriteVPReg		(OUTPUT | CPIA_MODULE_VP_CTRL | 31)

#define CPIA_COMMAND_GrabFrame		(OUTPUT | CPIA_MODULE_CAPTURE | 1)
#define CPIA_COMMAND_UploadFrame	(OUTPUT | CPIA_MODULE_CAPTURE | 2)
#define CPIA_COMMAND_SetGrabMode	(OUTPUT | CPIA_MODULE_CAPTURE | 3)
#define CPIA_COMMAND_InitStreamCap	(OUTPUT | CPIA_MODULE_CAPTURE | 4)
#define CPIA_COMMAND_FiniStreamCap	(OUTPUT | CPIA_MODULE_CAPTURE | 5)
#define CPIA_COMMAND_StartStreamCap	(OUTPUT | CPIA_MODULE_CAPTURE | 6)
#define CPIA_COMMAND_EndStreamCap	(OUTPUT | CPIA_MODULE_CAPTURE | 7)
#define CPIA_COMMAND_SetFormat		(OUTPUT | CPIA_MODULE_CAPTURE | 8)
#define CPIA_COMMAND_SetROI		(OUTPUT | CPIA_MODULE_CAPTURE | 9)
#define CPIA_COMMAND_SetCompression	(OUTPUT | CPIA_MODULE_CAPTURE | 10)
#define CPIA_COMMAND_SetCompressionTarget (OUTPUT | CPIA_MODULE_CAPTURE | 11)
#define CPIA_COMMAND_SetYUVThresh	(OUTPUT | CPIA_MODULE_CAPTURE | 12)
#define CPIA_COMMAND_SetCompressionParams (OUTPUT | CPIA_MODULE_CAPTURE | 13)
#define CPIA_COMMAND_DiscardFrame	(OUTPUT | CPIA_MODULE_CAPTURE | 14)
#define CPIA_COMMAND_GrabReset		(OUTPUT | CPIA_MODULE_CAPTURE | 15)

#define CPIA_COMMAND_OutputRS232	(OUTPUT | CPIA_MODULE_DEBUG | 1)
#define CPIA_COMMAND_AbortProcess	(OUTPUT | CPIA_MODULE_DEBUG | 4)
#define CPIA_COMMAND_SetDramPage	(OUTPUT | CPIA_MODULE_DEBUG | 5)
#define CPIA_COMMAND_StartDramUpload	(OUTPUT | CPIA_MODULE_DEBUG | 6)
#define CPIA_COMMAND_StartDummyDtream	(OUTPUT | CPIA_MODULE_DEBUG | 8)
#define CPIA_COMMAND_AbortStream	(OUTPUT | CPIA_MODULE_DEBUG | 9)
#define CPIA_COMMAND_DownloadDRAM	(OUTPUT | CPIA_MODULE_DEBUG | 10)
#define CPIA_COMMAND_Null		(OUTPUT | CPIA_MODULE_DEBUG | 11)

enum {
	FRAME_READY,		/* Ready to grab into */
	FRAME_GRABBING,		/* In the process of being grabbed into */
	FRAME_DONE,		/* Finished grabbing, but not been synced yet */
	FRAME_UNUSED,		/* Unused (no MCAPTURE) */
};

#define COMMAND_NONE			0x0000
#define COMMAND_SETCOMPRESSION		0x0001
#define COMMAND_SETCOMPRESSIONTARGET	0x0002
#define COMMAND_SETCOLOURPARAMS		0x0004
#define COMMAND_SETFORMAT		0x0008
#define COMMAND_PAUSE			0x0010
#define COMMAND_RESUME			0x0020
#define COMMAND_SETYUVTHRESH		0x0040
#define COMMAND_SETECPTIMING		0x0080
#define COMMAND_SETCOMPRESSIONPARAMS	0x0100
#define COMMAND_SETEXPOSURE		0x0200
#define COMMAND_SETCOLOURBALANCE	0x0400
#define COMMAND_SETSENSORFPS		0x0800
#define COMMAND_SETAPCOR		0x1000
#define COMMAND_SETFLICKERCTRL		0x2000
#define COMMAND_SETVLOFFSET		0x4000
#define COMMAND_SETLIGHTS		0x8000

#define ROUND_UP_EXP_FOR_FLICKER 15

/* Constants for automatic frame rate adjustment */
#define MAX_EXP       302
#define MAX_EXP_102   255
#define LOW_EXP       140
#define VERY_LOW_EXP   70
#define TC             94
#define	EXP_ACC_DARK   50
#define	EXP_ACC_LIGHT  90
192 193
#define HIGH_COMP_102 160
#define MAX_COMP      239
L
Linus Torvalds 已提交
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
#define DARK_TIME       3
#define LIGHT_TIME      3

/* Maximum number of 10ms loops to wait for the stream to become ready */
#define READY_TIMEOUT 100

/* Developer's Guide Table 5 p 3-34
 * indexed by [mains][sensorFps.baserate][sensorFps.divisor]*/
static u8 flicker_jumps[2][2][4] =
{ { { 76, 38, 19, 9 }, { 92, 46, 23, 11 } },
  { { 64, 32, 16, 8 }, { 76, 38, 19, 9} }
};

/* forward declaration of local function */
static void reset_camera_struct(struct cam_data *cam);
static int find_over_exposure(int brightness);
static void set_flicker(struct cam_params *params, volatile u32 *command_flags,
211
			int on);
L
Linus Torvalds 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264


/**********************************************************************
 *
 * Memory management
 *
 **********************************************************************/
static void *rvmalloc(unsigned long size)
{
	void *mem;
	unsigned long adr;

	size = PAGE_ALIGN(size);
	mem = vmalloc_32(size);
	if (!mem)
		return NULL;

	memset(mem, 0, size); /* Clear the ram out, no junk to the user */
	adr = (unsigned long) mem;
	while (size > 0) {
		SetPageReserved(vmalloc_to_page((void *)adr));
		adr += PAGE_SIZE;
		size -= PAGE_SIZE;
	}

	return mem;
}

static void rvfree(void *mem, unsigned long size)
{
	unsigned long adr;

	if (!mem)
		return;

	adr = (unsigned long) mem;
	while ((long) size > 0) {
		ClearPageReserved(vmalloc_to_page((void *)adr));
		adr += PAGE_SIZE;
		size -= PAGE_SIZE;
	}
	vfree(mem);
}

/**********************************************************************
 *
 * /proc interface
 *
 **********************************************************************/
#ifdef CONFIG_PROC_FS
static struct proc_dir_entry *cpia_proc_root=NULL;

static int cpia_read_proc(char *page, char **start, off_t off,
265
			  int count, int *eof, void *data)
L
Linus Torvalds 已提交
266 267 268 269 270 271 272 273 274 275 276 277 278
{
	char *out = page;
	int len, tmp;
	struct cam_data *cam = data;
	char tmpstr[29];

	/* IMPORTANT: This output MUST be kept under PAGE_SIZE
	 *            or we need to get more sophisticated. */

	out += sprintf(out, "read-only\n-----------------------\n");
	out += sprintf(out, "V4L Driver version:       %d.%d.%d\n",
		       CPIA_MAJ_VER, CPIA_MIN_VER, CPIA_PATCH_VER);
	out += sprintf(out, "CPIA Version:             %d.%02d (%d.%d)\n",
279 280 281 282
		       cam->params.version.firmwareVersion,
		       cam->params.version.firmwareRevision,
		       cam->params.version.vcVersion,
		       cam->params.version.vcRevision);
L
Linus Torvalds 已提交
283
	out += sprintf(out, "CPIA PnP-ID:              %04x:%04x:%04x\n",
284 285
		       cam->params.pnpID.vendor, cam->params.pnpID.product,
		       cam->params.pnpID.deviceRevision);
L
Linus Torvalds 已提交
286
	out += sprintf(out, "VP-Version:               %d.%d %04x\n",
287 288 289 290
		       cam->params.vpVersion.vpVersion,
		       cam->params.vpVersion.vpRevision,
		       cam->params.vpVersion.cameraHeadID);

L
Linus Torvalds 已提交
291
	out += sprintf(out, "system_state:             %#04x\n",
292
		       cam->params.status.systemState);
L
Linus Torvalds 已提交
293
	out += sprintf(out, "grab_state:               %#04x\n",
294
		       cam->params.status.grabState);
L
Linus Torvalds 已提交
295
	out += sprintf(out, "stream_state:             %#04x\n",
296
		       cam->params.status.streamState);
L
Linus Torvalds 已提交
297
	out += sprintf(out, "fatal_error:              %#04x\n",
298
		       cam->params.status.fatalError);
L
Linus Torvalds 已提交
299
	out += sprintf(out, "cmd_error:                %#04x\n",
300
		       cam->params.status.cmdError);
L
Linus Torvalds 已提交
301
	out += sprintf(out, "debug_flags:              %#04x\n",
302
		       cam->params.status.debugFlags);
L
Linus Torvalds 已提交
303
	out += sprintf(out, "vp_status:                %#04x\n",
304
		       cam->params.status.vpStatus);
L
Linus Torvalds 已提交
305
	out += sprintf(out, "error_code:               %#04x\n",
306
		       cam->params.status.errorCode);
L
Linus Torvalds 已提交
307 308 309
	/* QX3 specific entries */
	if (cam->params.qx3.qx3_detected) {
		out += sprintf(out, "button:                   %4d\n",
310
			       cam->params.qx3.button);
L
Linus Torvalds 已提交
311
		out += sprintf(out, "cradled:                  %4d\n",
312
			       cam->params.qx3.cradled);
L
Linus Torvalds 已提交
313 314
	}
	out += sprintf(out, "video_size:               %s\n",
315
		       cam->params.format.videoSize == VIDEOSIZE_CIF ?
L
Linus Torvalds 已提交
316 317
		       "CIF " : "QCIF");
	out += sprintf(out, "roi:                      (%3d, %3d) to (%3d, %3d)\n",
318 319 320 321
		       cam->params.roi.colStart*8,
		       cam->params.roi.rowStart*4,
		       cam->params.roi.colEnd*8,
		       cam->params.roi.rowEnd*4);
L
Linus Torvalds 已提交
322 323
	out += sprintf(out, "actual_fps:               %3d\n", cam->fps);
	out += sprintf(out, "transfer_rate:            %4dkB/s\n",
324 325
		       cam->transfer_rate);

L
Linus Torvalds 已提交
326 327
	out += sprintf(out, "\nread-write\n");
	out += sprintf(out, "-----------------------  current       min"
328
		       "       max   default  comment\n");
L
Linus Torvalds 已提交
329
	out += sprintf(out, "brightness:             %8d  %8d  %8d  %8d\n",
330
		       cam->params.colourParams.brightness, 0, 100, 50);
L
Linus Torvalds 已提交
331 332 333 334 335 336 337 338
	if (cam->params.version.firmwareVersion == 1 &&
	   cam->params.version.firmwareRevision == 2)
		/* 1-02 firmware limits contrast to 80 */
		tmp = 80;
	else
		tmp = 96;

	out += sprintf(out, "contrast:               %8d  %8d  %8d  %8d"
339 340
		       "  steps of 8\n",
		       cam->params.colourParams.contrast, 0, tmp, 48);
L
Linus Torvalds 已提交
341
	out += sprintf(out, "saturation:             %8d  %8d  %8d  %8d\n",
342
		       cam->params.colourParams.saturation, 0, 100, 50);
L
Linus Torvalds 已提交
343 344 345
	tmp = (25000+5000*cam->params.sensorFps.baserate)/
	      (1<<cam->params.sensorFps.divisor);
	out += sprintf(out, "sensor_fps:             %4d.%03d  %8d  %8d  %8d\n",
346
		       tmp/1000, tmp%1000, 3, 30, 15);
L
Linus Torvalds 已提交
347
	out += sprintf(out, "stream_start_line:      %8d  %8d  %8d  %8d\n",
348
		       2*cam->params.streamStartLine, 0,
L
Linus Torvalds 已提交
349 350 351
		       cam->params.format.videoSize == VIDEOSIZE_CIF ? 288:144,
		       cam->params.format.videoSize == VIDEOSIZE_CIF ? 240:120);
	out += sprintf(out, "sub_sample:             %8s  %8s  %8s  %8s\n",
352
		       cam->params.format.subSample == SUBSAMPLE_420 ?
L
Linus Torvalds 已提交
353 354
		       "420" : "422", "420", "422", "422");
	out += sprintf(out, "yuv_order:              %8s  %8s  %8s  %8s\n",
355
		       cam->params.format.yuvOrder == YUVORDER_YUYV ?
L
Linus Torvalds 已提交
356 357
		       "YUYV" : "UYVY", "YUYV" , "UYVY", "YUYV");
	out += sprintf(out, "ecp_timing:             %8s  %8s  %8s  %8s\n",
358
		       cam->params.ecpTiming ? "slow" : "normal", "slow",
L
Linus Torvalds 已提交
359 360 361 362 363 364 365 366 367 368
		       "normal", "normal");

	if (cam->params.colourBalance.balanceMode == 2) {
		sprintf(tmpstr, "auto");
	} else {
		sprintf(tmpstr, "manual");
	}
	out += sprintf(out, "color_balance_mode:     %8s  %8s  %8s"
		       "  %8s\n",  tmpstr, "manual", "auto", "auto");
	out += sprintf(out, "red_gain:               %8d  %8d  %8d  %8d\n",
369
		       cam->params.colourBalance.redGain, 0, 212, 32);
L
Linus Torvalds 已提交
370
	out += sprintf(out, "green_gain:             %8d  %8d  %8d  %8d\n",
371
		       cam->params.colourBalance.greenGain, 0, 212, 6);
L
Linus Torvalds 已提交
372
	out += sprintf(out, "blue_gain:              %8d  %8d  %8d  %8d\n",
373
		       cam->params.colourBalance.blueGain, 0, 212, 92);
L
Linus Torvalds 已提交
374 375 376 377 378 379 380 381 382 383

	if (cam->params.version.firmwareVersion == 1 &&
	   cam->params.version.firmwareRevision == 2)
		/* 1-02 firmware limits gain to 2 */
		sprintf(tmpstr, "%8d  %8d  %8d", 1, 2, 2);
	else
		sprintf(tmpstr, "%8d  %8d  %8d", 1, 8, 2);

	if (cam->params.exposure.gainMode == 0)
		out += sprintf(out, "max_gain:                unknown  %28s"
384
			       "  powers of 2\n", tmpstr);
L
Linus Torvalds 已提交
385 386 387
	else
		out += sprintf(out, "max_gain:               %8d  %28s"
			       "  1,2,4 or 8 \n",
388
			       1<<(cam->params.exposure.gainMode-1), tmpstr);
L
Linus Torvalds 已提交
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404

	switch(cam->params.exposure.expMode) {
	case 1:
	case 3:
		sprintf(tmpstr, "manual");
		break;
	case 2:
		sprintf(tmpstr, "auto");
		break;
	default:
		sprintf(tmpstr, "unknown");
		break;
	}
	out += sprintf(out, "exposure_mode:          %8s  %8s  %8s"
		       "  %8s\n",  tmpstr, "manual", "auto", "auto");
	out += sprintf(out, "centre_weight:          %8s  %8s  %8s  %8s\n",
405 406
		       (2-cam->params.exposure.centreWeight) ? "on" : "off",
		       "off", "on", "on");
L
Linus Torvalds 已提交
407
	out += sprintf(out, "gain:                   %8d  %8d  max_gain  %8d  1,2,4,8 possible\n",
408
		       1<<cam->params.exposure.gain, 1, 1);
L
Linus Torvalds 已提交
409 410 411 412 413 414 415 416
	if (cam->params.version.firmwareVersion == 1 &&
	   cam->params.version.firmwareRevision == 2)
		/* 1-02 firmware limits fineExp/2 to 127 */
		tmp = 254;
	else
		tmp = 510;

	out += sprintf(out, "fine_exp:               %8d  %8d  %8d  %8d\n",
417
		       cam->params.exposure.fineExp*2, 0, tmp, 0);
L
Linus Torvalds 已提交
418 419 420 421 422 423 424 425 426 427 428
	if (cam->params.version.firmwareVersion == 1 &&
	   cam->params.version.firmwareRevision == 2)
		/* 1-02 firmware limits coarseExpHi to 0 */
		tmp = MAX_EXP_102;
	else
		tmp = MAX_EXP;

	out += sprintf(out, "coarse_exp:             %8d  %8d  %8d"
		       "  %8d\n", cam->params.exposure.coarseExpLo+
		       256*cam->params.exposure.coarseExpHi, 0, tmp, 185);
	out += sprintf(out, "red_comp:               %8d  %8d  %8d  %8d\n",
429
		       cam->params.exposure.redComp, COMP_RED, 255, COMP_RED);
L
Linus Torvalds 已提交
430
	out += sprintf(out, "green1_comp:            %8d  %8d  %8d  %8d\n",
431
		       cam->params.exposure.green1Comp, COMP_GREEN1, 255,
L
Linus Torvalds 已提交
432 433
		       COMP_GREEN1);
	out += sprintf(out, "green2_comp:            %8d  %8d  %8d  %8d\n",
434
		       cam->params.exposure.green2Comp, COMP_GREEN2, 255,
L
Linus Torvalds 已提交
435 436
		       COMP_GREEN2);
	out += sprintf(out, "blue_comp:              %8d  %8d  %8d  %8d\n",
437 438
		       cam->params.exposure.blueComp, COMP_BLUE, 255, COMP_BLUE);

L
Linus Torvalds 已提交
439
	out += sprintf(out, "apcor_gain1:            %#8x  %#8x  %#8x  %#8x\n",
440
		       cam->params.apcor.gain1, 0, 0xff, 0x1c);
L
Linus Torvalds 已提交
441
	out += sprintf(out, "apcor_gain2:            %#8x  %#8x  %#8x  %#8x\n",
442
		       cam->params.apcor.gain2, 0, 0xff, 0x1a);
L
Linus Torvalds 已提交
443
	out += sprintf(out, "apcor_gain4:            %#8x  %#8x  %#8x  %#8x\n",
444
		       cam->params.apcor.gain4, 0, 0xff, 0x2d);
L
Linus Torvalds 已提交
445
	out += sprintf(out, "apcor_gain8:            %#8x  %#8x  %#8x  %#8x\n",
446
		       cam->params.apcor.gain8, 0, 0xff, 0x2a);
L
Linus Torvalds 已提交
447
	out += sprintf(out, "vl_offset_gain1:        %8d  %8d  %8d  %8d\n",
448
		       cam->params.vlOffset.gain1, 0, 255, 24);
L
Linus Torvalds 已提交
449
	out += sprintf(out, "vl_offset_gain2:        %8d  %8d  %8d  %8d\n",
450
		       cam->params.vlOffset.gain2, 0, 255, 28);
L
Linus Torvalds 已提交
451
	out += sprintf(out, "vl_offset_gain4:        %8d  %8d  %8d  %8d\n",
452
		       cam->params.vlOffset.gain4, 0, 255, 30);
L
Linus Torvalds 已提交
453
	out += sprintf(out, "vl_offset_gain8:        %8d  %8d  %8d  %8d\n",
454
		       cam->params.vlOffset.gain8, 0, 255, 30);
L
Linus Torvalds 已提交
455
	out += sprintf(out, "flicker_control:        %8s  %8s  %8s  %8s\n",
456
		       cam->params.flickerControl.flickerMode ? "on" : "off",
L
Linus Torvalds 已提交
457 458
		       "off", "on", "off");
	out += sprintf(out, "mains_frequency:        %8d  %8d  %8d  %8d"
459 460
		       " only 50/60\n",
		       cam->mainsFreq ? 60 : 50, 50, 60, 50);
L
Linus Torvalds 已提交
461 462
	if(cam->params.flickerControl.allowableOverExposure < 0)
		out += sprintf(out, "allowable_overexposure: %4dauto      auto  %8d      auto\n",
463 464
			       -cam->params.flickerControl.allowableOverExposure,
			       255);
L
Linus Torvalds 已提交
465 466
	else
		out += sprintf(out, "allowable_overexposure: %8d      auto  %8d      auto\n",
467 468
			       cam->params.flickerControl.allowableOverExposure,
			       255);
L
Linus Torvalds 已提交
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
	out += sprintf(out, "compression_mode:       ");
	switch(cam->params.compression.mode) {
	case CPIA_COMPRESSION_NONE:
		out += sprintf(out, "%8s", "none");
		break;
	case CPIA_COMPRESSION_AUTO:
		out += sprintf(out, "%8s", "auto");
		break;
	case CPIA_COMPRESSION_MANUAL:
		out += sprintf(out, "%8s", "manual");
		break;
	default:
		out += sprintf(out, "%8s", "unknown");
		break;
	}
	out += sprintf(out, "    none,auto,manual      auto\n");
	out += sprintf(out, "decimation_enable:      %8s  %8s  %8s  %8s\n",
486 487
		       cam->params.compression.decimation ==
		       DECIMATION_ENAB ? "on":"off", "off", "on",
L
Linus Torvalds 已提交
488 489
		       "off");
	out += sprintf(out, "compression_target:    %9s %9s %9s %9s\n",
490
		       cam->params.compressionTarget.frTargeting  ==
L
Linus Torvalds 已提交
491 492 493 494
		       CPIA_COMPRESSION_TARGET_FRAMERATE ?
		       "framerate":"quality",
		       "framerate", "quality", "quality");
	out += sprintf(out, "target_framerate:       %8d  %8d  %8d  %8d\n",
495
		       cam->params.compressionTarget.targetFR, 1, 30, 15);
L
Linus Torvalds 已提交
496
	out += sprintf(out, "target_quality:         %8d  %8d  %8d  %8d\n",
497
		       cam->params.compressionTarget.targetQ, 1, 64, 5);
L
Linus Torvalds 已提交
498
	out += sprintf(out, "y_threshold:            %8d  %8d  %8d  %8d\n",
499
		       cam->params.yuvThreshold.yThreshold, 0, 31, 6);
L
Linus Torvalds 已提交
500
	out += sprintf(out, "uv_threshold:           %8d  %8d  %8d  %8d\n",
501
		       cam->params.yuvThreshold.uvThreshold, 0, 31, 6);
L
Linus Torvalds 已提交
502
	out += sprintf(out, "hysteresis:             %8d  %8d  %8d  %8d\n",
503
		       cam->params.compressionParams.hysteresis, 0, 255, 3);
L
Linus Torvalds 已提交
504
	out += sprintf(out, "threshold_max:          %8d  %8d  %8d  %8d\n",
505
		       cam->params.compressionParams.threshMax, 0, 255, 11);
L
Linus Torvalds 已提交
506
	out += sprintf(out, "small_step:             %8d  %8d  %8d  %8d\n",
507
		       cam->params.compressionParams.smallStep, 0, 255, 1);
L
Linus Torvalds 已提交
508
	out += sprintf(out, "large_step:             %8d  %8d  %8d  %8d\n",
509
		       cam->params.compressionParams.largeStep, 0, 255, 3);
L
Linus Torvalds 已提交
510
	out += sprintf(out, "decimation_hysteresis:  %8d  %8d  %8d  %8d\n",
511
		       cam->params.compressionParams.decimationHysteresis,
L
Linus Torvalds 已提交
512 513
		       0, 255, 2);
	out += sprintf(out, "fr_diff_step_thresh:    %8d  %8d  %8d  %8d\n",
514
		       cam->params.compressionParams.frDiffStepThresh,
L
Linus Torvalds 已提交
515 516
		       0, 255, 5);
	out += sprintf(out, "q_diff_step_thresh:     %8d  %8d  %8d  %8d\n",
517
		       cam->params.compressionParams.qDiffStepThresh,
L
Linus Torvalds 已提交
518 519
		       0, 255, 3);
	out += sprintf(out, "decimation_thresh_mod:  %8d  %8d  %8d  %8d\n",
520
		       cam->params.compressionParams.decimationThreshMod,
L
Linus Torvalds 已提交
521 522 523
		       0, 255, 2);
	/* QX3 specific entries */
	if (cam->params.qx3.qx3_detected) {
524 525
		out += sprintf(out, "toplight:               %8s  %8s  %8s  %8s\n",
			       cam->params.qx3.toplight ? "on" : "off",
L
Linus Torvalds 已提交
526
			       "off", "on", "off");
527 528
		out += sprintf(out, "bottomlight:            %8s  %8s  %8s  %8s\n",
			       cam->params.qx3.bottomlight ? "on" : "off",
L
Linus Torvalds 已提交
529 530
			       "off", "on", "off");
	}
531

L
Linus Torvalds 已提交
532 533 534 535 536 537 538 539 540 541 542 543 544 545
	len = out - page;
	len -= off;
	if (len < count) {
		*eof = 1;
		if (len <= 0) return 0;
	} else
		len = count;

	*start = page + off;
	return len;
}


static int match(char *checkstr, char **buffer, unsigned long *count,
546
		 int *find_colon, int *err)
L
Linus Torvalds 已提交
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
{
	int ret, colon_found = 1;
	int len = strlen(checkstr);
	ret = (len <= *count && strncmp(*buffer, checkstr, len) == 0);
	if (ret) {
		*buffer += len;
		*count -= len;
		if (*find_colon) {
			colon_found = 0;
			while (*count && (**buffer == ' ' || **buffer == '\t' ||
					  (!colon_found && **buffer == ':'))) {
				if (**buffer == ':')
					colon_found = 1;
				--*count;
				++*buffer;
			}
			if (!*count || !colon_found)
				*err = -EINVAL;
			*find_colon = 0;
		}
	}
	return ret;
}

static unsigned long int value(char **buffer, unsigned long *count, int *err)
{
	char *p;
	unsigned long int ret;
	ret = simple_strtoul(*buffer, &p, 0);
	if (p == *buffer)
		*err = -EINVAL;
	else {
		*count -= p - *buffer;
		*buffer = p;
	}
	return ret;
}

static int cpia_write_proc(struct file *file, const char __user *buf,
586
			   unsigned long count, void *data)
L
Linus Torvalds 已提交
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
{
	struct cam_data *cam = data;
	struct cam_params new_params;
	char *page, *buffer;
	int retval, find_colon;
	int size = count;
	unsigned long val = 0;
	u32 command_flags = 0;
	u8 new_mains;

	/*
	 * This code to copy from buf to page is shamelessly copied
	 * from the comx driver
	 */
	if (count > PAGE_SIZE) {
		printk(KERN_ERR "count is %lu > %d!!!\n", count, (int)PAGE_SIZE);
		return -ENOSPC;
	}

	if (!(page = (char *)__get_free_page(GFP_KERNEL))) return -ENOMEM;

	if(copy_from_user(page, buf, count))
	{
		retval = -EFAULT;
		goto out;
	}

	if (page[count-1] == '\n')
		page[count-1] = '\0';
	else if (count < PAGE_SIZE)
		page[count] = '\0';
	else if (page[count]) {
		retval = -EINVAL;
		goto out;
	}
622

L
Linus Torvalds 已提交
623
	buffer = page;
624

625
	if (mutex_lock_interruptible(&cam->param_lock))
L
Linus Torvalds 已提交
626
		return -ERESTARTSYS;
627

L
Linus Torvalds 已提交
628 629 630 631 632 633 634
	/*
	 * Skip over leading whitespace
	 */
	while (count && isspace(*buffer)) {
		--count;
		++buffer;
	}
635

L
Linus Torvalds 已提交
636 637
	memcpy(&new_params, &cam->params, sizeof(struct cam_params));
	new_mains = cam->mainsFreq;
638

L
Linus Torvalds 已提交
639 640 641
#define MATCH(x) (match(x, &buffer, &count, &find_colon, &retval))
#define VALUE (value(&buffer,&count, &retval))
#define FIRMWARE_VERSION(x,y) (new_params.version.firmwareVersion == (x) && \
642 643
			       new_params.version.firmwareRevision == (y))

L
Linus Torvalds 已提交
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
	retval = 0;
	while (count && !retval) {
		find_colon = 1;
		if (MATCH("brightness")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val <= 100)
					new_params.colourParams.brightness = val;
				else
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETCOLOURPARAMS;
			if(new_params.flickerControl.allowableOverExposure < 0)
659
				new_params.flickerControl.allowableOverExposure =
L
Linus Torvalds 已提交
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
					-find_over_exposure(new_params.colourParams.brightness);
			if(new_params.flickerControl.flickerMode != 0)
				command_flags |= COMMAND_SETFLICKERCTRL;

		} else if (MATCH("contrast")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val <= 100) {
					/* contrast is in steps of 8, so round*/
					val = ((val + 3) / 8) * 8;
					/* 1-02 firmware limits contrast to 80*/
					if (FIRMWARE_VERSION(1,2) && val > 80)
						val = 80;

					new_params.colourParams.contrast = val;
				} else
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETCOLOURPARAMS;
		} else if (MATCH("saturation")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val <= 100)
					new_params.colourParams.saturation = val;
				else
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETCOLOURPARAMS;
		} else if (MATCH("sensor_fps")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				/* find values so that sensorFPS is minimized,
				 * but >= val */
				if (val > 30)
					retval = -EINVAL;
				else if (val > 25) {
					new_params.sensorFps.divisor = 0;
					new_params.sensorFps.baserate = 1;
				} else if (val > 15) {
					new_params.sensorFps.divisor = 0;
					new_params.sensorFps.baserate = 0;
				} else if (val > 12) {
					new_params.sensorFps.divisor = 1;
					new_params.sensorFps.baserate = 1;
				} else if (val > 7) {
					new_params.sensorFps.divisor = 1;
					new_params.sensorFps.baserate = 0;
				} else if (val > 6) {
					new_params.sensorFps.divisor = 2;
					new_params.sensorFps.baserate = 1;
				} else if (val > 3) {
					new_params.sensorFps.divisor = 2;
					new_params.sensorFps.baserate = 0;
				} else {
					new_params.sensorFps.divisor = 3;
					/* Either base rate would work here */
					new_params.sensorFps.baserate = 1;
				}
724
				new_params.flickerControl.coarseJump =
L
Linus Torvalds 已提交
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
					flicker_jumps[new_mains]
					[new_params.sensorFps.baserate]
					[new_params.sensorFps.divisor];
				if (new_params.flickerControl.flickerMode)
					command_flags |= COMMAND_SETFLICKERCTRL;
			}
			command_flags |= COMMAND_SETSENSORFPS;
			cam->exposure_status = EXPOSURE_NORMAL;
		} else if (MATCH("stream_start_line")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				int max_line = 288;

				if (new_params.format.videoSize == VIDEOSIZE_QCIF)
					max_line = 144;
				if (val <= max_line)
					new_params.streamStartLine = val/2;
				else
					retval = -EINVAL;
			}
		} else if (MATCH("sub_sample")) {
			if (!retval && MATCH("420"))
				new_params.format.subSample = SUBSAMPLE_420;
			else if (!retval && MATCH("422"))
				new_params.format.subSample = SUBSAMPLE_422;
			else
				retval = -EINVAL;

			command_flags |= COMMAND_SETFORMAT;
		} else if (MATCH("yuv_order")) {
			if (!retval && MATCH("YUYV"))
				new_params.format.yuvOrder = YUVORDER_YUYV;
			else if (!retval && MATCH("UYVY"))
				new_params.format.yuvOrder = YUVORDER_UYVY;
			else
				retval = -EINVAL;

			command_flags |= COMMAND_SETFORMAT;
		} else if (MATCH("ecp_timing")) {
			if (!retval && MATCH("normal"))
				new_params.ecpTiming = 0;
			else if (!retval && MATCH("slow"))
				new_params.ecpTiming = 1;
			else
				retval = -EINVAL;

			command_flags |= COMMAND_SETECPTIMING;
		} else if (MATCH("color_balance_mode")) {
			if (!retval && MATCH("manual"))
				new_params.colourBalance.balanceMode = 3;
			else if (!retval && MATCH("auto"))
				new_params.colourBalance.balanceMode = 2;
			else
				retval = -EINVAL;

			command_flags |= COMMAND_SETCOLOURBALANCE;
		} else if (MATCH("red_gain")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val <= 212) {
					new_params.colourBalance.redGain = val;
					new_params.colourBalance.balanceMode = 1;
				} else
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETCOLOURBALANCE;
		} else if (MATCH("green_gain")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val <= 212) {
					new_params.colourBalance.greenGain = val;
					new_params.colourBalance.balanceMode = 1;
				} else
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETCOLOURBALANCE;
		} else if (MATCH("blue_gain")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val <= 212) {
					new_params.colourBalance.blueGain = val;
					new_params.colourBalance.balanceMode = 1;
				} else
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETCOLOURBALANCE;
		} else if (MATCH("max_gain")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				/* 1-02 firmware limits gain to 2 */
				if (FIRMWARE_VERSION(1,2) && val > 2)
					val = 2;
				switch(val) {
				case 1:
					new_params.exposure.gainMode = 1;
					break;
				case 2:
					new_params.exposure.gainMode = 2;
					break;
				case 4:
					new_params.exposure.gainMode = 3;
					break;
				case 8:
					new_params.exposure.gainMode = 4;
					break;
				default:
					retval = -EINVAL;
					break;
				}
			}
			command_flags |= COMMAND_SETEXPOSURE;
		} else if (MATCH("exposure_mode")) {
			if (!retval && MATCH("auto"))
				new_params.exposure.expMode = 2;
			else if (!retval && MATCH("manual")) {
				if (new_params.exposure.expMode == 2)
					new_params.exposure.expMode = 3;
				if(new_params.flickerControl.flickerMode != 0)
					command_flags |= COMMAND_SETFLICKERCTRL;
				new_params.flickerControl.flickerMode = 0;
			} else
				retval = -EINVAL;

			command_flags |= COMMAND_SETEXPOSURE;
		} else if (MATCH("centre_weight")) {
			if (!retval && MATCH("on"))
				new_params.exposure.centreWeight = 1;
			else if (!retval && MATCH("off"))
				new_params.exposure.centreWeight = 2;
			else
				retval = -EINVAL;

			command_flags |= COMMAND_SETEXPOSURE;
		} else if (MATCH("gain")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				switch(val) {
				case 1:
					new_params.exposure.gain = 0;
					break;
				case 2:
					new_params.exposure.gain = 1;
					break;
				case 4:
					new_params.exposure.gain = 2;
					break;
				case 8:
					new_params.exposure.gain = 3;
					break;
				default:
					retval = -EINVAL;
					break;
				}
				new_params.exposure.expMode = 1;
				if(new_params.flickerControl.flickerMode != 0)
					command_flags |= COMMAND_SETFLICKERCTRL;
				new_params.flickerControl.flickerMode = 0;
				command_flags |= COMMAND_SETEXPOSURE;
				if (new_params.exposure.gain >
				    new_params.exposure.gainMode-1)
					retval = -EINVAL;
			}
		} else if (MATCH("fine_exp")) {
			if (!retval)
				val = VALUE/2;

			if (!retval) {
				if (val < 256) {
					/* 1-02 firmware limits fineExp/2 to 127*/
					if (FIRMWARE_VERSION(1,2) && val > 127)
						val = 127;
					new_params.exposure.fineExp = val;
					new_params.exposure.expMode = 1;
					command_flags |= COMMAND_SETEXPOSURE;
					if(new_params.flickerControl.flickerMode != 0)
						command_flags |= COMMAND_SETFLICKERCTRL;
					new_params.flickerControl.flickerMode = 0;
					command_flags |= COMMAND_SETFLICKERCTRL;
				} else
					retval = -EINVAL;
			}
		} else if (MATCH("coarse_exp")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val <= MAX_EXP) {
					if (FIRMWARE_VERSION(1,2) &&
					    val > MAX_EXP_102)
						val = MAX_EXP_102;
					new_params.exposure.coarseExpLo =
						val & 0xff;
					new_params.exposure.coarseExpHi =
						val >> 8;
					new_params.exposure.expMode = 1;
					command_flags |= COMMAND_SETEXPOSURE;
					if(new_params.flickerControl.flickerMode != 0)
						command_flags |= COMMAND_SETFLICKERCTRL;
					new_params.flickerControl.flickerMode = 0;
					command_flags |= COMMAND_SETFLICKERCTRL;
				} else
					retval = -EINVAL;
			}
		} else if (MATCH("red_comp")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val >= COMP_RED && val <= 255) {
					new_params.exposure.redComp = val;
					new_params.exposure.compMode = 1;
					command_flags |= COMMAND_SETEXPOSURE;
				} else
					retval = -EINVAL;
			}
		} else if (MATCH("green1_comp")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val >= COMP_GREEN1 && val <= 255) {
					new_params.exposure.green1Comp = val;
					new_params.exposure.compMode = 1;
					command_flags |= COMMAND_SETEXPOSURE;
				} else
					retval = -EINVAL;
			}
		} else if (MATCH("green2_comp")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val >= COMP_GREEN2 && val <= 255) {
					new_params.exposure.green2Comp = val;
					new_params.exposure.compMode = 1;
					command_flags |= COMMAND_SETEXPOSURE;
				} else
					retval = -EINVAL;
			}
		} else if (MATCH("blue_comp")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val >= COMP_BLUE && val <= 255) {
					new_params.exposure.blueComp = val;
					new_params.exposure.compMode = 1;
					command_flags |= COMMAND_SETEXPOSURE;
				} else
					retval = -EINVAL;
			}
		} else if (MATCH("apcor_gain1")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				command_flags |= COMMAND_SETAPCOR;
				if (val <= 0xff)
					new_params.apcor.gain1 = val;
				else
					retval = -EINVAL;
			}
		} else if (MATCH("apcor_gain2")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				command_flags |= COMMAND_SETAPCOR;
				if (val <= 0xff)
					new_params.apcor.gain2 = val;
				else
					retval = -EINVAL;
			}
		} else if (MATCH("apcor_gain4")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				command_flags |= COMMAND_SETAPCOR;
				if (val <= 0xff)
					new_params.apcor.gain4 = val;
				else
					retval = -EINVAL;
			}
		} else if (MATCH("apcor_gain8")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				command_flags |= COMMAND_SETAPCOR;
				if (val <= 0xff)
					new_params.apcor.gain8 = val;
				else
					retval = -EINVAL;
			}
		} else if (MATCH("vl_offset_gain1")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val <= 0xff)
					new_params.vlOffset.gain1 = val;
				else
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETVLOFFSET;
		} else if (MATCH("vl_offset_gain2")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val <= 0xff)
					new_params.vlOffset.gain2 = val;
				else
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETVLOFFSET;
		} else if (MATCH("vl_offset_gain4")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val <= 0xff)
					new_params.vlOffset.gain4 = val;
				else
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETVLOFFSET;
		} else if (MATCH("vl_offset_gain8")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val <= 0xff)
					new_params.vlOffset.gain8 = val;
				else
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETVLOFFSET;
		} else if (MATCH("flicker_control")) {
			if (!retval && MATCH("on")) {
				set_flicker(&new_params, &command_flags, 1);
			} else if (!retval && MATCH("off")) {
				set_flicker(&new_params, &command_flags, 0);
			} else
				retval = -EINVAL;

			command_flags |= COMMAND_SETFLICKERCTRL;
		} else if (MATCH("mains_frequency")) {
			if (!retval && MATCH("50")) {
				new_mains = 0;
1088
				new_params.flickerControl.coarseJump =
L
Linus Torvalds 已提交
1089 1090 1091 1092 1093 1094 1095
					flicker_jumps[new_mains]
					[new_params.sensorFps.baserate]
					[new_params.sensorFps.divisor];
				if (new_params.flickerControl.flickerMode)
					command_flags |= COMMAND_SETFLICKERCTRL;
			} else if (!retval && MATCH("60")) {
				new_mains = 1;
1096
				new_params.flickerControl.coarseJump =
L
Linus Torvalds 已提交
1097 1098 1099 1100 1101 1102 1103 1104 1105
					flicker_jumps[new_mains]
					[new_params.sensorFps.baserate]
					[new_params.sensorFps.divisor];
				if (new_params.flickerControl.flickerMode)
					command_flags |= COMMAND_SETFLICKERCTRL;
			} else
				retval = -EINVAL;
		} else if (MATCH("allowable_overexposure")) {
			if (!retval && MATCH("auto")) {
1106
				new_params.flickerControl.allowableOverExposure =
L
Linus Torvalds 已提交
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
					-find_over_exposure(new_params.colourParams.brightness);
				if(new_params.flickerControl.flickerMode != 0)
					command_flags |= COMMAND_SETFLICKERCTRL;
			} else {
				if (!retval)
					val = VALUE;

				if (!retval) {
					if (val <= 0xff) {
						new_params.flickerControl.
							allowableOverExposure = val;
						if(new_params.flickerControl.flickerMode != 0)
							command_flags |= COMMAND_SETFLICKERCTRL;
					} else
						retval = -EINVAL;
				}
			}
		} else if (MATCH("compression_mode")) {
			if (!retval && MATCH("none"))
				new_params.compression.mode =
					CPIA_COMPRESSION_NONE;
			else if (!retval && MATCH("auto"))
				new_params.compression.mode =
					CPIA_COMPRESSION_AUTO;
			else if (!retval && MATCH("manual"))
				new_params.compression.mode =
					CPIA_COMPRESSION_MANUAL;
			else
				retval = -EINVAL;

			command_flags |= COMMAND_SETCOMPRESSION;
		} else if (MATCH("decimation_enable")) {
			if (!retval && MATCH("off"))
				new_params.compression.decimation = 0;
			else if (!retval && MATCH("on"))
				new_params.compression.decimation = 1;
			else
				retval = -EINVAL;

			command_flags |= COMMAND_SETCOMPRESSION;
		} else if (MATCH("compression_target")) {
			if (!retval && MATCH("quality"))
1149
				new_params.compressionTarget.frTargeting =
L
Linus Torvalds 已提交
1150 1151
					CPIA_COMPRESSION_TARGET_QUALITY;
			else if (!retval && MATCH("framerate"))
1152
				new_params.compressionTarget.frTargeting =
L
Linus Torvalds 已提交
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
					CPIA_COMPRESSION_TARGET_FRAMERATE;
			else
				retval = -EINVAL;

			command_flags |= COMMAND_SETCOMPRESSIONTARGET;
		} else if (MATCH("target_framerate")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if(val > 0 && val <= 30)
					new_params.compressionTarget.targetFR = val;
				else
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETCOMPRESSIONTARGET;
		} else if (MATCH("target_quality")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if(val > 0 && val <= 64)
					new_params.compressionTarget.targetQ = val;
1176
				else
L
Linus Torvalds 已提交
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETCOMPRESSIONTARGET;
		} else if (MATCH("y_threshold")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val < 32)
					new_params.yuvThreshold.yThreshold = val;
				else
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETYUVTHRESH;
		} else if (MATCH("uv_threshold")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val < 32)
					new_params.yuvThreshold.uvThreshold = val;
				else
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETYUVTHRESH;
		} else if (MATCH("hysteresis")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val <= 0xff)
					new_params.compressionParams.hysteresis = val;
				else
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETCOMPRESSIONPARAMS;
		} else if (MATCH("threshold_max")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val <= 0xff)
					new_params.compressionParams.threshMax = val;
				else
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETCOMPRESSIONPARAMS;
		} else if (MATCH("small_step")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val <= 0xff)
					new_params.compressionParams.smallStep = val;
				else
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETCOMPRESSIONPARAMS;
		} else if (MATCH("large_step")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val <= 0xff)
					new_params.compressionParams.largeStep = val;
				else
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETCOMPRESSIONPARAMS;
		} else if (MATCH("decimation_hysteresis")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val <= 0xff)
					new_params.compressionParams.decimationHysteresis = val;
				else
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETCOMPRESSIONPARAMS;
		} else if (MATCH("fr_diff_step_thresh")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val <= 0xff)
					new_params.compressionParams.frDiffStepThresh = val;
				else
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETCOMPRESSIONPARAMS;
		} else if (MATCH("q_diff_step_thresh")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val <= 0xff)
					new_params.compressionParams.qDiffStepThresh = val;
				else
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETCOMPRESSIONPARAMS;
		} else if (MATCH("decimation_thresh_mod")) {
			if (!retval)
				val = VALUE;

			if (!retval) {
				if (val <= 0xff)
					new_params.compressionParams.decimationThreshMod = val;
				else
					retval = -EINVAL;
			}
			command_flags |= COMMAND_SETCOMPRESSIONPARAMS;
		} else if (MATCH("toplight")) {
1291
			if (!retval && MATCH("on"))
L
Linus Torvalds 已提交
1292 1293 1294
				new_params.qx3.toplight = 1;
			else if (!retval && MATCH("off"))
				new_params.qx3.toplight = 0;
1295
			else
L
Linus Torvalds 已提交
1296 1297 1298
				retval = -EINVAL;
			command_flags |= COMMAND_SETLIGHTS;
		} else if (MATCH("bottomlight")) {
1299
			if (!retval && MATCH("on"))
L
Linus Torvalds 已提交
1300
				new_params.qx3.bottomlight = 1;
1301
			else if (!retval && MATCH("off"))
L
Linus Torvalds 已提交
1302
				new_params.qx3.bottomlight = 0;
1303
			else
L
Linus Torvalds 已提交
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
				retval = -EINVAL;
			command_flags |= COMMAND_SETLIGHTS;
		} else {
			DBG("No match found\n");
			retval = -EINVAL;
		}

		if (!retval) {
			while (count && isspace(*buffer) && *buffer != '\n') {
				--count;
				++buffer;
			}
			if (count) {
				if (*buffer == '\0' && count != 1)
					retval = -EINVAL;
				else if (*buffer != '\n' && *buffer != ';' &&
					 *buffer != '\0')
					retval = -EINVAL;
				else {
					--count;
					++buffer;
				}
			}
		}
	}
1329
#undef MATCH
L
Linus Torvalds 已提交
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
#undef VALUE
#undef FIRMWARE_VERSION
	if (!retval) {
		if (command_flags & COMMAND_SETCOLOURPARAMS) {
			/* Adjust cam->vp to reflect these changes */
			cam->vp.brightness =
				new_params.colourParams.brightness*65535/100;
			cam->vp.contrast =
				new_params.colourParams.contrast*65535/100;
			cam->vp.colour =
				new_params.colourParams.saturation*65535/100;
		}
		if((command_flags & COMMAND_SETEXPOSURE) &&
		   new_params.exposure.expMode == 2)
			cam->exposure_status = EXPOSURE_NORMAL;

		memcpy(&cam->params, &new_params, sizeof(struct cam_params));
		cam->mainsFreq = new_mains;
		cam->cmd_queue |= command_flags;
		retval = size;
	} else
		DBG("error: %d\n", retval);
1352

1353
	mutex_unlock(&cam->param_lock);
1354

L
Linus Torvalds 已提交
1355 1356
out:
	free_page((unsigned long)page);
1357
	return retval;
L
Linus Torvalds 已提交
1358 1359 1360 1361 1362 1363
}

static void create_proc_cpia_cam(struct cam_data *cam)
{
	char name[7];
	struct proc_dir_entry *ent;
1364

L
Linus Torvalds 已提交
1365 1366 1367 1368
	if (!cpia_proc_root || !cam)
		return;

	sprintf(name, "video%d", cam->vdev.minor);
1369

L
Linus Torvalds 已提交
1370 1371 1372 1373 1374 1375 1376
	ent = create_proc_entry(name, S_IFREG|S_IRUGO|S_IWUSR, cpia_proc_root);
	if (!ent)
		return;

	ent->data = cam;
	ent->read_proc = cpia_read_proc;
	ent->write_proc = cpia_write_proc;
1377
	/*
L
Linus Torvalds 已提交
1378
	   size of the proc entry is 3736 bytes for the standard webcam;
1379
	   the extra features of the QX3 microscope add 189 bytes.
L
Linus Torvalds 已提交
1380 1381 1382 1383 1384 1385 1386 1387 1388
	   (we have not yet probed the camera to see which type it is).
	*/
	ent->size = 3736 + 189;
	cam->proc_entry = ent;
}

static void destroy_proc_cpia_cam(struct cam_data *cam)
{
	char name[7];
1389

L
Linus Torvalds 已提交
1390 1391
	if (!cam || !cam->proc_entry)
		return;
1392

L
Linus Torvalds 已提交
1393 1394 1395 1396 1397 1398 1399
	sprintf(name, "video%d", cam->vdev.minor);
	remove_proc_entry(name, cpia_proc_root);
	cam->proc_entry = NULL;
}

static void proc_cpia_create(void)
{
1400
	cpia_proc_root = proc_mkdir("cpia", NULL);
L
Linus Torvalds 已提交
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598

	if (cpia_proc_root)
		cpia_proc_root->owner = THIS_MODULE;
	else
		LOG("Unable to initialise /proc/cpia\n");
}

static void __exit proc_cpia_destroy(void)
{
	remove_proc_entry("cpia", NULL);
}
#endif /* CONFIG_PROC_FS */

/* ----------------------- debug functions ---------------------- */

#define printstatus(cam) \
  DBG("%02x %02x %02x %02x %02x %02x %02x %02x\n",\
	cam->params.status.systemState, cam->params.status.grabState, \
	cam->params.status.streamState, cam->params.status.fatalError, \
	cam->params.status.cmdError, cam->params.status.debugFlags, \
	cam->params.status.vpStatus, cam->params.status.errorCode);

/* ----------------------- v4l helpers -------------------------- */

/* supported frame palettes and depths */
static inline int valid_mode(u16 palette, u16 depth)
{
	if ((palette == VIDEO_PALETTE_YUV422 && depth == 16) ||
	    (palette == VIDEO_PALETTE_YUYV && depth == 16))
		return 1;

	if (colorspace_conv)
		return (palette == VIDEO_PALETTE_GREY && depth == 8) ||
		       (palette == VIDEO_PALETTE_RGB555 && depth == 16) ||
		       (palette == VIDEO_PALETTE_RGB565 && depth == 16) ||
		       (palette == VIDEO_PALETTE_RGB24 && depth == 24) ||
		       (palette == VIDEO_PALETTE_RGB32 && depth == 32) ||
		       (palette == VIDEO_PALETTE_UYVY && depth == 16);

	return 0;
}

static int match_videosize( int width, int height )
{
	/* return the best match, where 'best' is as always
	 * the largest that is not bigger than what is requested. */
	if (width>=352 && height>=288)
		return VIDEOSIZE_352_288; /* CIF */

	if (width>=320 && height>=240)
		return VIDEOSIZE_320_240; /* SIF */

	if (width>=288 && height>=216)
		return VIDEOSIZE_288_216;

	if (width>=256 && height>=192)
		return VIDEOSIZE_256_192;

	if (width>=224 && height>=168)
		return VIDEOSIZE_224_168;

	if (width>=192 && height>=144)
		return VIDEOSIZE_192_144;

	if (width>=176 && height>=144)
		return VIDEOSIZE_176_144; /* QCIF */

	if (width>=160 && height>=120)
		return VIDEOSIZE_160_120; /* QSIF */

	if (width>=128 && height>=96)
		return VIDEOSIZE_128_96;

	if (width>=88 && height>=72)
		return VIDEOSIZE_88_72;

	if (width>=64 && height>=48)
		return VIDEOSIZE_64_48;

	if (width>=48 && height>=48)
		return VIDEOSIZE_48_48;

	return -1;
}

/* these are the capture sizes we support */
static void set_vw_size(struct cam_data *cam)
{
	/* the col/row/start/end values are the result of simple math    */
	/* study the SetROI-command in cpia developers guide p 2-22      */
	/* streamStartLine is set to the recommended value in the cpia   */
	/*  developers guide p 3-37                                      */
	switch(cam->video_size) {
	case VIDEOSIZE_CIF:
		cam->vw.width = 352;
		cam->vw.height = 288;
		cam->params.format.videoSize=VIDEOSIZE_CIF;
		cam->params.roi.colStart=0;
		cam->params.roi.rowStart=0;
		cam->params.streamStartLine = 120;
		break;
	case VIDEOSIZE_SIF:
		cam->vw.width = 320;
		cam->vw.height = 240;
		cam->params.format.videoSize=VIDEOSIZE_CIF;
		cam->params.roi.colStart=2;
		cam->params.roi.rowStart=6;
		cam->params.streamStartLine = 120;
		break;
	case VIDEOSIZE_288_216:
		cam->vw.width = 288;
		cam->vw.height = 216;
		cam->params.format.videoSize=VIDEOSIZE_CIF;
		cam->params.roi.colStart=4;
		cam->params.roi.rowStart=9;
		cam->params.streamStartLine = 120;
		break;
	case VIDEOSIZE_256_192:
		cam->vw.width = 256;
		cam->vw.height = 192;
		cam->params.format.videoSize=VIDEOSIZE_CIF;
		cam->params.roi.colStart=6;
		cam->params.roi.rowStart=12;
		cam->params.streamStartLine = 120;
		break;
	case VIDEOSIZE_224_168:
		cam->vw.width = 224;
		cam->vw.height = 168;
		cam->params.format.videoSize=VIDEOSIZE_CIF;
		cam->params.roi.colStart=8;
		cam->params.roi.rowStart=15;
		cam->params.streamStartLine = 120;
		break;
	case VIDEOSIZE_192_144:
		cam->vw.width = 192;
		cam->vw.height = 144;
		cam->params.format.videoSize=VIDEOSIZE_CIF;
		cam->params.roi.colStart=10;
		cam->params.roi.rowStart=18;
		cam->params.streamStartLine = 120;
		break;
	case VIDEOSIZE_QCIF:
		cam->vw.width = 176;
		cam->vw.height = 144;
		cam->params.format.videoSize=VIDEOSIZE_QCIF;
		cam->params.roi.colStart=0;
		cam->params.roi.rowStart=0;
		cam->params.streamStartLine = 60;
		break;
	case VIDEOSIZE_QSIF:
		cam->vw.width = 160;
		cam->vw.height = 120;
		cam->params.format.videoSize=VIDEOSIZE_QCIF;
		cam->params.roi.colStart=1;
		cam->params.roi.rowStart=3;
		cam->params.streamStartLine = 60;
		break;
	case VIDEOSIZE_128_96:
		cam->vw.width = 128;
		cam->vw.height = 96;
		cam->params.format.videoSize=VIDEOSIZE_QCIF;
		cam->params.roi.colStart=3;
		cam->params.roi.rowStart=6;
		cam->params.streamStartLine = 60;
		break;
	case VIDEOSIZE_88_72:
		cam->vw.width = 88;
		cam->vw.height = 72;
		cam->params.format.videoSize=VIDEOSIZE_QCIF;
		cam->params.roi.colStart=5;
		cam->params.roi.rowStart=9;
		cam->params.streamStartLine = 60;
		break;
	case VIDEOSIZE_64_48:
		cam->vw.width = 64;
		cam->vw.height = 48;
		cam->params.format.videoSize=VIDEOSIZE_QCIF;
		cam->params.roi.colStart=7;
		cam->params.roi.rowStart=12;
		cam->params.streamStartLine = 60;
		break;
	case VIDEOSIZE_48_48:
		cam->vw.width = 48;
		cam->vw.height = 48;
		cam->params.format.videoSize=VIDEOSIZE_QCIF;
		cam->params.roi.colStart=8;
		cam->params.roi.rowStart=6;
		cam->params.streamStartLine = 60;
		break;
	default:
		LOG("bad videosize value: %d\n", cam->video_size);
		return;
	}

	if(cam->vc.width == 0)
		cam->vc.width = cam->vw.width;
	if(cam->vc.height == 0)
		cam->vc.height = cam->vw.height;
1599

L
Linus Torvalds 已提交
1600 1601
	cam->params.roi.colStart += cam->vc.x >> 3;
	cam->params.roi.colEnd = cam->params.roi.colStart +
1602
				 (cam->vc.width >> 3);
L
Linus Torvalds 已提交
1603 1604
	cam->params.roi.rowStart += cam->vc.y >> 2;
	cam->params.roi.rowEnd = cam->params.roi.rowStart +
1605
				 (cam->vc.height >> 2);
L
Linus Torvalds 已提交
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626

	return;
}

static int allocate_frame_buf(struct cam_data *cam)
{
	int i;

	cam->frame_buf = rvmalloc(FRAME_NUM * CPIA_MAX_FRAME_SIZE);
	if (!cam->frame_buf)
		return -ENOBUFS;

	for (i = 0; i < FRAME_NUM; i++)
		cam->frame[i].data = cam->frame_buf + i * CPIA_MAX_FRAME_SIZE;

	return 0;
}

static int free_frame_buf(struct cam_data *cam)
{
	int i;
1627

L
Linus Torvalds 已提交
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
	rvfree(cam->frame_buf, FRAME_NUM*CPIA_MAX_FRAME_SIZE);
	cam->frame_buf = NULL;
	for (i=0; i < FRAME_NUM; i++)
		cam->frame[i].data = NULL;

	return 0;
}


static inline void free_frames(struct cpia_frame frame[FRAME_NUM])
{
	int i;

	for (i=0; i < FRAME_NUM; i++)
		frame[i].state = FRAME_UNUSED;
	return;
}

/**********************************************************************
 *
 * General functions
 *
 **********************************************************************/
/* send an arbitrary command to the camera */
static int do_command(struct cam_data *cam, u16 command, u8 a, u8 b, u8 c, u8 d)
{
	int retval, datasize;
	u8 cmd[8], data[8];

	switch(command) {
	case CPIA_COMMAND_GetCPIAVersion:
	case CPIA_COMMAND_GetPnPID:
	case CPIA_COMMAND_GetCameraStatus:
	case CPIA_COMMAND_GetVPVersion:
		datasize=8;
		break;
	case CPIA_COMMAND_GetColourParams:
	case CPIA_COMMAND_GetColourBalance:
	case CPIA_COMMAND_GetExposure:
1667
		mutex_lock(&cam->param_lock);
L
Linus Torvalds 已提交
1668 1669
		datasize=8;
		break;
1670
	case CPIA_COMMAND_ReadMCPorts:
L
Linus Torvalds 已提交
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693
	case CPIA_COMMAND_ReadVCRegs:
		datasize = 4;
		break;
	default:
		datasize=0;
		break;
	}

	cmd[0] = command>>8;
	cmd[1] = command&0xff;
	cmd[2] = a;
	cmd[3] = b;
	cmd[4] = c;
	cmd[5] = d;
	cmd[6] = datasize;
	cmd[7] = 0;

	retval = cam->ops->transferCmd(cam->lowlevel_data, cmd, data);
	if (retval) {
		DBG("%x - failed, retval=%d\n", command, retval);
		if (command == CPIA_COMMAND_GetColourParams ||
		    command == CPIA_COMMAND_GetColourBalance ||
		    command == CPIA_COMMAND_GetExposure)
1694
			mutex_unlock(&cam->param_lock);
L
Linus Torvalds 已提交
1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
	} else {
		switch(command) {
		case CPIA_COMMAND_GetCPIAVersion:
			cam->params.version.firmwareVersion = data[0];
			cam->params.version.firmwareRevision = data[1];
			cam->params.version.vcVersion = data[2];
			cam->params.version.vcRevision = data[3];
			break;
		case CPIA_COMMAND_GetPnPID:
			cam->params.pnpID.vendor = data[0]+(((u16)data[1])<<8);
			cam->params.pnpID.product = data[2]+(((u16)data[3])<<8);
			cam->params.pnpID.deviceRevision =
				data[4]+(((u16)data[5])<<8);
			break;
		case CPIA_COMMAND_GetCameraStatus:
			cam->params.status.systemState = data[0];
			cam->params.status.grabState = data[1];
			cam->params.status.streamState = data[2];
			cam->params.status.fatalError = data[3];
			cam->params.status.cmdError = data[4];
			cam->params.status.debugFlags = data[5];
			cam->params.status.vpStatus = data[6];
			cam->params.status.errorCode = data[7];
			break;
		case CPIA_COMMAND_GetVPVersion:
			cam->params.vpVersion.vpVersion = data[0];
			cam->params.vpVersion.vpRevision = data[1];
			cam->params.vpVersion.cameraHeadID =
				data[2]+(((u16)data[3])<<8);
			break;
		case CPIA_COMMAND_GetColourParams:
			cam->params.colourParams.brightness = data[0];
			cam->params.colourParams.contrast = data[1];
			cam->params.colourParams.saturation = data[2];
1729
			mutex_unlock(&cam->param_lock);
L
Linus Torvalds 已提交
1730 1731 1732 1733 1734
			break;
		case CPIA_COMMAND_GetColourBalance:
			cam->params.colourBalance.redGain = data[0];
			cam->params.colourBalance.greenGain = data[1];
			cam->params.colourBalance.blueGain = data[2];
1735
			mutex_unlock(&cam->param_lock);
L
Linus Torvalds 已提交
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
			break;
		case CPIA_COMMAND_GetExposure:
			cam->params.exposure.gain = data[0];
			cam->params.exposure.fineExp = data[1];
			cam->params.exposure.coarseExpLo = data[2];
			cam->params.exposure.coarseExpHi = data[3];
			cam->params.exposure.redComp = data[4];
			cam->params.exposure.green1Comp = data[5];
			cam->params.exposure.green2Comp = data[6];
			cam->params.exposure.blueComp = data[7];
1746
			mutex_unlock(&cam->param_lock);
L
Linus Torvalds 已提交
1747 1748
			break;

1749 1750
		case CPIA_COMMAND_ReadMCPorts:
			if (!cam->params.qx3.qx3_detected)
L
Linus Torvalds 已提交
1751
				break;
1752
			/* test button press */
L
Linus Torvalds 已提交
1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
			cam->params.qx3.button = ((data[1] & 0x02) == 0);
			if (cam->params.qx3.button) {
				/* button pressed - unlock the latch */
				do_command(cam,CPIA_COMMAND_WriteMCPort,3,0xDF,0xDF,0);
				do_command(cam,CPIA_COMMAND_WriteMCPort,3,0xFF,0xFF,0);
			}

			/* test whether microscope is cradled */
			cam->params.qx3.cradled = ((data[2] & 0x40) == 0);
			break;

		default:
			break;
		}
	}
	return retval;
}

/* send a command  to the camera with an additional data transaction */
static int do_command_extended(struct cam_data *cam, u16 command,
1773 1774 1775
			       u8 a, u8 b, u8 c, u8 d,
			       u8 e, u8 f, u8 g, u8 h,
			       u8 i, u8 j, u8 k, u8 l)
L
Linus Torvalds 已提交
1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
{
	int retval;
	u8 cmd[8], data[8];

	cmd[0] = command>>8;
	cmd[1] = command&0xff;
	cmd[2] = a;
	cmd[3] = b;
	cmd[4] = c;
	cmd[5] = d;
	cmd[6] = 8;
	cmd[7] = 0;
	data[0] = e;
	data[1] = f;
	data[2] = g;
	data[3] = h;
	data[4] = i;
	data[5] = j;
	data[6] = k;
	data[7] = l;

	retval = cam->ops->transferCmd(cam->lowlevel_data, cmd, data);
	if (retval)
		DBG("%x - failed\n", command);

	return retval;
}

/**********************************************************************
 *
 * Colorspace conversion
 *
 **********************************************************************/
#define LIMIT(x) ((((x)>0xffffff)?0xff0000:(((x)<=0xffff)?0:(x)&0xff0000))>>16)

static int convert420(unsigned char *yuv, unsigned char *rgb, int out_fmt,
1812
		      int linesize, int mmap_kludge)
L
Linus Torvalds 已提交
1813 1814
{
	int y, u, v, r, g, b, y1;
1815

L
Linus Torvalds 已提交
1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927
	/* Odd lines use the same u and v as the previous line.
	 * Because of compression, it is necessary to get this
	 * information from the decoded image. */
	switch(out_fmt) {
	case VIDEO_PALETTE_RGB555:
		y = (*yuv++ - 16) * 76310;
		y1 = (*yuv - 16) * 76310;
		r = ((*(rgb+1-linesize)) & 0x7c) << 1;
		g = ((*(rgb-linesize)) & 0xe0) >> 4 |
		    ((*(rgb+1-linesize)) & 0x03) << 6;
		b = ((*(rgb-linesize)) & 0x1f) << 3;
		u = (-53294 * r - 104635 * g + 157929 * b) / 5756495;
		v = (157968 * r - 132278 * g - 25690 * b) / 5366159;
		r = 104635 * v;
		g = -25690 * u - 53294 * v;
		b = 132278 * u;
		*rgb++ = ((LIMIT(g+y) & 0xf8) << 2) | (LIMIT(b+y) >> 3);
		*rgb++ = ((LIMIT(r+y) & 0xf8) >> 1) | (LIMIT(g+y) >> 6);
		*rgb++ = ((LIMIT(g+y1) & 0xf8) << 2) | (LIMIT(b+y1) >> 3);
		*rgb = ((LIMIT(r+y1) & 0xf8) >> 1) | (LIMIT(g+y1) >> 6);
		return 4;
	case VIDEO_PALETTE_RGB565:
		y = (*yuv++ - 16) * 76310;
		y1 = (*yuv - 16) * 76310;
		r = (*(rgb+1-linesize)) & 0xf8;
		g = ((*(rgb-linesize)) & 0xe0) >> 3 |
		    ((*(rgb+1-linesize)) & 0x07) << 5;
		b = ((*(rgb-linesize)) & 0x1f) << 3;
		u = (-53294 * r - 104635 * g + 157929 * b) / 5756495;
		v = (157968 * r - 132278 * g - 25690 * b) / 5366159;
		r = 104635 * v;
		g = -25690 * u - 53294 * v;
		b = 132278 * u;
		*rgb++ = ((LIMIT(g+y) & 0xfc) << 3) | (LIMIT(b+y) >> 3);
		*rgb++ = (LIMIT(r+y) & 0xf8) | (LIMIT(g+y) >> 5);
		*rgb++ = ((LIMIT(g+y1) & 0xfc) << 3) | (LIMIT(b+y1) >> 3);
		*rgb = (LIMIT(r+y1) & 0xf8) | (LIMIT(g+y1) >> 5);
		return 4;
		break;
	case VIDEO_PALETTE_RGB24:
	case VIDEO_PALETTE_RGB32:
		y = (*yuv++ - 16) * 76310;
		y1 = (*yuv - 16) * 76310;
		if (mmap_kludge) {
			r = *(rgb+2-linesize);
			g = *(rgb+1-linesize);
			b = *(rgb-linesize);
		} else {
			r = *(rgb-linesize);
			g = *(rgb+1-linesize);
			b = *(rgb+2-linesize);
		}
		u = (-53294 * r - 104635 * g + 157929 * b) / 5756495;
		v = (157968 * r - 132278 * g - 25690 * b) / 5366159;
		r = 104635 * v;
		g = -25690 * u + -53294 * v;
		b = 132278 * u;
		if (mmap_kludge) {
			*rgb++ = LIMIT(b+y);
			*rgb++ = LIMIT(g+y);
			*rgb++ = LIMIT(r+y);
			if(out_fmt == VIDEO_PALETTE_RGB32)
				rgb++;
			*rgb++ = LIMIT(b+y1);
			*rgb++ = LIMIT(g+y1);
			*rgb = LIMIT(r+y1);
		} else {
			*rgb++ = LIMIT(r+y);
			*rgb++ = LIMIT(g+y);
			*rgb++ = LIMIT(b+y);
			if(out_fmt == VIDEO_PALETTE_RGB32)
				rgb++;
			*rgb++ = LIMIT(r+y1);
			*rgb++ = LIMIT(g+y1);
			*rgb = LIMIT(b+y1);
		}
		if(out_fmt == VIDEO_PALETTE_RGB32)
			return 8;
		return 6;
	case VIDEO_PALETTE_YUV422:
	case VIDEO_PALETTE_YUYV:
		y = *yuv++;
		u = *(rgb+1-linesize);
		y1 = *yuv;
		v = *(rgb+3-linesize);
		*rgb++ = y;
		*rgb++ = u;
		*rgb++ = y1;
		*rgb = v;
		return 4;
	case VIDEO_PALETTE_UYVY:
		u = *(rgb-linesize);
		y = *yuv++;
		v = *(rgb+2-linesize);
		y1 = *yuv;
		*rgb++ = u;
		*rgb++ = y;
		*rgb++ = v;
		*rgb = y1;
		return 4;
	case VIDEO_PALETTE_GREY:
		*rgb++ = *yuv++;
		*rgb = *yuv;
		return 2;
	default:
		DBG("Empty: %d\n", out_fmt);
		return 0;
	}
}


static int yuvconvert(unsigned char *yuv, unsigned char *rgb, int out_fmt,
1928
		      int in_uyvy, int mmap_kludge)
L
Linus Torvalds 已提交
1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
{
	int y, u, v, r, g, b, y1;

	switch(out_fmt) {
	case VIDEO_PALETTE_RGB555:
	case VIDEO_PALETTE_RGB565:
	case VIDEO_PALETTE_RGB24:
	case VIDEO_PALETTE_RGB32:
		if (in_uyvy) {
			u = *yuv++ - 128;
			y = (*yuv++ - 16) * 76310;
			v = *yuv++ - 128;
			y1 = (*yuv - 16) * 76310;
		} else {
			y = (*yuv++ - 16) * 76310;
			u = *yuv++ - 128;
			y1 = (*yuv++ - 16) * 76310;
			v = *yuv - 128;
		}
		r = 104635 * v;
		g = -25690 * u + -53294 * v;
		b = 132278 * u;
		break;
	default:
		y = *yuv++;
		u = *yuv++;
		y1 = *yuv++;
		v = *yuv;
		/* Just to avoid compiler warnings */
		r = 0;
		g = 0;
		b = 0;
		break;
	}
	switch(out_fmt) {
	case VIDEO_PALETTE_RGB555:
		*rgb++ = ((LIMIT(g+y) & 0xf8) << 2) | (LIMIT(b+y) >> 3);
		*rgb++ = ((LIMIT(r+y) & 0xf8) >> 1) | (LIMIT(g+y) >> 6);
		*rgb++ = ((LIMIT(g+y1) & 0xf8) << 2) | (LIMIT(b+y1) >> 3);
		*rgb = ((LIMIT(r+y1) & 0xf8) >> 1) | (LIMIT(g+y1) >> 6);
		return 4;
	case VIDEO_PALETTE_RGB565:
		*rgb++ = ((LIMIT(g+y) & 0xfc) << 3) | (LIMIT(b+y) >> 3);
		*rgb++ = (LIMIT(r+y) & 0xf8) | (LIMIT(g+y) >> 5);
		*rgb++ = ((LIMIT(g+y1) & 0xfc) << 3) | (LIMIT(b+y1) >> 3);
		*rgb = (LIMIT(r+y1) & 0xf8) | (LIMIT(g+y1) >> 5);
		return 4;
	case VIDEO_PALETTE_RGB24:
		if (mmap_kludge) {
			*rgb++ = LIMIT(b+y);
			*rgb++ = LIMIT(g+y);
			*rgb++ = LIMIT(r+y);
			*rgb++ = LIMIT(b+y1);
			*rgb++ = LIMIT(g+y1);
			*rgb = LIMIT(r+y1);
		} else {
			*rgb++ = LIMIT(r+y);
			*rgb++ = LIMIT(g+y);
			*rgb++ = LIMIT(b+y);
			*rgb++ = LIMIT(r+y1);
			*rgb++ = LIMIT(g+y1);
			*rgb = LIMIT(b+y1);
		}
		return 6;
	case VIDEO_PALETTE_RGB32:
		if (mmap_kludge) {
			*rgb++ = LIMIT(b+y);
			*rgb++ = LIMIT(g+y);
			*rgb++ = LIMIT(r+y);
			rgb++;
			*rgb++ = LIMIT(b+y1);
			*rgb++ = LIMIT(g+y1);
			*rgb = LIMIT(r+y1);
		} else {
			*rgb++ = LIMIT(r+y);
			*rgb++ = LIMIT(g+y);
			*rgb++ = LIMIT(b+y);
			rgb++;
			*rgb++ = LIMIT(r+y1);
			*rgb++ = LIMIT(g+y1);
			*rgb = LIMIT(b+y1);
		}
		return 8;
	case VIDEO_PALETTE_GREY:
		*rgb++ = y;
		*rgb = y1;
		return 2;
	case VIDEO_PALETTE_YUV422:
	case VIDEO_PALETTE_YUYV:
		*rgb++ = y;
		*rgb++ = u;
		*rgb++ = y1;
		*rgb = v;
		return 4;
	case VIDEO_PALETTE_UYVY:
		*rgb++ = u;
		*rgb++ = y;
		*rgb++ = v;
		*rgb = y1;
		return 4;
	default:
		DBG("Empty: %d\n", out_fmt);
		return 0;
	}
}

static int skipcount(int count, int fmt)
{
	switch(fmt) {
	case VIDEO_PALETTE_GREY:
		return count;
	case VIDEO_PALETTE_RGB555:
	case VIDEO_PALETTE_RGB565:
	case VIDEO_PALETTE_YUV422:
	case VIDEO_PALETTE_YUYV:
	case VIDEO_PALETTE_UYVY:
		return 2*count;
	case VIDEO_PALETTE_RGB24:
		return 3*count;
	case VIDEO_PALETTE_RGB32:
		return 4*count;
	default:
		return 0;
	}
}

static int parse_picture(struct cam_data *cam, int size)
{
	u8 *obuf, *ibuf, *end_obuf;
	int ll, in_uyvy, compressed, decimation, even_line, origsize, out_fmt;
	int rows, cols, linesize, subsample_422;

	/* make sure params don't change while we are decoding */
2062
	mutex_lock(&cam->param_lock);
L
Linus Torvalds 已提交
2063 2064 2065 2066 2067 2068 2069 2070 2071

	obuf = cam->decompressed_frame.data;
	end_obuf = obuf+CPIA_MAX_FRAME_SIZE;
	ibuf = cam->raw_image;
	origsize = size;
	out_fmt = cam->vp.palette;

	if ((ibuf[0] != MAGIC_0) || (ibuf[1] != MAGIC_1)) {
		LOG("header not found\n");
2072
		mutex_unlock(&cam->param_lock);
L
Linus Torvalds 已提交
2073 2074 2075 2076 2077
		return -1;
	}

	if ((ibuf[16] != VIDEOSIZE_QCIF) && (ibuf[16] != VIDEOSIZE_CIF)) {
		LOG("wrong video size\n");
2078
		mutex_unlock(&cam->param_lock);
L
Linus Torvalds 已提交
2079 2080
		return -1;
	}
2081

L
Linus Torvalds 已提交
2082 2083
	if (ibuf[17] != SUBSAMPLE_420 && ibuf[17] != SUBSAMPLE_422) {
		LOG("illegal subtype %d\n",ibuf[17]);
2084
		mutex_unlock(&cam->param_lock);
L
Linus Torvalds 已提交
2085 2086 2087
		return -1;
	}
	subsample_422 = ibuf[17] == SUBSAMPLE_422;
2088

L
Linus Torvalds 已提交
2089 2090
	if (ibuf[18] != YUVORDER_YUYV && ibuf[18] != YUVORDER_UYVY) {
		LOG("illegal yuvorder %d\n",ibuf[18]);
2091
		mutex_unlock(&cam->param_lock);
L
Linus Torvalds 已提交
2092 2093 2094
		return -1;
	}
	in_uyvy = ibuf[18] == YUVORDER_UYVY;
2095

L
Linus Torvalds 已提交
2096 2097 2098 2099 2100
	if ((ibuf[24] != cam->params.roi.colStart) ||
	    (ibuf[25] != cam->params.roi.colEnd) ||
	    (ibuf[26] != cam->params.roi.rowStart) ||
	    (ibuf[27] != cam->params.roi.rowEnd)) {
		LOG("ROI mismatch\n");
2101
		mutex_unlock(&cam->param_lock);
L
Linus Torvalds 已提交
2102 2103 2104 2105 2106
		return -1;
	}
	cols = 8*(ibuf[25] - ibuf[24]);
	rows = 4*(ibuf[27] - ibuf[26]);

2107

L
Linus Torvalds 已提交
2108 2109
	if ((ibuf[28] != NOT_COMPRESSED) && (ibuf[28] != COMPRESSED)) {
		LOG("illegal compression %d\n",ibuf[28]);
2110
		mutex_unlock(&cam->param_lock);
L
Linus Torvalds 已提交
2111 2112 2113
		return -1;
	}
	compressed = (ibuf[28] == COMPRESSED);
2114

L
Linus Torvalds 已提交
2115 2116
	if (ibuf[29] != NO_DECIMATION && ibuf[29] != DECIMATION_ENAB) {
		LOG("illegal decimation %d\n",ibuf[29]);
2117
		mutex_unlock(&cam->param_lock);
L
Linus Torvalds 已提交
2118 2119
		return -1;
	}
2120
	decimation = (ibuf[29] == DECIMATION_ENAB);
L
Linus Torvalds 已提交
2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132

	cam->params.yuvThreshold.yThreshold = ibuf[30];
	cam->params.yuvThreshold.uvThreshold = ibuf[31];
	cam->params.status.systemState = ibuf[32];
	cam->params.status.grabState = ibuf[33];
	cam->params.status.streamState = ibuf[34];
	cam->params.status.fatalError = ibuf[35];
	cam->params.status.cmdError = ibuf[36];
	cam->params.status.debugFlags = ibuf[37];
	cam->params.status.vpStatus = ibuf[38];
	cam->params.status.errorCode = ibuf[39];
	cam->fps = ibuf[41];
2133
	mutex_unlock(&cam->param_lock);
2134

L
Linus Torvalds 已提交
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152
	linesize = skipcount(cols, out_fmt);
	ibuf += FRAME_HEADER_SIZE;
	size -= FRAME_HEADER_SIZE;
	ll = ibuf[0] | (ibuf[1] << 8);
	ibuf += 2;
	even_line = 1;

	while (size > 0) {
		size -= (ll+2);
		if (size < 0) {
			LOG("Insufficient data in buffer\n");
			return -1;
		}

		while (ll > 1) {
			if (!compressed || (compressed && !(*ibuf & 1))) {
				if(subsample_422 || even_line) {
				obuf += yuvconvert(ibuf, obuf, out_fmt,
2153
						   in_uyvy, cam->mmap_kludge);
L
Linus Torvalds 已提交
2154 2155 2156 2157 2158
				ibuf += 4;
				ll -= 4;
			} else {
					/* SUBSAMPLE_420 on an odd line */
					obuf += convert420(ibuf, obuf,
2159 2160
							   out_fmt, linesize,
							   cam->mmap_kludge);
L
Linus Torvalds 已提交
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185
					ibuf += 2;
					ll -= 2;
				}
			} else {
				/*skip compressed interval from previous frame*/
				obuf += skipcount(*ibuf >> 1, out_fmt);
				if (obuf > end_obuf) {
					LOG("Insufficient buffer size\n");
					return -1;
				}
				++ibuf;
				ll--;
			}
		}
		if (ll == 1) {
			if (*ibuf != EOL) {
				DBG("EOL not found giving up after %d/%d"
				    " bytes\n", origsize-size, origsize);
				return -1;
			}

			++ibuf; /* skip over EOL */

			if ((size > 3) && (ibuf[0] == EOI) && (ibuf[1] == EOI) &&
			   (ibuf[2] == EOI) && (ibuf[3] == EOI)) {
2186
				size -= 4;
L
Linus Torvalds 已提交
2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206
				break;
			}

			if(decimation) {
				/* skip the odd lines for now */
				obuf += linesize;
			}

			if (size > 1) {
				ll = ibuf[0] | (ibuf[1] << 8);
				ibuf += 2; /* skip over line length */
			}
			if(!decimation)
				even_line = !even_line;
		} else {
			LOG("line length was not 1 but %d after %d/%d bytes\n",
			    ll, origsize-size, origsize);
			return -1;
		}
	}
2207

L
Linus Torvalds 已提交
2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235
	if(decimation) {
		/* interpolate odd rows */
		int i, j;
		u8 *prev, *next;
		prev = cam->decompressed_frame.data;
		obuf = prev+linesize;
		next = obuf+linesize;
		for(i=1; i<rows-1; i+=2) {
			for(j=0; j<linesize; ++j) {
				*obuf++ = ((int)*prev++ + *next++) / 2;
			}
			prev += linesize;
			obuf += linesize;
			next += linesize;
		}
		/* last row is odd, just copy previous row */
		memcpy(obuf, prev, linesize);
	}

	cam->decompressed_frame.count = obuf-cam->decompressed_frame.data;

	return cam->decompressed_frame.count;
}

/* InitStreamCap wrapper to select correct start line */
static inline int init_stream_cap(struct cam_data *cam)
{
	return do_command(cam, CPIA_COMMAND_InitStreamCap,
2236
			  0, cam->params.streamStartLine, 0, 0);
L
Linus Torvalds 已提交
2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256
}


/*  find_over_exposure
 *    Finds a suitable value of OverExposure for use with SetFlickerCtrl
 *    Some calculation is required because this value changes with the brightness
 *    set with SetColourParameters
 *
 *  Parameters: Brightness  -  last brightness value set with SetColourParameters
 *
 *  Returns: OverExposure value to use with SetFlickerCtrl
 */
#define FLICKER_MAX_EXPOSURE                    250
#define FLICKER_ALLOWABLE_OVER_EXPOSURE         146
#define FLICKER_BRIGHTNESS_CONSTANT             59
static int find_over_exposure(int brightness)
{
	int MaxAllowableOverExposure, OverExposure;

	MaxAllowableOverExposure = FLICKER_MAX_EXPOSURE - brightness -
2257
				   FLICKER_BRIGHTNESS_CONSTANT;
L
Linus Torvalds 已提交
2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273

	if (MaxAllowableOverExposure < FLICKER_ALLOWABLE_OVER_EXPOSURE) {
		OverExposure = MaxAllowableOverExposure;
	} else {
		OverExposure = FLICKER_ALLOWABLE_OVER_EXPOSURE;
	}

	return OverExposure;
}
#undef FLICKER_MAX_EXPOSURE
#undef FLICKER_ALLOWABLE_OVER_EXPOSURE
#undef FLICKER_BRIGHTNESS_CONSTANT

/* update various camera modes and settings */
static void dispatch_commands(struct cam_data *cam)
{
2274
	mutex_lock(&cam->param_lock);
L
Linus Torvalds 已提交
2275
	if (cam->cmd_queue==COMMAND_NONE) {
2276
		mutex_unlock(&cam->param_lock);
L
Linus Torvalds 已提交
2277 2278 2279 2280 2281 2282
		return;
	}
	DEB_BYTE(cam->cmd_queue);
	DEB_BYTE(cam->cmd_queue>>8);
	if (cam->cmd_queue & COMMAND_SETFORMAT) {
		do_command(cam, CPIA_COMMAND_SetFormat,
2283 2284 2285
			   cam->params.format.videoSize,
			   cam->params.format.subSample,
			   cam->params.format.yuvOrder, 0);
L
Linus Torvalds 已提交
2286
		do_command(cam, CPIA_COMMAND_SetROI,
2287 2288
			   cam->params.roi.colStart, cam->params.roi.colEnd,
			   cam->params.roi.rowStart, cam->params.roi.rowEnd);
L
Linus Torvalds 已提交
2289 2290 2291 2292 2293
		cam->first_frame = 1;
	}

	if (cam->cmd_queue & COMMAND_SETCOLOURPARAMS)
		do_command(cam, CPIA_COMMAND_SetColourParams,
2294 2295 2296
			   cam->params.colourParams.brightness,
			   cam->params.colourParams.contrast,
			   cam->params.colourParams.saturation, 0);
L
Linus Torvalds 已提交
2297 2298 2299

	if (cam->cmd_queue & COMMAND_SETAPCOR)
		do_command(cam, CPIA_COMMAND_SetApcor,
2300 2301 2302 2303
			   cam->params.apcor.gain1,
			   cam->params.apcor.gain2,
			   cam->params.apcor.gain4,
			   cam->params.apcor.gain8);
L
Linus Torvalds 已提交
2304 2305 2306

	if (cam->cmd_queue & COMMAND_SETVLOFFSET)
		do_command(cam, CPIA_COMMAND_SetVLOffset,
2307 2308 2309 2310
			   cam->params.vlOffset.gain1,
			   cam->params.vlOffset.gain2,
			   cam->params.vlOffset.gain4,
			   cam->params.vlOffset.gain8);
L
Linus Torvalds 已提交
2311 2312 2313

	if (cam->cmd_queue & COMMAND_SETEXPOSURE) {
		do_command_extended(cam, CPIA_COMMAND_SetExposure,
2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
				    cam->params.exposure.gainMode,
				    1,
				    cam->params.exposure.compMode,
				    cam->params.exposure.centreWeight,
				    cam->params.exposure.gain,
				    cam->params.exposure.fineExp,
				    cam->params.exposure.coarseExpLo,
				    cam->params.exposure.coarseExpHi,
				    cam->params.exposure.redComp,
				    cam->params.exposure.green1Comp,
				    cam->params.exposure.green2Comp,
				    cam->params.exposure.blueComp);
L
Linus Torvalds 已提交
2326 2327
		if(cam->params.exposure.expMode != 1) {
			do_command_extended(cam, CPIA_COMMAND_SetExposure,
2328 2329 2330 2331 2332 2333 2334 2335
					    0,
					    cam->params.exposure.expMode,
					    0, 0,
					    cam->params.exposure.gain,
					    cam->params.exposure.fineExp,
					    cam->params.exposure.coarseExpLo,
					    cam->params.exposure.coarseExpHi,
					    0, 0, 0, 0);
L
Linus Torvalds 已提交
2336 2337
		}
	}
2338

L
Linus Torvalds 已提交
2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360
	if (cam->cmd_queue & COMMAND_SETCOLOURBALANCE) {
		if (cam->params.colourBalance.balanceMode == 1) {
			do_command(cam, CPIA_COMMAND_SetColourBalance,
				   1,
				   cam->params.colourBalance.redGain,
				   cam->params.colourBalance.greenGain,
				   cam->params.colourBalance.blueGain);
			do_command(cam, CPIA_COMMAND_SetColourBalance,
				   3, 0, 0, 0);
		}
		if (cam->params.colourBalance.balanceMode == 2) {
			do_command(cam, CPIA_COMMAND_SetColourBalance,
				   2, 0, 0, 0);
		}
		if (cam->params.colourBalance.balanceMode == 3) {
			do_command(cam, CPIA_COMMAND_SetColourBalance,
				   3, 0, 0, 0);
		}
	}

	if (cam->cmd_queue & COMMAND_SETCOMPRESSIONTARGET)
		do_command(cam, CPIA_COMMAND_SetCompressionTarget,
2361 2362 2363
			   cam->params.compressionTarget.frTargeting,
			   cam->params.compressionTarget.targetFR,
			   cam->params.compressionTarget.targetQ, 0);
L
Linus Torvalds 已提交
2364 2365 2366

	if (cam->cmd_queue & COMMAND_SETYUVTHRESH)
		do_command(cam, CPIA_COMMAND_SetYUVThresh,
2367 2368
			   cam->params.yuvThreshold.yThreshold,
			   cam->params.yuvThreshold.uvThreshold, 0, 0);
L
Linus Torvalds 已提交
2369 2370 2371

	if (cam->cmd_queue & COMMAND_SETCOMPRESSIONPARAMS)
		do_command_extended(cam, CPIA_COMMAND_SetCompressionParams,
2372 2373 2374 2375 2376 2377 2378 2379 2380
			    0, 0, 0, 0,
			    cam->params.compressionParams.hysteresis,
			    cam->params.compressionParams.threshMax,
			    cam->params.compressionParams.smallStep,
			    cam->params.compressionParams.largeStep,
			    cam->params.compressionParams.decimationHysteresis,
			    cam->params.compressionParams.frDiffStepThresh,
			    cam->params.compressionParams.qDiffStepThresh,
			    cam->params.compressionParams.decimationThreshMod);
L
Linus Torvalds 已提交
2381 2382 2383

	if (cam->cmd_queue & COMMAND_SETCOMPRESSION)
		do_command(cam, CPIA_COMMAND_SetCompression,
2384
			   cam->params.compression.mode,
L
Linus Torvalds 已提交
2385 2386 2387 2388
			   cam->params.compression.decimation, 0, 0);

	if (cam->cmd_queue & COMMAND_SETSENSORFPS)
		do_command(cam, CPIA_COMMAND_SetSensorFPS,
2389 2390
			   cam->params.sensorFps.divisor,
			   cam->params.sensorFps.baserate, 0, 0);
L
Linus Torvalds 已提交
2391 2392 2393

	if (cam->cmd_queue & COMMAND_SETFLICKERCTRL)
		do_command(cam, CPIA_COMMAND_SetFlickerCtrl,
2394 2395 2396 2397
			   cam->params.flickerControl.flickerMode,
			   cam->params.flickerControl.coarseJump,
			   abs(cam->params.flickerControl.allowableOverExposure),
			   0);
L
Linus Torvalds 已提交
2398 2399 2400

	if (cam->cmd_queue & COMMAND_SETECPTIMING)
		do_command(cam, CPIA_COMMAND_SetECPTiming,
2401
			   cam->params.ecpTiming, 0, 0, 0);
L
Linus Torvalds 已提交
2402 2403 2404 2405 2406 2407 2408 2409 2410 2411

	if (cam->cmd_queue & COMMAND_PAUSE)
		do_command(cam, CPIA_COMMAND_EndStreamCap, 0, 0, 0, 0);

	if (cam->cmd_queue & COMMAND_RESUME)
		init_stream_cap(cam);

	if (cam->cmd_queue & COMMAND_SETLIGHTS && cam->params.qx3.qx3_detected)
	  {
	    int p1 = (cam->params.qx3.bottomlight == 0) << 1;
2412 2413 2414
	    int p2 = (cam->params.qx3.toplight == 0) << 3;
	    do_command(cam, CPIA_COMMAND_WriteVCReg,  0x90, 0x8F, 0x50, 0);
	    do_command(cam, CPIA_COMMAND_WriteMCPort, 2, 0, (p1|p2|0xE0), 0);
L
Linus Torvalds 已提交
2415 2416 2417
	  }

	cam->cmd_queue = COMMAND_NONE;
2418
	mutex_unlock(&cam->param_lock);
L
Linus Torvalds 已提交
2419 2420 2421 2422 2423 2424
	return;
}



static void set_flicker(struct cam_params *params, volatile u32 *command_flags,
2425
			int on)
L
Linus Torvalds 已提交
2426 2427 2428
{
	/* Everything in here is from the Windows driver */
#define FIRMWARE_VERSION(x,y) (params->version.firmwareVersion == (x) && \
2429
			       params->version.firmwareRevision == (y))
L
Linus Torvalds 已提交
2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443
/* define for compgain calculation */
#if 0
#define COMPGAIN(base, curexp, newexp) \
    (u8) ((((float) base - 128.0) * ((float) curexp / (float) newexp)) + 128.5)
#define EXP_FROM_COMP(basecomp, curcomp, curexp) \
    (u16)((float)curexp * (float)(u8)(curcomp + 128) / (float)(u8)(basecomp - 128))
#else
  /* equivalent functions without floating point math */
#define COMPGAIN(base, curexp, newexp) \
    (u8)(128 + (((u32)(2*(base-128)*curexp + newexp)) / (2* newexp)) )
#define EXP_FROM_COMP(basecomp, curcomp, curexp) \
     (u16)(((u32)(curexp * (u8)(curcomp + 128)) / (u8)(basecomp - 128)))
#endif

2444

L
Linus Torvalds 已提交
2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484
	int currentexp = params->exposure.coarseExpLo +
			 params->exposure.coarseExpHi*256;
	int startexp;
	if (on) {
		int cj = params->flickerControl.coarseJump;
		params->flickerControl.flickerMode = 1;
		params->flickerControl.disabled = 0;
		if(params->exposure.expMode != 2)
			*command_flags |= COMMAND_SETEXPOSURE;
		params->exposure.expMode = 2;
		currentexp = currentexp << params->exposure.gain;
		params->exposure.gain = 0;
		/* round down current exposure to nearest value */
		startexp = (currentexp + ROUND_UP_EXP_FOR_FLICKER) / cj;
		if(startexp < 1)
			startexp = 1;
		startexp = (startexp * cj) - 1;
		if(FIRMWARE_VERSION(1,2))
			while(startexp > MAX_EXP_102)
				startexp -= cj;
		else
			while(startexp > MAX_EXP)
				startexp -= cj;
		params->exposure.coarseExpLo = startexp & 0xff;
		params->exposure.coarseExpHi = startexp >> 8;
		if (currentexp > startexp) {
			if (currentexp > (2 * startexp))
				currentexp = 2 * startexp;
			params->exposure.redComp = COMPGAIN (COMP_RED, currentexp, startexp);
			params->exposure.green1Comp = COMPGAIN (COMP_GREEN1, currentexp, startexp);
			params->exposure.green2Comp = COMPGAIN (COMP_GREEN2, currentexp, startexp);
			params->exposure.blueComp = COMPGAIN (COMP_BLUE, currentexp, startexp);
		} else {
			params->exposure.redComp = COMP_RED;
			params->exposure.green1Comp = COMP_GREEN1;
			params->exposure.green2Comp = COMP_GREEN2;
			params->exposure.blueComp = COMP_BLUE;
		}
		if(FIRMWARE_VERSION(1,2))
			params->exposure.compMode = 0;
2485
		else
L
Linus Torvalds 已提交
2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535
			params->exposure.compMode = 1;

		params->apcor.gain1 = 0x18;
		params->apcor.gain2 = 0x18;
		params->apcor.gain4 = 0x16;
		params->apcor.gain8 = 0x14;
		*command_flags |= COMMAND_SETAPCOR;
	} else {
		params->flickerControl.flickerMode = 0;
		params->flickerControl.disabled = 1;
		/* Coarse = average of equivalent coarse for each comp channel */
		startexp = EXP_FROM_COMP(COMP_RED, params->exposure.redComp, currentexp);
		startexp += EXP_FROM_COMP(COMP_GREEN1, params->exposure.green1Comp, currentexp);
		startexp += EXP_FROM_COMP(COMP_GREEN2, params->exposure.green2Comp, currentexp);
		startexp += EXP_FROM_COMP(COMP_BLUE, params->exposure.blueComp, currentexp);
		startexp = startexp >> 2;
		while(startexp > MAX_EXP &&
		      params->exposure.gain < params->exposure.gainMode-1) {
			startexp = startexp >> 1;
			++params->exposure.gain;
		}
		if(FIRMWARE_VERSION(1,2) && startexp > MAX_EXP_102)
			startexp = MAX_EXP_102;
		if(startexp > MAX_EXP)
			startexp = MAX_EXP;
		params->exposure.coarseExpLo = startexp&0xff;
		params->exposure.coarseExpHi = startexp >> 8;
		params->exposure.redComp = COMP_RED;
		params->exposure.green1Comp = COMP_GREEN1;
		params->exposure.green2Comp = COMP_GREEN2;
		params->exposure.blueComp = COMP_BLUE;
		params->exposure.compMode = 1;
		*command_flags |= COMMAND_SETEXPOSURE;
		params->apcor.gain1 = 0x18;
		params->apcor.gain2 = 0x16;
		params->apcor.gain4 = 0x24;
		params->apcor.gain8 = 0x34;
		*command_flags |= COMMAND_SETAPCOR;
	}
	params->vlOffset.gain1 = 20;
	params->vlOffset.gain2 = 24;
	params->vlOffset.gain4 = 26;
	params->vlOffset.gain8 = 26;
	*command_flags |= COMMAND_SETVLOFFSET;
#undef FIRMWARE_VERSION
#undef EXP_FROM_COMP
#undef COMPGAIN
}

#define FIRMWARE_VERSION(x,y) (cam->params.version.firmwareVersion == (x) && \
2536
			       cam->params.version.firmwareRevision == (y))
L
Linus Torvalds 已提交
2537 2538 2539 2540 2541 2542
/* monitor the exposure and adjust the sensor frame rate if needed */
static void monitor_exposure(struct cam_data *cam)
{
	u8 exp_acc, bcomp, gain, coarseL, cmd[8], data[8];
	int retval, light_exp, dark_exp, very_dark_exp;
	int old_exposure, new_exposure, framerate;
2543

L
Linus Torvalds 已提交
2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564
	/* get necessary stats and register settings from camera */
	/* do_command can't handle this, so do it ourselves */
	cmd[0] = CPIA_COMMAND_ReadVPRegs>>8;
	cmd[1] = CPIA_COMMAND_ReadVPRegs&0xff;
	cmd[2] = 30;
	cmd[3] = 4;
	cmd[4] = 9;
	cmd[5] = 8;
	cmd[6] = 8;
	cmd[7] = 0;
	retval = cam->ops->transferCmd(cam->lowlevel_data, cmd, data);
	if (retval) {
		LOG("ReadVPRegs(30,4,9,8) - failed, retval=%d\n",
		    retval);
		return;
	}
	exp_acc = data[0];
	bcomp = data[1];
	gain = data[2];
	coarseL = data[3];

2565
	mutex_lock(&cam->param_lock);
L
Linus Torvalds 已提交
2566
	light_exp = cam->params.colourParams.brightness +
2567
		    TC - 50 + EXP_ACC_LIGHT;
L
Linus Torvalds 已提交
2568 2569 2570
	if(light_exp > 255)
		light_exp = 255;
	dark_exp = cam->params.colourParams.brightness +
2571
		   TC - 50 - EXP_ACC_DARK;
L
Linus Torvalds 已提交
2572 2573 2574
	if(dark_exp < 0)
		dark_exp = 0;
	very_dark_exp = dark_exp/2;
2575

L
Linus Torvalds 已提交
2576
	old_exposure = cam->params.exposure.coarseExpHi * 256 +
2577
		       cam->params.exposure.coarseExpLo;
L
Linus Torvalds 已提交
2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669

	if(!cam->params.flickerControl.disabled) {
		/* Flicker control on */
		int max_comp = FIRMWARE_VERSION(1,2) ? MAX_COMP : HIGH_COMP_102;
		bcomp += 128;	/* decode */
		if(bcomp >= max_comp && exp_acc < dark_exp) {
			/* dark */
			if(exp_acc < very_dark_exp) {
				/* very dark */
				if(cam->exposure_status == EXPOSURE_VERY_DARK)
					++cam->exposure_count;
				else {
					cam->exposure_status = EXPOSURE_VERY_DARK;
					cam->exposure_count = 1;
				}
			} else {
				/* just dark */
				if(cam->exposure_status == EXPOSURE_DARK)
					++cam->exposure_count;
				else {
					cam->exposure_status = EXPOSURE_DARK;
					cam->exposure_count = 1;
				}
			}
		} else if(old_exposure <= LOW_EXP || exp_acc > light_exp) {
			/* light */
			if(old_exposure <= VERY_LOW_EXP) {
				/* very light */
				if(cam->exposure_status == EXPOSURE_VERY_LIGHT)
					++cam->exposure_count;
				else {
					cam->exposure_status = EXPOSURE_VERY_LIGHT;
					cam->exposure_count = 1;
				}
			} else {
				/* just light */
				if(cam->exposure_status == EXPOSURE_LIGHT)
					++cam->exposure_count;
				else {
					cam->exposure_status = EXPOSURE_LIGHT;
					cam->exposure_count = 1;
				}
			}
		} else {
			/* not dark or light */
			cam->exposure_status = EXPOSURE_NORMAL;
		}
	} else {
		/* Flicker control off */
		if(old_exposure >= MAX_EXP && exp_acc < dark_exp) {
			/* dark */
			if(exp_acc < very_dark_exp) {
				/* very dark */
				if(cam->exposure_status == EXPOSURE_VERY_DARK)
					++cam->exposure_count;
				else {
					cam->exposure_status = EXPOSURE_VERY_DARK;
					cam->exposure_count = 1;
				}
			} else {
				/* just dark */
				if(cam->exposure_status == EXPOSURE_DARK)
					++cam->exposure_count;
				else {
					cam->exposure_status = EXPOSURE_DARK;
					cam->exposure_count = 1;
				}
			}
		} else if(old_exposure <= LOW_EXP || exp_acc > light_exp) {
			/* light */
			if(old_exposure <= VERY_LOW_EXP) {
				/* very light */
				if(cam->exposure_status == EXPOSURE_VERY_LIGHT)
					++cam->exposure_count;
				else {
					cam->exposure_status = EXPOSURE_VERY_LIGHT;
					cam->exposure_count = 1;
				}
			} else {
				/* just light */
				if(cam->exposure_status == EXPOSURE_LIGHT)
					++cam->exposure_count;
				else {
					cam->exposure_status = EXPOSURE_LIGHT;
					cam->exposure_count = 1;
				}
			}
		} else {
			/* not dark or light */
			cam->exposure_status = EXPOSURE_NORMAL;
		}
	}
2670

L
Linus Torvalds 已提交
2671 2672 2673
	framerate = cam->fps;
	if(framerate > 30 || framerate < 1)
		framerate = 1;
2674

L
Linus Torvalds 已提交
2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685
	if(!cam->params.flickerControl.disabled) {
		/* Flicker control on */
		if((cam->exposure_status == EXPOSURE_VERY_DARK ||
		    cam->exposure_status == EXPOSURE_DARK) &&
		   cam->exposure_count >= DARK_TIME*framerate &&
		   cam->params.sensorFps.divisor < 3) {

			/* dark for too long */
			++cam->params.sensorFps.divisor;
			cam->cmd_queue |= COMMAND_SETSENSORFPS;

2686
			cam->params.flickerControl.coarseJump =
L
Linus Torvalds 已提交
2687
				flicker_jumps[cam->mainsFreq]
2688 2689
					     [cam->params.sensorFps.baserate]
					     [cam->params.sensorFps.divisor];
L
Linus Torvalds 已提交
2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706
			cam->cmd_queue |= COMMAND_SETFLICKERCTRL;

			new_exposure = cam->params.flickerControl.coarseJump-1;
			while(new_exposure < old_exposure/2)
				new_exposure += cam->params.flickerControl.coarseJump;
			cam->params.exposure.coarseExpLo = new_exposure & 0xff;
			cam->params.exposure.coarseExpHi = new_exposure >> 8;
			cam->cmd_queue |= COMMAND_SETEXPOSURE;
			cam->exposure_status = EXPOSURE_NORMAL;
			LOG("Automatically decreasing sensor_fps\n");

		} else if((cam->exposure_status == EXPOSURE_VERY_LIGHT ||
		    cam->exposure_status == EXPOSURE_LIGHT) &&
		   cam->exposure_count >= LIGHT_TIME*framerate &&
		   cam->params.sensorFps.divisor > 0) {

			/* light for too long */
2707
			int max_exp = FIRMWARE_VERSION(1,2) ? MAX_EXP_102 : MAX_EXP ;
L
Linus Torvalds 已提交
2708 2709 2710 2711

			--cam->params.sensorFps.divisor;
			cam->cmd_queue |= COMMAND_SETSENSORFPS;

2712
			cam->params.flickerControl.coarseJump =
L
Linus Torvalds 已提交
2713
				flicker_jumps[cam->mainsFreq]
2714 2715
					     [cam->params.sensorFps.baserate]
					     [cam->params.sensorFps.divisor];
L
Linus Torvalds 已提交
2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764
			cam->cmd_queue |= COMMAND_SETFLICKERCTRL;

			new_exposure = cam->params.flickerControl.coarseJump-1;
			while(new_exposure < 2*old_exposure &&
			      new_exposure+
			      cam->params.flickerControl.coarseJump < max_exp)
				new_exposure += cam->params.flickerControl.coarseJump;
			cam->params.exposure.coarseExpLo = new_exposure & 0xff;
			cam->params.exposure.coarseExpHi = new_exposure >> 8;
			cam->cmd_queue |= COMMAND_SETEXPOSURE;
			cam->exposure_status = EXPOSURE_NORMAL;
			LOG("Automatically increasing sensor_fps\n");
		}
	} else {
		/* Flicker control off */
		if((cam->exposure_status == EXPOSURE_VERY_DARK ||
		    cam->exposure_status == EXPOSURE_DARK) &&
		   cam->exposure_count >= DARK_TIME*framerate &&
		   cam->params.sensorFps.divisor < 3) {

			/* dark for too long */
			++cam->params.sensorFps.divisor;
			cam->cmd_queue |= COMMAND_SETSENSORFPS;

			if(cam->params.exposure.gain > 0) {
				--cam->params.exposure.gain;
				cam->cmd_queue |= COMMAND_SETEXPOSURE;
			}
			cam->exposure_status = EXPOSURE_NORMAL;
			LOG("Automatically decreasing sensor_fps\n");

		} else if((cam->exposure_status == EXPOSURE_VERY_LIGHT ||
		    cam->exposure_status == EXPOSURE_LIGHT) &&
		   cam->exposure_count >= LIGHT_TIME*framerate &&
		   cam->params.sensorFps.divisor > 0) {

			/* light for too long */
			--cam->params.sensorFps.divisor;
			cam->cmd_queue |= COMMAND_SETSENSORFPS;

			if(cam->params.exposure.gain <
			   cam->params.exposure.gainMode-1) {
				++cam->params.exposure.gain;
				cam->cmd_queue |= COMMAND_SETEXPOSURE;
			}
			cam->exposure_status = EXPOSURE_NORMAL;
			LOG("Automatically increasing sensor_fps\n");
		}
	}
2765
	mutex_unlock(&cam->param_lock);
L
Linus Torvalds 已提交
2766 2767 2768 2769 2770 2771 2772 2773 2774
}

/*-----------------------------------------------------------------*/
/* if flicker is switched off, this function switches it back on.It checks,
   however, that conditions are suitable before restarting it.
   This should only be called for firmware version 1.2.

   It also adjust the colour balance when an exposure step is detected - as
   long as flicker is running
2775
*/
L
Linus Torvalds 已提交
2776 2777 2778 2779 2780
static void restart_flicker(struct cam_data *cam)
{
	int cam_exposure, old_exp;
	if(!FIRMWARE_VERSION(1,2))
		return;
2781
	mutex_lock(&cam->param_lock);
L
Linus Torvalds 已提交
2782 2783
	if(cam->params.flickerControl.flickerMode == 0 ||
	   cam->raw_image[39] == 0) {
2784
		mutex_unlock(&cam->param_lock);
L
Linus Torvalds 已提交
2785 2786 2787 2788
		return;
	}
	cam_exposure = cam->raw_image[39]*2;
	old_exp = cam->params.exposure.coarseExpLo +
2789 2790 2791 2792 2793 2794
		  cam->params.exposure.coarseExpHi*256;
	/*
	  see how far away camera exposure is from a valid
	  flicker exposure value
	*/
	cam_exposure %= cam->params.flickerControl.coarseJump;
L
Linus Torvalds 已提交
2795
	if(!cam->params.flickerControl.disabled &&
2796
	   cam_exposure <= cam->params.flickerControl.coarseJump - 3) {
L
Linus Torvalds 已提交
2797 2798 2799
		/* Flicker control auto-disabled */
		cam->params.flickerControl.disabled = 1;
	}
2800

L
Linus Torvalds 已提交
2801 2802 2803
	if(cam->params.flickerControl.disabled &&
	   cam->params.flickerControl.flickerMode &&
	   old_exp > cam->params.flickerControl.coarseJump +
2804
		     ROUND_UP_EXP_FOR_FLICKER) {
L
Linus Torvalds 已提交
2805 2806 2807 2808 2809 2810 2811 2812
		/* exposure is now high enough to switch
		   flicker control back on */
		set_flicker(&cam->params, &cam->cmd_queue, 1);
		if((cam->cmd_queue & COMMAND_SETEXPOSURE) &&
		   cam->params.exposure.expMode == 2)
			cam->exposure_status = EXPOSURE_NORMAL;

	}
2813
	mutex_unlock(&cam->param_lock);
L
Linus Torvalds 已提交
2814 2815 2816 2817 2818 2819 2820
}
#undef FIRMWARE_VERSION

static int clear_stall(struct cam_data *cam)
{
	/* FIXME: Does this actually work? */
	LOG("Clearing stall\n");
2821

L
Linus Torvalds 已提交
2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880
	cam->ops->streamRead(cam->lowlevel_data, cam->raw_image, 0);
	do_command(cam, CPIA_COMMAND_GetCameraStatus,0,0,0,0);
	return cam->params.status.streamState != STREAM_PAUSED;
}

/* kernel thread function to read image from camera */
static int fetch_frame(void *data)
{
	int image_size, retry;
	struct cam_data *cam = (struct cam_data *)data;
	unsigned long oldjif, rate, diff;

	/* Allow up to two bad images in a row to be read and
	 * ignored before an error is reported */
	for (retry = 0; retry < 3; ++retry) {
		if (retry)
			DBG("retry=%d\n", retry);

		if (!cam->ops)
			continue;

		/* load first frame always uncompressed */
		if (cam->first_frame &&
		    cam->params.compression.mode != CPIA_COMPRESSION_NONE) {
			do_command(cam, CPIA_COMMAND_SetCompression,
				   CPIA_COMPRESSION_NONE,
				   NO_DECIMATION, 0, 0);
			/* Trial & error - Discarding a frame prevents the
			   first frame from having an error in the data. */
			do_command(cam, CPIA_COMMAND_DiscardFrame, 0, 0, 0, 0);
		}

		/* init camera upload */
		if (do_command(cam, CPIA_COMMAND_GrabFrame, 0,
			       cam->params.streamStartLine, 0, 0))
			continue;

		if (cam->ops->wait_for_stream_ready) {
			/* loop until image ready */
			int count = 0;
			do_command(cam, CPIA_COMMAND_GetCameraStatus,0,0,0,0);
			while (cam->params.status.streamState != STREAM_READY) {
				if(++count > READY_TIMEOUT)
					break;
				if(cam->params.status.streamState ==
				   STREAM_PAUSED) {
					/* Bad news */
					if(!clear_stall(cam))
						return -EIO;
				}

				cond_resched();

				/* sleep for 10 ms, hopefully ;) */
				msleep_interruptible(10);
				if (signal_pending(current))
					return -EINTR;

				do_command(cam, CPIA_COMMAND_GetCameraStatus,
2881
					   0, 0, 0, 0);
L
Linus Torvalds 已提交
2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905
			}
			if(cam->params.status.streamState != STREAM_READY) {
				continue;
			}
		}

		cond_resched();

		/* grab image from camera */
		oldjif = jiffies;
		image_size = cam->ops->streamRead(cam->lowlevel_data,
						  cam->raw_image, 0);
		if (image_size <= 0) {
			DBG("streamRead failed: %d\n", image_size);
			continue;
		}

		rate = image_size * HZ / 1024;
		diff = jiffies-oldjif;
		cam->transfer_rate = diff==0 ? rate : rate/diff;
			/* diff==0 ? unlikely but possible */

		/* Switch flicker control back on if it got turned off */
		restart_flicker(cam);
2906

L
Linus Torvalds 已提交
2907 2908 2909 2910
		/* If AEC is enabled, monitor the exposure and
		   adjust the sensor frame rate if needed */
		if(cam->params.exposure.expMode == 2)
			monitor_exposure(cam);
2911

L
Linus Torvalds 已提交
2912 2913 2914 2915
		/* camera idle now so dispatch queued commands */
		dispatch_commands(cam);

		/* Update our knowledge of the camera state */
2916 2917
		do_command(cam, CPIA_COMMAND_GetColourBalance, 0, 0, 0, 0);
		do_command(cam, CPIA_COMMAND_GetExposure, 0, 0, 0, 0);
L
Linus Torvalds 已提交
2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935
		do_command(cam, CPIA_COMMAND_ReadMCPorts, 0, 0, 0, 0);

		/* decompress and convert image to by copying it from
		 * raw_image to decompressed_frame
		 */

		cond_resched();

		cam->image_size = parse_picture(cam, image_size);
		if (cam->image_size <= 0) {
			DBG("parse_picture failed %d\n", cam->image_size);
			if(cam->params.compression.mode !=
			   CPIA_COMPRESSION_NONE) {
				/* Compression may not work right if we
				   had a bad frame, get the next one
				   uncompressed. */
				cam->first_frame = 1;
				do_command(cam, CPIA_COMMAND_SetGrabMode,
2936
					   CPIA_GRAB_SINGLE, 0, 0, 0);
L
Linus Torvalds 已提交
2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959
				/* FIXME: Trial & error - need up to 70ms for
				   the grab mode change to complete ? */
				msleep_interruptible(70);
				if (signal_pending(current))
					return -EINTR;
			}
		} else
			break;
	}

	if (retry < 3) {
		/* FIXME: this only works for double buffering */
		if (cam->frame[cam->curframe].state == FRAME_READY) {
			memcpy(cam->frame[cam->curframe].data,
			       cam->decompressed_frame.data,
			       cam->decompressed_frame.count);
			cam->frame[cam->curframe].state = FRAME_DONE;
		} else
			cam->decompressed_frame.state = FRAME_DONE;

		if (cam->first_frame) {
			cam->first_frame = 0;
			do_command(cam, CPIA_COMMAND_SetCompression,
2960
				   cam->params.compression.mode,
L
Linus Torvalds 已提交
2961 2962 2963 2964
				   cam->params.compression.decimation, 0, 0);

			/* Switch from single-grab to continuous grab */
			do_command(cam, CPIA_COMMAND_SetGrabMode,
2965
				   CPIA_GRAB_CONTINUOUS, 0, 0, 0);
L
Linus Torvalds 已提交
2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979
		}
		return 0;
	}
	return -EIO;
}

static int capture_frame(struct cam_data *cam, struct video_mmap *vm)
{
	if (!cam->frame_buf) {
		/* we do lazy allocation */
		int err;
		if ((err = allocate_frame_buf(cam)))
			return err;
	}
2980

L
Linus Torvalds 已提交
2981 2982 2983 2984
	cam->curframe = vm->frame;
	cam->frame[cam->curframe].state = FRAME_READY;
	return fetch_frame(cam);
}
2985

L
Linus Torvalds 已提交
2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041
static int goto_high_power(struct cam_data *cam)
{
	if (do_command(cam, CPIA_COMMAND_GotoHiPower, 0, 0, 0, 0))
		return -EIO;
	msleep_interruptible(40);	/* windows driver does it too */
	if(signal_pending(current))
		return -EINTR;
	if (do_command(cam, CPIA_COMMAND_GetCameraStatus, 0, 0, 0, 0))
		return -EIO;
	if (cam->params.status.systemState == HI_POWER_STATE) {
		DBG("camera now in HIGH power state\n");
		return 0;
	}
	printstatus(cam);
	return -EIO;
}

static int goto_low_power(struct cam_data *cam)
{
	if (do_command(cam, CPIA_COMMAND_GotoLoPower, 0, 0, 0, 0))
		return -1;
	if (do_command(cam, CPIA_COMMAND_GetCameraStatus, 0, 0, 0, 0))
		return -1;
	if (cam->params.status.systemState == LO_POWER_STATE) {
		DBG("camera now in LOW power state\n");
		return 0;
	}
	printstatus(cam);
	return -1;
}

static void save_camera_state(struct cam_data *cam)
{
	if(!(cam->cmd_queue & COMMAND_SETCOLOURBALANCE))
		do_command(cam, CPIA_COMMAND_GetColourBalance, 0, 0, 0, 0);
	if(!(cam->cmd_queue & COMMAND_SETEXPOSURE))
		do_command(cam, CPIA_COMMAND_GetExposure, 0, 0, 0, 0);

	DBG("%d/%d/%d/%d/%d/%d/%d/%d\n",
	     cam->params.exposure.gain,
	     cam->params.exposure.fineExp,
	     cam->params.exposure.coarseExpLo,
	     cam->params.exposure.coarseExpHi,
	     cam->params.exposure.redComp,
	     cam->params.exposure.green1Comp,
	     cam->params.exposure.green2Comp,
	     cam->params.exposure.blueComp);
	DBG("%d/%d/%d\n",
	     cam->params.colourBalance.redGain,
	     cam->params.colourBalance.greenGain,
	     cam->params.colourBalance.blueGain);
}

static int set_camera_state(struct cam_data *cam)
{
	cam->cmd_queue = COMMAND_SETCOMPRESSION |
3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053
			 COMMAND_SETCOMPRESSIONTARGET |
			 COMMAND_SETCOLOURPARAMS |
			 COMMAND_SETFORMAT |
			 COMMAND_SETYUVTHRESH |
			 COMMAND_SETECPTIMING |
			 COMMAND_SETCOMPRESSIONPARAMS |
			 COMMAND_SETEXPOSURE |
			 COMMAND_SETCOLOURBALANCE |
			 COMMAND_SETSENSORFPS |
			 COMMAND_SETAPCOR |
			 COMMAND_SETFLICKERCTRL |
			 COMMAND_SETVLOFFSET;
L
Linus Torvalds 已提交
3054 3055 3056

	do_command(cam, CPIA_COMMAND_SetGrabMode, CPIA_GRAB_SINGLE,0,0,0);
	dispatch_commands(cam);
3057

L
Linus Torvalds 已提交
3058 3059 3060 3061 3062 3063 3064
	/* Wait 6 frames for the sensor to get all settings and
	   AEC/ACB to settle */
	msleep_interruptible(6*(cam->params.sensorFps.baserate ? 33 : 40) *
			       (1 << cam->params.sensorFps.divisor) + 10);

	if(signal_pending(current))
		return -EINTR;
3065

L
Linus Torvalds 已提交
3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096
	save_camera_state(cam);

	return 0;
}

static void get_version_information(struct cam_data *cam)
{
	/* GetCPIAVersion */
	do_command(cam, CPIA_COMMAND_GetCPIAVersion, 0, 0, 0, 0);

	/* GetPnPID */
	do_command(cam, CPIA_COMMAND_GetPnPID, 0, 0, 0, 0);
}

/* initialize camera */
static int reset_camera(struct cam_data *cam)
{
	int err;
	/* Start the camera in low power mode */
	if (goto_low_power(cam)) {
		if (cam->params.status.systemState != WARM_BOOT_STATE)
			return -ENODEV;

		/* FIXME: this is just dirty trial and error */
		err = goto_high_power(cam);
		if(err)
			return err;
		do_command(cam, CPIA_COMMAND_DiscardFrame, 0, 0, 0, 0);
		if (goto_low_power(cam))
			return -ENODEV;
	}
3097

L
Linus Torvalds 已提交
3098
	/* procedure described in developer's guide p3-28 */
3099

L
Linus Torvalds 已提交
3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115
	/* Check the firmware version. */
	cam->params.version.firmwareVersion = 0;
	get_version_information(cam);
	if (cam->params.version.firmwareVersion != 1)
		return -ENODEV;

	/* A bug in firmware 1-02 limits gainMode to 2 */
	if(cam->params.version.firmwareRevision <= 2 &&
	   cam->params.exposure.gainMode > 2) {
		cam->params.exposure.gainMode = 2;
	}

	/* set QX3 detected flag */
	cam->params.qx3.qx3_detected = (cam->params.pnpID.vendor == 0x0813 &&
					cam->params.pnpID.product == 0x0001);

3116
	/* The fatal error checking should be done after
L
Linus Torvalds 已提交
3117 3118 3119 3120 3121
	 * the camera powers up (developer's guide p 3-38) */

	/* Set streamState before transition to high power to avoid bug
	 * in firmware 1-02 */
	do_command(cam, CPIA_COMMAND_ModifyCameraStatus, STREAMSTATE, 0,
3122 3123
		   STREAM_NOT_READY, 0);

L
Linus Torvalds 已提交
3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144
	/* GotoHiPower */
	err = goto_high_power(cam);
	if (err)
		return err;

	/* Check the camera status */
	if (do_command(cam, CPIA_COMMAND_GetCameraStatus, 0, 0, 0, 0))
		return -EIO;

	if (cam->params.status.fatalError) {
		DBG("fatal_error:              %#04x\n",
		    cam->params.status.fatalError);
		DBG("vp_status:                %#04x\n",
		    cam->params.status.vpStatus);
		if (cam->params.status.fatalError & ~(COM_FLAG|CPIA_FLAG)) {
			/* Fatal error in camera */
			return -EIO;
		} else if (cam->params.status.fatalError & (COM_FLAG|CPIA_FLAG)) {
			/* Firmware 1-02 may do this for parallel port cameras,
			 * just clear the flags (developer's guide p 3-38) */
			do_command(cam, CPIA_COMMAND_ModifyCameraStatus,
3145
				   FATALERROR, ~(COM_FLAG|CPIA_FLAG), 0, 0);
L
Linus Torvalds 已提交
3146 3147
		}
	}
3148

L
Linus Torvalds 已提交
3149 3150 3151 3152 3153
	/* Check the camera status again */
	if (cam->params.status.fatalError) {
		if (cam->params.status.fatalError)
			return -EIO;
	}
3154

L
Linus Torvalds 已提交
3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188
	/* VPVersion can't be retrieved before the camera is in HiPower,
	 * so get it here instead of in get_version_information. */
	do_command(cam, CPIA_COMMAND_GetVPVersion, 0, 0, 0, 0);

	/* set camera to a known state */
	return set_camera_state(cam);
}

static void put_cam(struct cpia_camera_ops* ops)
{
	if (ops->owner)
		module_put(ops->owner);
}

/* ------------------------- V4L interface --------------------- */
static int cpia_open(struct inode *inode, struct file *file)
{
	struct video_device *dev = video_devdata(file);
	struct cam_data *cam = dev->priv;
	int err;

	if (!cam) {
		DBG("Internal error, cam_data not found!\n");
		return -ENODEV;
	}

	if (cam->open_count > 0) {
		DBG("Camera already open\n");
		return -EBUSY;
	}

	if (!try_module_get(cam->ops->owner))
		return -ENODEV;

3189
	mutex_lock(&cam->busy_lock);
L
Linus Torvalds 已提交
3190 3191 3192 3193 3194 3195
	err = -ENOMEM;
	if (!cam->raw_image) {
		cam->raw_image = rvmalloc(CPIA_MAX_IMAGE_SIZE);
		if (!cam->raw_image)
			goto oops;
	}
3196

L
Linus Torvalds 已提交
3197 3198 3199 3200 3201
	if (!cam->decompressed_frame.data) {
		cam->decompressed_frame.data = rvmalloc(CPIA_MAX_FRAME_SIZE);
		if (!cam->decompressed_frame.data)
			goto oops;
	}
3202

L
Linus Torvalds 已提交
3203 3204 3205 3206
	/* open cpia */
	err = -ENODEV;
	if (cam->ops->open(cam->lowlevel_data))
		goto oops;
3207

L
Linus Torvalds 已提交
3208 3209 3210 3211 3212
	/* reset the camera */
	if ((err = reset_camera(cam)) != 0) {
		cam->ops->close(cam->lowlevel_data);
		goto oops;
	}
3213

L
Linus Torvalds 已提交
3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226
	err = -EINTR;
	if(signal_pending(current))
		goto oops;

	/* Set ownership of /proc/cpia/videoX to current user */
	if(cam->proc_entry)
		cam->proc_entry->uid = current->uid;

	/* set mark for loading first frame uncompressed */
	cam->first_frame = 1;

	/* init it to something */
	cam->mmap_kludge = 0;
3227

L
Linus Torvalds 已提交
3228 3229
	++cam->open_count;
	file->private_data = dev;
3230
	mutex_unlock(&cam->busy_lock);
L
Linus Torvalds 已提交
3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241
	return 0;

 oops:
	if (cam->decompressed_frame.data) {
		rvfree(cam->decompressed_frame.data, CPIA_MAX_FRAME_SIZE);
		cam->decompressed_frame.data = NULL;
	}
	if (cam->raw_image) {
		rvfree(cam->raw_image, CPIA_MAX_IMAGE_SIZE);
		cam->raw_image = NULL;
	}
3242
	mutex_unlock(&cam->busy_lock);
L
Linus Torvalds 已提交
3243 3244 3245 3246 3247 3248 3249 3250 3251 3252
	put_cam(cam->ops);
	return err;
}

static int cpia_close(struct inode *inode, struct file *file)
{
	struct  video_device *dev = file->private_data;
	struct cam_data *cam = dev->priv;

	if (cam->ops) {
3253
		/* Return ownership of /proc/cpia/videoX to root */
L
Linus Torvalds 已提交
3254 3255
		if(cam->proc_entry)
			cam->proc_entry->uid = 0;
3256

L
Linus Torvalds 已提交
3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305
		/* save camera state for later open (developers guide ch 3.5.3) */
		save_camera_state(cam);

		/* GotoLoPower */
		goto_low_power(cam);

		/* Update the camera status */
		do_command(cam, CPIA_COMMAND_GetCameraStatus, 0, 0, 0, 0);

		/* cleanup internal state stuff */
		free_frames(cam->frame);

		/* close cpia */
		cam->ops->close(cam->lowlevel_data);

		put_cam(cam->ops);
	}

	if (--cam->open_count == 0) {
		/* clean up capture-buffers */
		if (cam->raw_image) {
			rvfree(cam->raw_image, CPIA_MAX_IMAGE_SIZE);
			cam->raw_image = NULL;
		}

		if (cam->decompressed_frame.data) {
			rvfree(cam->decompressed_frame.data, CPIA_MAX_FRAME_SIZE);
			cam->decompressed_frame.data = NULL;
		}

		if (cam->frame_buf)
			free_frame_buf(cam);

		if (!cam->ops)
			kfree(cam);
	}
	file->private_data = NULL;

	return 0;
}

static ssize_t cpia_read(struct file *file, char __user *buf,
			 size_t count, loff_t *ppos)
{
	struct video_device *dev = file->private_data;
	struct cam_data *cam = dev->priv;
	int err;

	/* make this _really_ smp and multithread-safe */
3306
	if (mutex_lock_interruptible(&cam->busy_lock))
L
Linus Torvalds 已提交
3307 3308 3309 3310
		return -EINTR;

	if (!buf) {
		DBG("buf NULL\n");
3311
		mutex_unlock(&cam->busy_lock);
L
Linus Torvalds 已提交
3312 3313 3314 3315 3316
		return -EINVAL;
	}

	if (!count) {
		DBG("count 0\n");
3317
		mutex_unlock(&cam->busy_lock);
L
Linus Torvalds 已提交
3318 3319 3320 3321 3322
		return 0;
	}

	if (!cam->ops) {
		DBG("ops NULL\n");
3323
		mutex_unlock(&cam->busy_lock);
L
Linus Torvalds 已提交
3324 3325 3326 3327 3328 3329 3330 3331
		return -ENODEV;
	}

	/* upload frame */
	cam->decompressed_frame.state = FRAME_READY;
	cam->mmap_kludge=0;
	if((err = fetch_frame(cam)) != 0) {
		DBG("ERROR from fetch_frame: %d\n", err);
3332
		mutex_unlock(&cam->busy_lock);
L
Linus Torvalds 已提交
3333 3334 3335 3336 3337 3338 3339 3340
		return err;
	}
	cam->decompressed_frame.state = FRAME_UNUSED;

	/* copy data to user space */
	if (cam->decompressed_frame.count > count) {
		DBG("count wrong: %d, %lu\n", cam->decompressed_frame.count,
		    (unsigned long) count);
3341
		mutex_unlock(&cam->busy_lock);
L
Linus Torvalds 已提交
3342 3343 3344
		return -EFAULT;
	}
	if (copy_to_user(buf, cam->decompressed_frame.data,
3345
			cam->decompressed_frame.count)) {
L
Linus Torvalds 已提交
3346
		DBG("copy_to_user failed\n");
3347
		mutex_unlock(&cam->busy_lock);
L
Linus Torvalds 已提交
3348 3349 3350
		return -EFAULT;
	}

3351
	mutex_unlock(&cam->busy_lock);
L
Linus Torvalds 已提交
3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363
	return cam->decompressed_frame.count;
}

static int cpia_do_ioctl(struct inode *inode, struct file *file,
			 unsigned int ioctlnr, void *arg)
{
	struct video_device *dev = file->private_data;
	struct cam_data *cam = dev->priv;
	int retval = 0;

	if (!cam || !cam->ops)
		return -ENODEV;
3364

L
Linus Torvalds 已提交
3365
	/* make this _really_ smp-safe */
3366
	if (mutex_lock_interruptible(&cam->busy_lock))
L
Linus Torvalds 已提交
3367 3368 3369 3370 3371
		return -EINTR;

	//DBG("cpia_ioctl: %u\n", ioctlnr);

	switch (ioctlnr) {
3372
	/* query capabilities */
L
Linus Torvalds 已提交
3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407
	case VIDIOCGCAP:
	{
		struct video_capability *b = arg;

		DBG("VIDIOCGCAP\n");
		strcpy(b->name, "CPiA Camera");
		b->type = VID_TYPE_CAPTURE | VID_TYPE_SUBCAPTURE;
		b->channels = 1;
		b->audios = 0;
		b->maxwidth = 352;	/* VIDEOSIZE_CIF */
		b->maxheight = 288;
		b->minwidth = 48;	/* VIDEOSIZE_48_48 */
		b->minheight = 48;
		break;
	}

	/* get/set video source - we are a camera and nothing else */
	case VIDIOCGCHAN:
	{
		struct video_channel *v = arg;

		DBG("VIDIOCGCHAN\n");
		if (v->channel != 0) {
			retval = -EINVAL;
			break;
		}

		v->channel = 0;
		strcpy(v->name, "Camera");
		v->tuners = 0;
		v->flags = 0;
		v->type = VIDEO_TYPE_CAMERA;
		v->norm = 0;
		break;
	}
3408

L
Linus Torvalds 已提交
3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426
	case VIDIOCSCHAN:
	{
		struct video_channel *v = arg;

		DBG("VIDIOCSCHAN\n");
		if (v->channel != 0)
			retval = -EINVAL;
		break;
	}

	/* image properties */
	case VIDIOCGPICT:
	{
		struct video_picture *pic = arg;
		DBG("VIDIOCGPICT\n");
		*pic = cam->vp;
		break;
	}
3427

L
Linus Torvalds 已提交
3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441
	case VIDIOCSPICT:
	{
		struct video_picture *vp = arg;

		DBG("VIDIOCSPICT\n");

		/* check validity */
		DBG("palette: %d\n", vp->palette);
		DBG("depth: %d\n", vp->depth);
		if (!valid_mode(vp->palette, vp->depth)) {
			retval = -EINVAL;
			break;
		}

3442
		mutex_lock(&cam->param_lock);
L
Linus Torvalds 已提交
3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460
		/* brightness, colour, contrast need no check 0-65535 */
		cam->vp = *vp;
		/* update cam->params.colourParams */
		cam->params.colourParams.brightness = vp->brightness*100/65535;
		cam->params.colourParams.contrast = vp->contrast*100/65535;
		cam->params.colourParams.saturation = vp->colour*100/65535;
		/* contrast is in steps of 8, so round */
		cam->params.colourParams.contrast =
			((cam->params.colourParams.contrast + 3) / 8) * 8;
		if (cam->params.version.firmwareVersion == 1 &&
		    cam->params.version.firmwareRevision == 2 &&
		    cam->params.colourParams.contrast > 80) {
			/* 1-02 firmware limits contrast to 80 */
			cam->params.colourParams.contrast = 80;
		}

		/* Adjust flicker control if necessary */
		if(cam->params.flickerControl.allowableOverExposure < 0)
3461
			cam->params.flickerControl.allowableOverExposure =
L
Linus Torvalds 已提交
3462 3463 3464
				-find_over_exposure(cam->params.colourParams.brightness);
		if(cam->params.flickerControl.flickerMode != 0)
			cam->cmd_queue |= COMMAND_SETFLICKERCTRL;
3465

L
Linus Torvalds 已提交
3466 3467 3468

		/* queue command to update camera */
		cam->cmd_queue |= COMMAND_SETCOLOURPARAMS;
3469
		mutex_unlock(&cam->param_lock);
L
Linus Torvalds 已提交
3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484
		DBG("VIDIOCSPICT: %d / %d // %d / %d / %d / %d\n",
		    vp->depth, vp->palette, vp->brightness, vp->hue, vp->colour,
		    vp->contrast);
		break;
	}

	/* get/set capture window */
	case VIDIOCGWIN:
	{
		struct video_window *vw = arg;
		DBG("VIDIOCGWIN\n");

		*vw = cam->vw;
		break;
	}
3485

L
Linus Torvalds 已提交
3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503
	case VIDIOCSWIN:
	{
		/* copy_from_user, check validity, copy to internal structure */
		struct video_window *vw = arg;
		DBG("VIDIOCSWIN\n");

		if (vw->clipcount != 0) {    /* clipping not supported */
			retval = -EINVAL;
			break;
		}
		if (vw->clips != NULL) {     /* clipping not supported */
			retval = -EINVAL;
			break;
		}

		/* we set the video window to something smaller or equal to what
		* is requested by the user???
		*/
3504
		mutex_lock(&cam->param_lock);
L
Linus Torvalds 已提交
3505 3506 3507 3508 3509
		if (vw->width != cam->vw.width || vw->height != cam->vw.height) {
			int video_size = match_videosize(vw->width, vw->height);

			if (video_size < 0) {
				retval = -EINVAL;
3510
				mutex_unlock(&cam->param_lock);
L
Linus Torvalds 已提交
3511 3512 3513 3514 3515 3516
				break;
			}
			cam->video_size = video_size;

			/* video size is changing, reset the subcapture area */
			memset(&cam->vc, 0, sizeof(cam->vc));
3517

L
Linus Torvalds 已提交
3518 3519 3520 3521 3522
			set_vw_size(cam);
			DBG("%d / %d\n", cam->vw.width, cam->vw.height);
			cam->cmd_queue |= COMMAND_SETFORMAT;
		}

3523
		mutex_unlock(&cam->param_lock);
L
Linus Torvalds 已提交
3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549

		/* setformat ignored by camera during streaming,
		 * so stop/dispatch/start */
		if (cam->cmd_queue & COMMAND_SETFORMAT) {
			DBG("\n");
			dispatch_commands(cam);
		}
		DBG("%d/%d:%d\n", cam->video_size,
		    cam->vw.width, cam->vw.height);
		break;
	}

	/* mmap interface */
	case VIDIOCGMBUF:
	{
		struct video_mbuf *vm = arg;
		int i;

		DBG("VIDIOCGMBUF\n");
		memset(vm, 0, sizeof(*vm));
		vm->size = CPIA_MAX_FRAME_SIZE*FRAME_NUM;
		vm->frames = FRAME_NUM;
		for (i = 0; i < FRAME_NUM; i++)
			vm->offsets[i] = CPIA_MAX_FRAME_SIZE * i;
		break;
	}
3550

L
Linus Torvalds 已提交
3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599
	case VIDIOCMCAPTURE:
	{
		struct video_mmap *vm = arg;
		int video_size;

		DBG("VIDIOCMCAPTURE: %d / %d / %dx%d\n", vm->format, vm->frame,
		    vm->width, vm->height);
		if (vm->frame<0||vm->frame>=FRAME_NUM) {
			retval = -EINVAL;
			break;
		}

		/* set video format */
		cam->vp.palette = vm->format;
		switch(vm->format) {
		case VIDEO_PALETTE_GREY:
			cam->vp.depth=8;
			break;
		case VIDEO_PALETTE_RGB555:
		case VIDEO_PALETTE_RGB565:
		case VIDEO_PALETTE_YUV422:
		case VIDEO_PALETTE_YUYV:
		case VIDEO_PALETTE_UYVY:
			cam->vp.depth = 16;
			break;
		case VIDEO_PALETTE_RGB24:
			cam->vp.depth = 24;
			break;
		case VIDEO_PALETTE_RGB32:
			cam->vp.depth = 32;
			break;
		default:
			retval = -EINVAL;
			break;
		}
		if (retval)
			break;

		/* set video size */
		video_size = match_videosize(vm->width, vm->height);
		if (video_size < 0) {
			retval = -EINVAL;
			break;
		}
		if (video_size != cam->video_size) {
			cam->video_size = video_size;

			/* video size is changing, reset the subcapture area */
			memset(&cam->vc, 0, sizeof(cam->vc));
3600

L
Linus Torvalds 已提交
3601 3602 3603 3604 3605 3606 3607 3608 3609 3610
			set_vw_size(cam);
			cam->cmd_queue |= COMMAND_SETFORMAT;
			dispatch_commands(cam);
		}
		/* according to v4l-spec we must start streaming here */
		cam->mmap_kludge = 1;
		retval = capture_frame(cam, vm);

		break;
	}
3611

L
Linus Torvalds 已提交
3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651
	case VIDIOCSYNC:
	{
		int *frame = arg;

		//DBG("VIDIOCSYNC: %d\n", *frame);

		if (*frame<0 || *frame >= FRAME_NUM) {
			retval = -EINVAL;
			break;
		}

		switch (cam->frame[*frame].state) {
		case FRAME_UNUSED:
		case FRAME_READY:
		case FRAME_GRABBING:
			DBG("sync to unused frame %d\n", *frame);
			retval = -EINVAL;
			break;

		case FRAME_DONE:
			cam->frame[*frame].state = FRAME_UNUSED;
			//DBG("VIDIOCSYNC: %d synced\n", *frame);
			break;
		}
		if (retval == -EINTR) {
			/* FIXME - xawtv does not handle this nice */
			retval = 0;
		}
		break;
	}

	case VIDIOCGCAPTURE:
	{
		struct video_capture *vc = arg;

		DBG("VIDIOCGCAPTURE\n");

		*vc = cam->vc;

		break;
3652
	}
L
Linus Torvalds 已提交
3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667

	case VIDIOCSCAPTURE:
	{
		struct video_capture *vc = arg;

		DBG("VIDIOCSCAPTURE\n");

		if (vc->decimation != 0) {    /* How should this be used? */
			retval = -EINVAL;
			break;
		}
		if (vc->flags != 0) {     /* Even/odd grab not supported */
			retval = -EINVAL;
			break;
		}
3668

L
Linus Torvalds 已提交
3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683
		/* Clip to the resolution we can set for the ROI
		   (every 8 columns and 4 rows) */
		vc->x      = vc->x      & ~(__u32)7;
		vc->y      = vc->y      & ~(__u32)3;
		vc->width  = vc->width  & ~(__u32)7;
		vc->height = vc->height & ~(__u32)3;

		if(vc->width == 0 || vc->height == 0 ||
		   vc->x + vc->width  > cam->vw.width ||
		   vc->y + vc->height > cam->vw.height) {
			retval = -EINVAL;
			break;
		}

		DBG("%d,%d/%dx%d\n", vc->x,vc->y,vc->width, vc->height);
3684

3685
		mutex_lock(&cam->param_lock);
3686

L
Linus Torvalds 已提交
3687 3688 3689 3690
		cam->vc.x      = vc->x;
		cam->vc.y      = vc->y;
		cam->vc.width  = vc->width;
		cam->vc.height = vc->height;
3691

L
Linus Torvalds 已提交
3692 3693 3694
		set_vw_size(cam);
		cam->cmd_queue |= COMMAND_SETFORMAT;

3695
		mutex_unlock(&cam->param_lock);
L
Linus Torvalds 已提交
3696 3697 3698 3699 3700 3701

		/* setformat ignored by camera during streaming,
		 * so stop/dispatch/start */
		dispatch_commands(cam);
		break;
	}
3702

L
Linus Torvalds 已提交
3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717
	case VIDIOCGUNIT:
	{
		struct video_unit *vu = arg;

		DBG("VIDIOCGUNIT\n");

		vu->video    = cam->vdev.minor;
		vu->vbi      = VIDEO_NO_UNIT;
		vu->radio    = VIDEO_NO_UNIT;
		vu->audio    = VIDEO_NO_UNIT;
		vu->teletext = VIDEO_NO_UNIT;

		break;
	}

3718

L
Linus Torvalds 已提交
3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738
	/* pointless to implement overlay with this camera */
	case VIDIOCCAPTURE:
	case VIDIOCGFBUF:
	case VIDIOCSFBUF:
	case VIDIOCKEY:
	/* tuner interface - we have none */
	case VIDIOCGTUNER:
	case VIDIOCSTUNER:
	case VIDIOCGFREQ:
	case VIDIOCSFREQ:
	/* audio interface - we have none */
	case VIDIOCGAUDIO:
	case VIDIOCSAUDIO:
		retval = -EINVAL;
		break;
	default:
		retval = -ENOIOCTLCMD;
		break;
	}

3739
	mutex_unlock(&cam->busy_lock);
L
Linus Torvalds 已提交
3740
	return retval;
3741
}
L
Linus Torvalds 已提交
3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761

static int cpia_ioctl(struct inode *inode, struct file *file,
		     unsigned int cmd, unsigned long arg)
{
	return video_usercopy(inode, file, cmd, arg, cpia_do_ioctl);
}


/* FIXME */
static int cpia_mmap(struct file *file, struct vm_area_struct *vma)
{
	struct video_device *dev = file->private_data;
	unsigned long start = vma->vm_start;
	unsigned long size  = vma->vm_end - vma->vm_start;
	unsigned long page, pos;
	struct cam_data *cam = dev->priv;
	int retval;

	if (!cam || !cam->ops)
		return -ENODEV;
3762

L
Linus Torvalds 已提交
3763 3764 3765 3766 3767 3768 3769
	DBG("cpia_mmap: %ld\n", size);

	if (size > FRAME_NUM*CPIA_MAX_FRAME_SIZE)
		return -EINVAL;

	if (!cam || !cam->ops)
		return -ENODEV;
3770

L
Linus Torvalds 已提交
3771
	/* make this _really_ smp-safe */
3772
	if (mutex_lock_interruptible(&cam->busy_lock))
L
Linus Torvalds 已提交
3773 3774 3775 3776
		return -EINTR;

	if (!cam->frame_buf) {	/* we do lazy allocation */
		if ((retval = allocate_frame_buf(cam))) {
3777
			mutex_unlock(&cam->busy_lock);
L
Linus Torvalds 已提交
3778 3779 3780 3781 3782 3783 3784 3785
			return retval;
		}
	}

	pos = (unsigned long)(cam->frame_buf);
	while (size > 0) {
		page = vmalloc_to_pfn((void *)pos);
		if (remap_pfn_range(vma, start, page, PAGE_SIZE, PAGE_SHARED)) {
3786
			mutex_unlock(&cam->busy_lock);
L
Linus Torvalds 已提交
3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797
			return -EAGAIN;
		}
		start += PAGE_SIZE;
		pos += PAGE_SIZE;
		if (size > PAGE_SIZE)
			size -= PAGE_SIZE;
		else
			size = 0;
	}

	DBG("cpia_mmap: %ld\n", size);
3798
	mutex_unlock(&cam->busy_lock);
L
Linus Torvalds 已提交
3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809

	return 0;
}

static struct file_operations cpia_fops = {
	.owner		= THIS_MODULE,
	.open		= cpia_open,
	.release       	= cpia_close,
	.read		= cpia_read,
	.mmap		= cpia_mmap,
	.ioctl          = cpia_ioctl,
3810
	.compat_ioctl	= v4l_compat_ioctl32,
L
Linus Torvalds 已提交
3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853
	.llseek         = no_llseek,
};

static struct video_device cpia_template = {
	.owner		= THIS_MODULE,
	.name		= "CPiA Camera",
	.type		= VID_TYPE_CAPTURE,
	.hardware	= VID_HARDWARE_CPIA,
	.fops           = &cpia_fops,
};

/* initialise cam_data structure  */
static void reset_camera_struct(struct cam_data *cam)
{
	/* The following parameter values are the defaults from
	 * "Software Developer's Guide for CPiA Cameras".  Any changes
	 * to the defaults are noted in comments. */
	cam->params.colourParams.brightness = 50;
	cam->params.colourParams.contrast = 48;
	cam->params.colourParams.saturation = 50;
	cam->params.exposure.gainMode = 4;
	cam->params.exposure.expMode = 2;		/* AEC */
	cam->params.exposure.compMode = 1;
	cam->params.exposure.centreWeight = 1;
	cam->params.exposure.gain = 0;
	cam->params.exposure.fineExp = 0;
	cam->params.exposure.coarseExpLo = 185;
	cam->params.exposure.coarseExpHi = 0;
	cam->params.exposure.redComp = COMP_RED;
	cam->params.exposure.green1Comp = COMP_GREEN1;
	cam->params.exposure.green2Comp = COMP_GREEN2;
	cam->params.exposure.blueComp = COMP_BLUE;
	cam->params.colourBalance.balanceMode = 2;	/* ACB */
	cam->params.colourBalance.redGain = 32;
	cam->params.colourBalance.greenGain = 6;
	cam->params.colourBalance.blueGain = 92;
	cam->params.apcor.gain1 = 0x18;
	cam->params.apcor.gain2 = 0x16;
	cam->params.apcor.gain4 = 0x24;
	cam->params.apcor.gain8 = 0x34;
	cam->params.flickerControl.flickerMode = 0;
	cam->params.flickerControl.disabled = 1;

3854
	cam->params.flickerControl.coarseJump =
L
Linus Torvalds 已提交
3855
		flicker_jumps[cam->mainsFreq]
3856 3857 3858
			     [cam->params.sensorFps.baserate]
			     [cam->params.sensorFps.divisor];
	cam->params.flickerControl.allowableOverExposure =
L
Linus Torvalds 已提交
3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872
		-find_over_exposure(cam->params.colourParams.brightness);
	cam->params.vlOffset.gain1 = 20;
	cam->params.vlOffset.gain2 = 24;
	cam->params.vlOffset.gain4 = 26;
	cam->params.vlOffset.gain8 = 26;
	cam->params.compressionParams.hysteresis = 3;
	cam->params.compressionParams.threshMax = 11;
	cam->params.compressionParams.smallStep = 1;
	cam->params.compressionParams.largeStep = 3;
	cam->params.compressionParams.decimationHysteresis = 2;
	cam->params.compressionParams.frDiffStepThresh = 5;
	cam->params.compressionParams.qDiffStepThresh = 3;
	cam->params.compressionParams.decimationThreshMod = 2;
	/* End of default values from Software Developer's Guide */
3873

L
Linus Torvalds 已提交
3874 3875
	cam->transfer_rate = 0;
	cam->exposure_status = EXPOSURE_NORMAL;
3876

L
Linus Torvalds 已提交
3877 3878 3879 3880
	/* Set Sensor FPS to 15fps. This seems better than 30fps
	 * for indoor lighting. */
	cam->params.sensorFps.divisor = 1;
	cam->params.sensorFps.baserate = 1;
3881

L
Linus Torvalds 已提交
3882 3883
	cam->params.yuvThreshold.yThreshold = 6; /* From windows driver */
	cam->params.yuvThreshold.uvThreshold = 6; /* From windows driver */
3884

L
Linus Torvalds 已提交
3885 3886
	cam->params.format.subSample = SUBSAMPLE_422;
	cam->params.format.yuvOrder = YUVORDER_YUYV;
3887

L
Linus Torvalds 已提交
3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900
	cam->params.compression.mode = CPIA_COMPRESSION_AUTO;
	cam->params.compressionTarget.frTargeting =
		CPIA_COMPRESSION_TARGET_QUALITY;
	cam->params.compressionTarget.targetFR = 15; /* From windows driver */
	cam->params.compressionTarget.targetQ = 5; /* From windows driver */

	cam->params.qx3.qx3_detected = 0;
	cam->params.qx3.toplight = 0;
	cam->params.qx3.bottomlight = 0;
	cam->params.qx3.button = 0;
	cam->params.qx3.cradled = 0;

	cam->video_size = VIDEOSIZE_CIF;
3901

L
Linus Torvalds 已提交
3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913
	cam->vp.colour = 32768;      /* 50% */
	cam->vp.hue = 32768;         /* 50% */
	cam->vp.brightness = 32768;  /* 50% */
	cam->vp.contrast = 32768;    /* 50% */
	cam->vp.whiteness = 0;       /* not used -> grayscale only */
	cam->vp.depth = 24;          /* to be set by user */
	cam->vp.palette = VIDEO_PALETTE_RGB24; /* to be set by user */

	cam->vc.x = 0;
	cam->vc.y = 0;
	cam->vc.width = 0;
	cam->vc.height = 0;
3914

L
Linus Torvalds 已提交
3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930
	cam->vw.x = 0;
	cam->vw.y = 0;
	set_vw_size(cam);
	cam->vw.chromakey = 0;
	cam->vw.flags = 0;
	cam->vw.clipcount = 0;
	cam->vw.clips = NULL;

	cam->cmd_queue = COMMAND_NONE;
	cam->first_frame = 1;

	return;
}

/* initialize cam_data structure  */
static void init_camera_struct(struct cam_data *cam,
3931
			       struct cpia_camera_ops *ops )
L
Linus Torvalds 已提交
3932 3933 3934 3935 3936 3937 3938
{
	int i;

	/* Default everything to 0 */
	memset(cam, 0, sizeof(struct cam_data));

	cam->ops = ops;
3939 3940
	mutex_init(&cam->param_lock);
	mutex_init(&cam->busy_lock);
L
Linus Torvalds 已提交
3941 3942 3943 3944 3945 3946 3947

	reset_camera_struct(cam);

	cam->proc_entry = NULL;

	memcpy(&cam->vdev, &cpia_template, sizeof(cpia_template));
	cam->vdev.priv = cam;
3948

L
Linus Torvalds 已提交
3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963
	cam->curframe = 0;
	for (i = 0; i < FRAME_NUM; i++) {
		cam->frame[i].width = 0;
		cam->frame[i].height = 0;
		cam->frame[i].state = FRAME_UNUSED;
		cam->frame[i].data = NULL;
	}
	cam->decompressed_frame.width = 0;
	cam->decompressed_frame.height = 0;
	cam->decompressed_frame.state = FRAME_UNUSED;
	cam->decompressed_frame.data = NULL;
}

struct cam_data *cpia_register_camera(struct cpia_camera_ops *ops, void *lowlevel)
{
3964 3965
	struct cam_data *camera;

L
Linus Torvalds 已提交
3966 3967 3968
	if ((camera = kmalloc(sizeof(struct cam_data), GFP_KERNEL)) == NULL)
		return NULL;

3969

L
Linus Torvalds 已提交
3970 3971
	init_camera_struct( camera, ops );
	camera->lowlevel_data = lowlevel;
3972

L
Linus Torvalds 已提交
3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984
	/* register v4l device */
	if (video_register_device(&camera->vdev, VFL_TYPE_GRABBER, video_nr) == -1) {
		kfree(camera);
		printk(KERN_DEBUG "video_register_device failed\n");
		return NULL;
	}

	/* get version information from camera: open/reset/close */

	/* open cpia */
	if (camera->ops->open(camera->lowlevel_data))
		return camera;
3985

L
Linus Torvalds 已提交
3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024
	/* reset the camera */
	if (reset_camera(camera) != 0) {
		camera->ops->close(camera->lowlevel_data);
		return camera;
	}

	/* close cpia */
	camera->ops->close(camera->lowlevel_data);

#ifdef CONFIG_PROC_FS
	create_proc_cpia_cam(camera);
#endif

	printk(KERN_INFO "  CPiA Version: %d.%02d (%d.%d)\n",
	       camera->params.version.firmwareVersion,
	       camera->params.version.firmwareRevision,
	       camera->params.version.vcVersion,
	       camera->params.version.vcRevision);
	printk(KERN_INFO "  CPiA PnP-ID: %04x:%04x:%04x\n",
	       camera->params.pnpID.vendor,
	       camera->params.pnpID.product,
	       camera->params.pnpID.deviceRevision);
	printk(KERN_INFO "  VP-Version: %d.%d %04x\n",
	       camera->params.vpVersion.vpVersion,
	       camera->params.vpVersion.vpRevision,
	       camera->params.vpVersion.cameraHeadID);

	return camera;
}

void cpia_unregister_camera(struct cam_data *cam)
{
	DBG("unregistering video\n");
	video_unregister_device(&cam->vdev);
	if (cam->open_count) {
		put_cam(cam->ops);
		DBG("camera open -- setting ops to NULL\n");
		cam->ops = NULL;
	}
4025

L
Linus Torvalds 已提交
4026 4027 4028
#ifdef CONFIG_PROC_FS
	DBG("destroying /proc/cpia/video%d\n", cam->vdev.minor);
	destroy_proc_cpia_cam(cam);
4029
#endif
L
Linus Torvalds 已提交
4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074
	if (!cam->open_count) {
		DBG("freeing camera\n");
		kfree(cam);
	}
}

static int __init cpia_init(void)
{
	printk(KERN_INFO "%s v%d.%d.%d\n", ABOUT,
	       CPIA_MAJ_VER, CPIA_MIN_VER, CPIA_PATCH_VER);

	printk(KERN_WARNING "Since in-kernel colorspace conversion is not "
	       "allowed, it is disabled by default now. Users should fix the "
	       "applications in case they don't work without conversion "
	       "reenabled by setting the 'colorspace_conv' module "
	       "parameter to 1");

#ifdef CONFIG_PROC_FS
	proc_cpia_create();
#endif

#ifdef CONFIG_VIDEO_CPIA_PP
	cpia_pp_init();
#endif
#ifdef CONFIG_VIDEO_CPIA_USB
	cpia_usb_init();
#endif

	return 0;
}

static void __exit cpia_exit(void)
{
#ifdef CONFIG_PROC_FS
	proc_cpia_destroy();
#endif
}

module_init(cpia_init);
module_exit(cpia_exit);

/* Exported symbols for modules. */

EXPORT_SYMBOL(cpia_register_camera);
EXPORT_SYMBOL(cpia_unregister_camera);