pvrusb2-hdw.c 139.2 KB
Newer Older
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
/*
 *
 *
 *  Copyright (C) 2005 Mike Isely <isely@pobox.com>
 *
 *  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
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

#include <linux/errno.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/firmware.h>
#include <linux/videodev2.h>
26
#include <media/v4l2-common.h>
27
#include <media/tuner.h>
28 29 30 31 32
#include "pvrusb2.h"
#include "pvrusb2-std.h"
#include "pvrusb2-util.h"
#include "pvrusb2-hdw.h"
#include "pvrusb2-i2c-core.h"
33
#include "pvrusb2-i2c-track.h"
34 35 36 37 38
#include "pvrusb2-tuner.h"
#include "pvrusb2-eeprom.h"
#include "pvrusb2-hdw-internal.h"
#include "pvrusb2-encoder.h"
#include "pvrusb2-debug.h"
39
#include "pvrusb2-fx2-cmd.h"
40
#include "pvrusb2-wm8775.h"
41
#include "pvrusb2-video-v4l.h"
42
#include "pvrusb2-cx2584x-v4l.h"
43
#include "pvrusb2-audio.h"
44

45 46
#define TV_MIN_FREQ     55250000L
#define TV_MAX_FREQ    850000000L
47

48 49 50 51 52
/* This defines a minimum interval that the decoder must remain quiet
   before we are allowed to start it running. */
#define TIME_MSEC_DECODER_WAIT 50

/* This defines a minimum interval that the encoder must remain quiet
53 54 55 56
   before we are allowed to configure it.  I had this originally set to
   50msec, but Martin Dauskardt <martin.dauskardt@gmx.de> reports that
   things work better when it's set to 100msec. */
#define TIME_MSEC_ENCODER_WAIT 100
57 58 59 60 61 62 63 64

/* This defines the minimum interval that the encoder must successfully run
   before we consider that the encoder has run at least once since its
   firmware has been loaded.  This measurement is in important for cases
   where we can't do something until we know that the encoder has been run
   at least once. */
#define TIME_MSEC_ENCODER_OK 250

65
static struct pvr2_hdw *unit_pointers[PVR_NUM] = {[ 0 ... PVR_NUM-1 ] = NULL};
66
static DEFINE_MUTEX(pvr2_unit_mtx);
67

68 69
static int ctlchg;
static int procreload;
70 71 72
static int tuner[PVR_NUM] = { [0 ... PVR_NUM-1] = -1 };
static int tolerance[PVR_NUM] = { [0 ... PVR_NUM-1] = 0 };
static int video_std[PVR_NUM] = { [0 ... PVR_NUM-1] = 0 };
73
static int init_pause_msec;
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88

module_param(ctlchg, int, S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(ctlchg, "0=optimize ctl change 1=always accept new ctl value");
module_param(init_pause_msec, int, S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(init_pause_msec, "hardware initialization settling delay");
module_param(procreload, int, S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(procreload,
		 "Attempt init failure recovery with firmware reload");
module_param_array(tuner,    int, NULL, 0444);
MODULE_PARM_DESC(tuner,"specify installed tuner type");
module_param_array(video_std,    int, NULL, 0444);
MODULE_PARM_DESC(video_std,"specify initial video standard");
module_param_array(tolerance,    int, NULL, 0444);
MODULE_PARM_DESC(tolerance,"specify stream error tolerance");

89 90 91 92 93 94 95 96 97 98
/* US Broadcast channel 7 (175.25 MHz) */
static int default_tv_freq    = 175250000L;
/* 104.3 MHz, a usable FM station for my area */
static int default_radio_freq = 104300000L;

module_param_named(tv_freq, default_tv_freq, int, 0444);
MODULE_PARM_DESC(tv_freq, "specify initial television frequency");
module_param_named(radio_freq, default_radio_freq, int, 0444);
MODULE_PARM_DESC(radio_freq, "specify initial radio frequency");

99 100 101 102 103 104 105 106 107 108 109 110 111 112
#define PVR2_CTL_WRITE_ENDPOINT  0x01
#define PVR2_CTL_READ_ENDPOINT   0x81

#define PVR2_GPIO_IN 0x9008
#define PVR2_GPIO_OUT 0x900c
#define PVR2_GPIO_DIR 0x9020

#define trace_firmware(...) pvr2_trace(PVR2_TRACE_FIRMWARE,__VA_ARGS__)

#define PVR2_FIRMWARE_ENDPOINT   0x02

/* size of a firmware chunk */
#define FIRMWARE_CHUNK_SIZE 0x2000

113 114 115 116
typedef void (*pvr2_subdev_update_func)(struct pvr2_hdw *,
					struct v4l2_subdev *);

static const pvr2_subdev_update_func pvr2_module_update_functions[] = {
117
	[PVR2_CLIENT_ID_WM8775] = pvr2_wm8775_subdev_update,
118
	[PVR2_CLIENT_ID_SAA7115] = pvr2_saa7115_subdev_update,
119
	[PVR2_CLIENT_ID_MSP3400] = pvr2_msp3400_subdev_update,
120
	[PVR2_CLIENT_ID_CX25840] = pvr2_cx25840_subdev_update,
121 122
};

123 124 125 126 127
static const char *module_names[] = {
	[PVR2_CLIENT_ID_MSP3400] = "msp3400",
	[PVR2_CLIENT_ID_CX25840] = "cx25840",
	[PVR2_CLIENT_ID_SAA7115] = "saa7115",
	[PVR2_CLIENT_ID_TUNER] = "tuner",
128
	[PVR2_CLIENT_ID_CS53L32A] = "cs53l32a",
129
	[PVR2_CLIENT_ID_WM8775] = "wm8775",
130 131 132 133 134
};


static const unsigned char *module_i2c_addresses[] = {
	[PVR2_CLIENT_ID_TUNER] = "\x60\x61\x62\x63",
135 136
	[PVR2_CLIENT_ID_MSP3400] = "\x40",
	[PVR2_CLIENT_ID_SAA7115] = "\x21",
137
	[PVR2_CLIENT_ID_WM8775] = "\x1b",
138
	[PVR2_CLIENT_ID_CX25840] = "\x44",
139
	[PVR2_CLIENT_ID_CS53L32A] = "\x11",
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 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
/* Define the list of additional controls we'll dynamically construct based
   on query of the cx2341x module. */
struct pvr2_mpeg_ids {
	const char *strid;
	int id;
};
static const struct pvr2_mpeg_ids mpeg_ids[] = {
	{
		.strid = "audio_layer",
		.id = V4L2_CID_MPEG_AUDIO_ENCODING,
	},{
		.strid = "audio_bitrate",
		.id = V4L2_CID_MPEG_AUDIO_L2_BITRATE,
	},{
		/* Already using audio_mode elsewhere :-( */
		.strid = "mpeg_audio_mode",
		.id = V4L2_CID_MPEG_AUDIO_MODE,
	},{
		.strid = "mpeg_audio_mode_extension",
		.id = V4L2_CID_MPEG_AUDIO_MODE_EXTENSION,
	},{
		.strid = "audio_emphasis",
		.id = V4L2_CID_MPEG_AUDIO_EMPHASIS,
	},{
		.strid = "audio_crc",
		.id = V4L2_CID_MPEG_AUDIO_CRC,
	},{
		.strid = "video_aspect",
		.id = V4L2_CID_MPEG_VIDEO_ASPECT,
	},{
		.strid = "video_b_frames",
		.id = V4L2_CID_MPEG_VIDEO_B_FRAMES,
	},{
		.strid = "video_gop_size",
		.id = V4L2_CID_MPEG_VIDEO_GOP_SIZE,
	},{
		.strid = "video_gop_closure",
		.id = V4L2_CID_MPEG_VIDEO_GOP_CLOSURE,
	},{
		.strid = "video_bitrate_mode",
		.id = V4L2_CID_MPEG_VIDEO_BITRATE_MODE,
	},{
		.strid = "video_bitrate",
		.id = V4L2_CID_MPEG_VIDEO_BITRATE,
	},{
		.strid = "video_bitrate_peak",
		.id = V4L2_CID_MPEG_VIDEO_BITRATE_PEAK,
	},{
		.strid = "video_temporal_decimation",
		.id = V4L2_CID_MPEG_VIDEO_TEMPORAL_DECIMATION,
	},{
		.strid = "stream_type",
		.id = V4L2_CID_MPEG_STREAM_TYPE,
	},{
		.strid = "video_spatial_filter_mode",
		.id = V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE,
	},{
		.strid = "video_spatial_filter",
		.id = V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER,
	},{
		.strid = "video_luma_spatial_filter_type",
		.id = V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE,
	},{
		.strid = "video_chroma_spatial_filter_type",
		.id = V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE,
	},{
		.strid = "video_temporal_filter_mode",
		.id = V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE,
	},{
		.strid = "video_temporal_filter",
		.id = V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER,
	},{
		.strid = "video_median_filter_type",
		.id = V4L2_CID_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE,
	},{
		.strid = "video_luma_median_filter_top",
		.id = V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_TOP,
	},{
		.strid = "video_luma_median_filter_bottom",
		.id = V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_BOTTOM,
	},{
		.strid = "video_chroma_median_filter_top",
		.id = V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_TOP,
	},{
		.strid = "video_chroma_median_filter_bottom",
		.id = V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_BOTTOM,
	}
};
231
#define MPEGDEF_COUNT ARRAY_SIZE(mpeg_ids)
232

233

234
static const char *control_values_srate[] = {
235 236 237
	[V4L2_MPEG_AUDIO_SAMPLING_FREQ_44100]   = "44.1 kHz",
	[V4L2_MPEG_AUDIO_SAMPLING_FREQ_48000]   = "48 kHz",
	[V4L2_MPEG_AUDIO_SAMPLING_FREQ_32000]   = "32 kHz",
238 239 240 241 242 243
};



static const char *control_values_input[] = {
	[PVR2_CVAL_INPUT_TV]        = "television",  /*xawtv needs this name*/
244
	[PVR2_CVAL_INPUT_DTV]       = "dtv",
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
	[PVR2_CVAL_INPUT_RADIO]     = "radio",
	[PVR2_CVAL_INPUT_SVIDEO]    = "s-video",
	[PVR2_CVAL_INPUT_COMPOSITE] = "composite",
};


static const char *control_values_audiomode[] = {
	[V4L2_TUNER_MODE_MONO]   = "Mono",
	[V4L2_TUNER_MODE_STEREO] = "Stereo",
	[V4L2_TUNER_MODE_LANG1]  = "Lang1",
	[V4L2_TUNER_MODE_LANG2]  = "Lang2",
	[V4L2_TUNER_MODE_LANG1_LANG2] = "Lang1+Lang2",
};


static const char *control_values_hsm[] = {
	[PVR2_CVAL_HSM_FAIL] = "Fail",
	[PVR2_CVAL_HSM_HIGH] = "High",
	[PVR2_CVAL_HSM_FULL] = "Full",
};


267 268 269 270 271 272 273 274
static const char *pvr2_state_names[] = {
	[PVR2_STATE_NONE] =    "none",
	[PVR2_STATE_DEAD] =    "dead",
	[PVR2_STATE_COLD] =    "cold",
	[PVR2_STATE_WARM] =    "warm",
	[PVR2_STATE_ERROR] =   "error",
	[PVR2_STATE_READY] =   "ready",
	[PVR2_STATE_RUN] =     "run",
275 276
};

277

278
struct pvr2_fx2cmd_descdef {
279 280 281 282
	unsigned char id;
	unsigned char *desc;
};

283
static const struct pvr2_fx2cmd_descdef pvr2_fx2cmd_desc[] = {
284 285
	{FX2CMD_MEM_WRITE_DWORD, "write encoder dword"},
	{FX2CMD_MEM_READ_DWORD, "read encoder dword"},
286
	{FX2CMD_HCW_ZILOG_RESET, "zilog IR reset control"},
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
	{FX2CMD_MEM_READ_64BYTES, "read encoder 64bytes"},
	{FX2CMD_REG_WRITE, "write encoder register"},
	{FX2CMD_REG_READ, "read encoder register"},
	{FX2CMD_MEMSEL, "encoder memsel"},
	{FX2CMD_I2C_WRITE, "i2c write"},
	{FX2CMD_I2C_READ, "i2c read"},
	{FX2CMD_GET_USB_SPEED, "get USB speed"},
	{FX2CMD_STREAMING_ON, "stream on"},
	{FX2CMD_STREAMING_OFF, "stream off"},
	{FX2CMD_FWPOST1, "fwpost1"},
	{FX2CMD_POWER_OFF, "power off"},
	{FX2CMD_POWER_ON, "power on"},
	{FX2CMD_DEEP_RESET, "deep reset"},
	{FX2CMD_GET_EEPROM_ADDR, "get rom addr"},
	{FX2CMD_GET_IR_CODE, "get IR code"},
	{FX2CMD_HCW_DEMOD_RESETIN, "hcw demod resetin"},
	{FX2CMD_HCW_DTV_STREAMING_ON, "hcw dtv stream on"},
	{FX2CMD_HCW_DTV_STREAMING_OFF, "hcw dtv stream off"},
	{FX2CMD_ONAIR_DTV_STREAMING_ON, "onair dtv stream on"},
	{FX2CMD_ONAIR_DTV_STREAMING_OFF, "onair dtv stream off"},
	{FX2CMD_ONAIR_DTV_POWER_ON, "onair dtv power on"},
	{FX2CMD_ONAIR_DTV_POWER_OFF, "onair dtv power off"},
};


312
static int pvr2_hdw_set_input(struct pvr2_hdw *hdw,int v);
313 314
static void pvr2_hdw_state_sched(struct pvr2_hdw *);
static int pvr2_hdw_state_eval(struct pvr2_hdw *);
315
static void pvr2_hdw_set_cur_freq(struct pvr2_hdw *,unsigned long);
316 317 318 319 320
static void pvr2_hdw_worker_i2c(struct work_struct *work);
static void pvr2_hdw_worker_poll(struct work_struct *work);
static int pvr2_hdw_wait(struct pvr2_hdw *,int state);
static int pvr2_hdw_untrip_unlocked(struct pvr2_hdw *);
static void pvr2_hdw_state_log_state(struct pvr2_hdw *);
321
static int pvr2_hdw_cmd_usbstream(struct pvr2_hdw *hdw,int runFl);
322
static int pvr2_hdw_commit_setup(struct pvr2_hdw *hdw);
323 324 325
static int pvr2_hdw_get_eeprom_addr(struct pvr2_hdw *hdw);
static void pvr2_hdw_internal_find_stdenum(struct pvr2_hdw *hdw);
static void pvr2_hdw_internal_set_std_avail(struct pvr2_hdw *hdw);
326 327
static void pvr2_hdw_quiescent_timeout(unsigned long);
static void pvr2_hdw_encoder_wait_timeout(unsigned long);
328
static void pvr2_hdw_encoder_run_timeout(unsigned long);
329
static int pvr2_issue_simple_cmd(struct pvr2_hdw *,u32);
330 331 332 333
static int pvr2_send_request_ex(struct pvr2_hdw *hdw,
				unsigned int timeout,int probe_fl,
				void *write_data,unsigned int write_len,
				void *read_data,unsigned int read_len);
334
static int pvr2_hdw_check_cropcap(struct pvr2_hdw *hdw);
335

336 337 338 339 340 341 342 343

static void trace_stbit(const char *name,int val)
{
	pvr2_trace(PVR2_TRACE_STBITS,
		   "State bit %s <-- %s",
		   name,(val ? "true" : "false"));
}

344 345 346 347 348 349 350 351 352 353 354 355 356 357
static int ctrl_channelfreq_get(struct pvr2_ctrl *cptr,int *vp)
{
	struct pvr2_hdw *hdw = cptr->hdw;
	if ((hdw->freqProgSlot > 0) && (hdw->freqProgSlot <= FREQTABLE_SIZE)) {
		*vp = hdw->freqTable[hdw->freqProgSlot-1];
	} else {
		*vp = 0;
	}
	return 0;
}

static int ctrl_channelfreq_set(struct pvr2_ctrl *cptr,int m,int v)
{
	struct pvr2_hdw *hdw = cptr->hdw;
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
	unsigned int slotId = hdw->freqProgSlot;
	if ((slotId > 0) && (slotId <= FREQTABLE_SIZE)) {
		hdw->freqTable[slotId-1] = v;
		/* Handle side effects correctly - if we're tuned to this
		   slot, then forgot the slot id relation since the stored
		   frequency has been changed. */
		if (hdw->freqSelector) {
			if (hdw->freqSlotRadio == slotId) {
				hdw->freqSlotRadio = 0;
			}
		} else {
			if (hdw->freqSlotTelevision == slotId) {
				hdw->freqSlotTelevision = 0;
			}
		}
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
	}
	return 0;
}

static int ctrl_channelprog_get(struct pvr2_ctrl *cptr,int *vp)
{
	*vp = cptr->hdw->freqProgSlot;
	return 0;
}

static int ctrl_channelprog_set(struct pvr2_ctrl *cptr,int m,int v)
{
	struct pvr2_hdw *hdw = cptr->hdw;
	if ((v >= 0) && (v <= FREQTABLE_SIZE)) {
		hdw->freqProgSlot = v;
	}
	return 0;
}

static int ctrl_channel_get(struct pvr2_ctrl *cptr,int *vp)
{
394 395
	struct pvr2_hdw *hdw = cptr->hdw;
	*vp = hdw->freqSelector ? hdw->freqSlotRadio : hdw->freqSlotTelevision;
396 397 398
	return 0;
}

399
static int ctrl_channel_set(struct pvr2_ctrl *cptr,int m,int slotId)
400 401 402
{
	unsigned freq = 0;
	struct pvr2_hdw *hdw = cptr->hdw;
403 404 405 406 407
	if ((slotId < 0) || (slotId > FREQTABLE_SIZE)) return 0;
	if (slotId > 0) {
		freq = hdw->freqTable[slotId-1];
		if (!freq) return 0;
		pvr2_hdw_set_cur_freq(hdw,freq);
408
	}
409 410 411 412
	if (hdw->freqSelector) {
		hdw->freqSlotRadio = slotId;
	} else {
		hdw->freqSlotTelevision = slotId;
413 414 415 416 417 418
	}
	return 0;
}

static int ctrl_freq_get(struct pvr2_ctrl *cptr,int *vp)
{
419
	*vp = pvr2_hdw_get_cur_freq(cptr->hdw);
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
	return 0;
}

static int ctrl_freq_is_dirty(struct pvr2_ctrl *cptr)
{
	return cptr->hdw->freqDirty != 0;
}

static void ctrl_freq_clear_dirty(struct pvr2_ctrl *cptr)
{
	cptr->hdw->freqDirty = 0;
}

static int ctrl_freq_set(struct pvr2_ctrl *cptr,int m,int v)
{
435
	pvr2_hdw_set_cur_freq(cptr->hdw,v);
436 437 438
	return 0;
}

439 440
static int ctrl_cropl_min_get(struct pvr2_ctrl *cptr, int *left)
{
441 442 443 444
	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
	if (stat != 0) {
		return stat;
445
	}
446
	*left = cap->bounds.left;
447 448 449 450 451
	return 0;
}

static int ctrl_cropl_max_get(struct pvr2_ctrl *cptr, int *left)
{
452 453 454 455 456 457 458 459
	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
	if (stat != 0) {
		return stat;
	}
	*left = cap->bounds.left;
	if (cap->bounds.width > cptr->hdw->cropw_val) {
		*left += cap->bounds.width - cptr->hdw->cropw_val;
460 461 462 463 464 465
	}
	return 0;
}

static int ctrl_cropt_min_get(struct pvr2_ctrl *cptr, int *top)
{
466 467 468 469
	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
	if (stat != 0) {
		return stat;
470
	}
471
	*top = cap->bounds.top;
472 473 474
	return 0;
}

475
static int ctrl_cropt_max_get(struct pvr2_ctrl *cptr, int *top)
476
{
477 478 479 480 481 482 483 484
	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
	if (stat != 0) {
		return stat;
	}
	*top = cap->bounds.top;
	if (cap->bounds.height > cptr->hdw->croph_val) {
		*top += cap->bounds.height - cptr->hdw->croph_val;
485 486 487 488
	}
	return 0;
}

489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 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 586 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 622 623 624 625 626 627
static int ctrl_cropw_max_get(struct pvr2_ctrl *cptr, int *val)
{
	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
	if (stat != 0) {
		return stat;
	}
	*val = 0;
	if (cap->bounds.width > cptr->hdw->cropl_val) {
		*val = cap->bounds.width - cptr->hdw->cropl_val;
	}
	return 0;
}

static int ctrl_croph_max_get(struct pvr2_ctrl *cptr, int *val)
{
	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
	if (stat != 0) {
		return stat;
	}
	*val = 0;
	if (cap->bounds.height > cptr->hdw->cropt_val) {
		*val = cap->bounds.height - cptr->hdw->cropt_val;
	}
	return 0;
}

static int ctrl_get_cropcapbl(struct pvr2_ctrl *cptr, int *val)
{
	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
	if (stat != 0) {
		return stat;
	}
	*val = cap->bounds.left;
	return 0;
}

static int ctrl_get_cropcapbt(struct pvr2_ctrl *cptr, int *val)
{
	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
	if (stat != 0) {
		return stat;
	}
	*val = cap->bounds.top;
	return 0;
}

static int ctrl_get_cropcapbw(struct pvr2_ctrl *cptr, int *val)
{
	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
	if (stat != 0) {
		return stat;
	}
	*val = cap->bounds.width;
	return 0;
}

static int ctrl_get_cropcapbh(struct pvr2_ctrl *cptr, int *val)
{
	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
	if (stat != 0) {
		return stat;
	}
	*val = cap->bounds.height;
	return 0;
}

static int ctrl_get_cropcapdl(struct pvr2_ctrl *cptr, int *val)
{
	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
	if (stat != 0) {
		return stat;
	}
	*val = cap->defrect.left;
	return 0;
}

static int ctrl_get_cropcapdt(struct pvr2_ctrl *cptr, int *val)
{
	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
	if (stat != 0) {
		return stat;
	}
	*val = cap->defrect.top;
	return 0;
}

static int ctrl_get_cropcapdw(struct pvr2_ctrl *cptr, int *val)
{
	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
	if (stat != 0) {
		return stat;
	}
	*val = cap->defrect.width;
	return 0;
}

static int ctrl_get_cropcapdh(struct pvr2_ctrl *cptr, int *val)
{
	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
	if (stat != 0) {
		return stat;
	}
	*val = cap->defrect.height;
	return 0;
}

static int ctrl_get_cropcappan(struct pvr2_ctrl *cptr, int *val)
{
	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
	if (stat != 0) {
		return stat;
	}
	*val = cap->pixelaspect.numerator;
	return 0;
}

static int ctrl_get_cropcappad(struct pvr2_ctrl *cptr, int *val)
{
	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
	if (stat != 0) {
		return stat;
	}
	*val = cap->pixelaspect.denominator;
	return 0;
}

static int ctrl_vres_max_get(struct pvr2_ctrl *cptr,int *vp)
628
{
629 630 631
	/* Actual maximum depends on the video standard in effect. */
	if (cptr->hdw->std_mask_cur & V4L2_STD_525_60) {
		*vp = 480;
632
	} else {
633
		*vp = 576;
634 635 636 637
	}
	return 0;
}

638 639
static int ctrl_vres_min_get(struct pvr2_ctrl *cptr,int *vp)
{
640 641
	/* Actual minimum depends on device digitizer type. */
	if (cptr->hdw->hdw_desc->flag_has_cx25840) {
642 643 644 645 646 647 648
		*vp = 75;
	} else {
		*vp = 17;
	}
	return 0;
}

649
static int ctrl_get_input(struct pvr2_ctrl *cptr,int *vp)
650
{
651 652 653 654
	*vp = cptr->hdw->input_val;
	return 0;
}

655 656
static int ctrl_check_input(struct pvr2_ctrl *cptr,int v)
{
657
	return ((1 << v) & cptr->hdw->input_allowed_mask) != 0;
658 659
}

660 661
static int ctrl_set_input(struct pvr2_ctrl *cptr,int m,int v)
{
662
	return pvr2_hdw_set_input(cptr->hdw,v);
663 664 665 666 667 668 669 670 671 672 673 674
}

static int ctrl_isdirty_input(struct pvr2_ctrl *cptr)
{
	return cptr->hdw->input_dirty != 0;
}

static void ctrl_cleardirty_input(struct pvr2_ctrl *cptr)
{
	cptr->hdw->input_dirty = 0;
}

675

676 677
static int ctrl_freq_max_get(struct pvr2_ctrl *cptr, int *vp)
{
678 679 680
	unsigned long fv;
	struct pvr2_hdw *hdw = cptr->hdw;
	if (hdw->tuner_signal_stale) {
681
		pvr2_hdw_status_poll(hdw);
682 683 684 685
	}
	fv = hdw->tuner_signal_info.rangehigh;
	if (!fv) {
		/* Safety fallback */
686
		*vp = TV_MAX_FREQ;
687
		return 0;
688
	}
689 690 691 692 693 694
	if (hdw->tuner_signal_info.capability & V4L2_TUNER_CAP_LOW) {
		fv = (fv * 125) / 2;
	} else {
		fv = fv * 62500;
	}
	*vp = fv;
695 696 697 698 699
	return 0;
}

static int ctrl_freq_min_get(struct pvr2_ctrl *cptr, int *vp)
{
700 701 702
	unsigned long fv;
	struct pvr2_hdw *hdw = cptr->hdw;
	if (hdw->tuner_signal_stale) {
703
		pvr2_hdw_status_poll(hdw);
704 705 706 707
	}
	fv = hdw->tuner_signal_info.rangelow;
	if (!fv) {
		/* Safety fallback */
708
		*vp = TV_MIN_FREQ;
709 710 711 712 713 714
		return 0;
	}
	if (hdw->tuner_signal_info.capability & V4L2_TUNER_CAP_LOW) {
		fv = (fv * 125) / 2;
	} else {
		fv = fv * 62500;
715
	}
716
	*vp = fv;
717 718 719
	return 0;
}

720 721 722 723 724 725 726 727
static int ctrl_cx2341x_is_dirty(struct pvr2_ctrl *cptr)
{
	return cptr->hdw->enc_stale != 0;
}

static void ctrl_cx2341x_clear_dirty(struct pvr2_ctrl *cptr)
{
	cptr->hdw->enc_stale = 0;
728
	cptr->hdw->enc_unsafe_stale = 0;
729 730 731 732 733 734 735 736 737 738 739 740
}

static int ctrl_cx2341x_get(struct pvr2_ctrl *cptr,int *vp)
{
	int ret;
	struct v4l2_ext_controls cs;
	struct v4l2_ext_control c1;
	memset(&cs,0,sizeof(cs));
	memset(&c1,0,sizeof(c1));
	cs.controls = &c1;
	cs.count = 1;
	c1.id = cptr->info->v4l_id;
741
	ret = cx2341x_ext_ctrls(&cptr->hdw->enc_ctl_state, 0, &cs,
742 743 744 745 746 747 748 749 750
				VIDIOC_G_EXT_CTRLS);
	if (ret) return ret;
	*vp = c1.value;
	return 0;
}

static int ctrl_cx2341x_set(struct pvr2_ctrl *cptr,int m,int v)
{
	int ret;
751
	struct pvr2_hdw *hdw = cptr->hdw;
752 753 754 755 756 757 758 759
	struct v4l2_ext_controls cs;
	struct v4l2_ext_control c1;
	memset(&cs,0,sizeof(cs));
	memset(&c1,0,sizeof(c1));
	cs.controls = &c1;
	cs.count = 1;
	c1.id = cptr->info->v4l_id;
	c1.value = v;
760 761
	ret = cx2341x_ext_ctrls(&hdw->enc_ctl_state,
				hdw->state_encoder_run, &cs,
762
				VIDIOC_S_EXT_CTRLS);
763 764 765 766 767 768 769 770 771 772 773
	if (ret == -EBUSY) {
		/* Oops.  cx2341x is telling us it's not safe to change
		   this control while we're capturing.  Make a note of this
		   fact so that the pipeline will be stopped the next time
		   controls are committed.  Then go on ahead and store this
		   change anyway. */
		ret = cx2341x_ext_ctrls(&hdw->enc_ctl_state,
					0, &cs,
					VIDIOC_S_EXT_CTRLS);
		if (!ret) hdw->enc_unsafe_stale = !0;
	}
774
	if (ret) return ret;
775
	hdw->enc_stale = !0;
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
	return 0;
}

static unsigned int ctrl_cx2341x_getv4lflags(struct pvr2_ctrl *cptr)
{
	struct v4l2_queryctrl qctrl;
	struct pvr2_ctl_info *info;
	qctrl.id = cptr->info->v4l_id;
	cx2341x_ctrl_query(&cptr->hdw->enc_ctl_state,&qctrl);
	/* Strip out the const so we can adjust a function pointer.  It's
	   OK to do this here because we know this is a dynamically created
	   control, so the underlying storage for the info pointer is (a)
	   private to us, and (b) not in read-only storage.  Either we do
	   this or we significantly complicate the underlying control
	   implementation. */
	info = (struct pvr2_ctl_info *)(cptr->info);
	if (qctrl.flags & V4L2_CTRL_FLAG_READ_ONLY) {
		if (info->set_value) {
794
			info->set_value = NULL;
795 796 797 798 799 800 801 802 803
		}
	} else {
		if (!(info->set_value)) {
			info->set_value = ctrl_cx2341x_set;
		}
	}
	return qctrl.flags;
}

804 805
static int ctrl_streamingenabled_get(struct pvr2_ctrl *cptr,int *vp)
{
806 807 808 809 810 811 812
	*vp = cptr->hdw->state_pipeline_req;
	return 0;
}

static int ctrl_masterstate_get(struct pvr2_ctrl *cptr,int *vp)
{
	*vp = cptr->hdw->master_state;
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
	return 0;
}

static int ctrl_hsm_get(struct pvr2_ctrl *cptr,int *vp)
{
	int result = pvr2_hdw_is_hsm(cptr->hdw);
	*vp = PVR2_CVAL_HSM_FULL;
	if (result < 0) *vp = PVR2_CVAL_HSM_FAIL;
	if (result) *vp = PVR2_CVAL_HSM_HIGH;
	return 0;
}

static int ctrl_stdavail_get(struct pvr2_ctrl *cptr,int *vp)
{
	*vp = cptr->hdw->std_mask_avail;
	return 0;
}

static int ctrl_stdavail_set(struct pvr2_ctrl *cptr,int m,int v)
{
	struct pvr2_hdw *hdw = cptr->hdw;
	v4l2_std_id ns;
	ns = hdw->std_mask_avail;
	ns = (ns & ~m) | (v & m);
	if (ns == hdw->std_mask_avail) return 0;
	hdw->std_mask_avail = ns;
	pvr2_hdw_internal_set_std_avail(hdw);
	pvr2_hdw_internal_find_stdenum(hdw);
	return 0;
}

static int ctrl_std_val_to_sym(struct pvr2_ctrl *cptr,int msk,int val,
			       char *bufPtr,unsigned int bufSize,
			       unsigned int *len)
{
	*len = pvr2_std_id_to_str(bufPtr,bufSize,msk & val);
	return 0;
}

static int ctrl_std_sym_to_val(struct pvr2_ctrl *cptr,
			       const char *bufPtr,unsigned int bufSize,
			       int *mskp,int *valp)
{
	int ret;
	v4l2_std_id id;
	ret = pvr2_std_str_to_id(&id,bufPtr,bufSize);
	if (ret < 0) return ret;
	if (mskp) *mskp = id;
	if (valp) *valp = id;
	return 0;
}

static int ctrl_stdcur_get(struct pvr2_ctrl *cptr,int *vp)
{
	*vp = cptr->hdw->std_mask_cur;
	return 0;
}

static int ctrl_stdcur_set(struct pvr2_ctrl *cptr,int m,int v)
{
	struct pvr2_hdw *hdw = cptr->hdw;
	v4l2_std_id ns;
	ns = hdw->std_mask_cur;
	ns = (ns & ~m) | (v & m);
	if (ns == hdw->std_mask_cur) return 0;
	hdw->std_mask_cur = ns;
	hdw->std_dirty = !0;
	pvr2_hdw_internal_find_stdenum(hdw);
	return 0;
}

static int ctrl_stdcur_is_dirty(struct pvr2_ctrl *cptr)
{
	return cptr->hdw->std_dirty != 0;
}

static void ctrl_stdcur_clear_dirty(struct pvr2_ctrl *cptr)
{
	cptr->hdw->std_dirty = 0;
}

static int ctrl_signal_get(struct pvr2_ctrl *cptr,int *vp)
{
896
	struct pvr2_hdw *hdw = cptr->hdw;
897
	pvr2_hdw_status_poll(hdw);
898 899 900 901 902 903 904 905 906
	*vp = hdw->tuner_signal_info.signal;
	return 0;
}

static int ctrl_audio_modes_present_get(struct pvr2_ctrl *cptr,int *vp)
{
	int val = 0;
	unsigned int subchan;
	struct pvr2_hdw *hdw = cptr->hdw;
907
	pvr2_hdw_status_poll(hdw);
908 909 910 911 912 913 914 915 916 917 918 919 920 921
	subchan = hdw->tuner_signal_info.rxsubchans;
	if (subchan & V4L2_TUNER_SUB_MONO) {
		val |= (1 << V4L2_TUNER_MODE_MONO);
	}
	if (subchan & V4L2_TUNER_SUB_STEREO) {
		val |= (1 << V4L2_TUNER_MODE_STEREO);
	}
	if (subchan & V4L2_TUNER_SUB_LANG1) {
		val |= (1 << V4L2_TUNER_MODE_LANG1);
	}
	if (subchan & V4L2_TUNER_SUB_LANG2) {
		val |= (1 << V4L2_TUNER_MODE_LANG2);
	}
	*vp = val;
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
	return 0;
}


static int ctrl_stdenumcur_set(struct pvr2_ctrl *cptr,int m,int v)
{
	struct pvr2_hdw *hdw = cptr->hdw;
	if (v < 0) return -EINVAL;
	if (v > hdw->std_enum_cnt) return -EINVAL;
	hdw->std_enum_cur = v;
	if (!v) return 0;
	v--;
	if (hdw->std_mask_cur == hdw->std_defs[v].id) return 0;
	hdw->std_mask_cur = hdw->std_defs[v].id;
	hdw->std_dirty = !0;
	return 0;
}


static int ctrl_stdenumcur_get(struct pvr2_ctrl *cptr,int *vp)
{
	*vp = cptr->hdw->std_enum_cur;
	return 0;
}


static int ctrl_stdenumcur_is_dirty(struct pvr2_ctrl *cptr)
{
	return cptr->hdw->std_dirty != 0;
}


static void ctrl_stdenumcur_clear_dirty(struct pvr2_ctrl *cptr)
{
	cptr->hdw->std_dirty = 0;
}


#define DEFINT(vmin,vmax) \
	.type = pvr2_ctl_int, \
	.def.type_int.min_value = vmin, \
	.def.type_int.max_value = vmax

#define DEFENUM(tab) \
	.type = pvr2_ctl_enum, \
967
	.def.type_enum.count = ARRAY_SIZE(tab), \
968 969
	.def.type_enum.value_names = tab

970 971 972
#define DEFBOOL \
	.type = pvr2_ctl_bool

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
#define DEFMASK(msk,tab) \
	.type = pvr2_ctl_bitmask, \
	.def.type_bitmask.valid_bits = msk, \
	.def.type_bitmask.bit_names = tab

#define DEFREF(vname) \
	.set_value = ctrl_set_##vname, \
	.get_value = ctrl_get_##vname, \
	.is_dirty = ctrl_isdirty_##vname, \
	.clear_dirty = ctrl_cleardirty_##vname


#define VCREATE_FUNCS(vname) \
static int ctrl_get_##vname(struct pvr2_ctrl *cptr,int *vp) \
{*vp = cptr->hdw->vname##_val; return 0;} \
static int ctrl_set_##vname(struct pvr2_ctrl *cptr,int m,int v) \
{cptr->hdw->vname##_val = v; cptr->hdw->vname##_dirty = !0; return 0;} \
static int ctrl_isdirty_##vname(struct pvr2_ctrl *cptr) \
{return cptr->hdw->vname##_dirty != 0;} \
static void ctrl_cleardirty_##vname(struct pvr2_ctrl *cptr) \
{cptr->hdw->vname##_dirty = 0;}

VCREATE_FUNCS(brightness)
VCREATE_FUNCS(contrast)
VCREATE_FUNCS(saturation)
VCREATE_FUNCS(hue)
VCREATE_FUNCS(volume)
VCREATE_FUNCS(balance)
VCREATE_FUNCS(bass)
VCREATE_FUNCS(treble)
VCREATE_FUNCS(mute)
1004 1005 1006 1007
VCREATE_FUNCS(cropl)
VCREATE_FUNCS(cropt)
VCREATE_FUNCS(cropw)
VCREATE_FUNCS(croph)
1008 1009 1010
VCREATE_FUNCS(audiomode)
VCREATE_FUNCS(res_hor)
VCREATE_FUNCS(res_ver)
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
VCREATE_FUNCS(srate)

/* Table definition of all controls which can be manipulated */
static const struct pvr2_ctl_info control_defs[] = {
	{
		.v4l_id = V4L2_CID_BRIGHTNESS,
		.desc = "Brightness",
		.name = "brightness",
		.default_value = 128,
		DEFREF(brightness),
		DEFINT(0,255),
	},{
		.v4l_id = V4L2_CID_CONTRAST,
		.desc = "Contrast",
		.name = "contrast",
		.default_value = 68,
		DEFREF(contrast),
		DEFINT(0,127),
	},{
		.v4l_id = V4L2_CID_SATURATION,
		.desc = "Saturation",
		.name = "saturation",
		.default_value = 64,
		DEFREF(saturation),
		DEFINT(0,127),
	},{
		.v4l_id = V4L2_CID_HUE,
		.desc = "Hue",
		.name = "hue",
		.default_value = 0,
		DEFREF(hue),
		DEFINT(-128,127),
	},{
		.v4l_id = V4L2_CID_AUDIO_VOLUME,
		.desc = "Volume",
		.name = "volume",
1047
		.default_value = 62000,
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
		DEFREF(volume),
		DEFINT(0,65535),
	},{
		.v4l_id = V4L2_CID_AUDIO_BALANCE,
		.desc = "Balance",
		.name = "balance",
		.default_value = 0,
		DEFREF(balance),
		DEFINT(-32768,32767),
	},{
		.v4l_id = V4L2_CID_AUDIO_BASS,
		.desc = "Bass",
		.name = "bass",
		.default_value = 0,
		DEFREF(bass),
		DEFINT(-32768,32767),
	},{
		.v4l_id = V4L2_CID_AUDIO_TREBLE,
		.desc = "Treble",
		.name = "treble",
		.default_value = 0,
		DEFREF(treble),
		DEFINT(-32768,32767),
	},{
		.v4l_id = V4L2_CID_AUDIO_MUTE,
		.desc = "Mute",
		.name = "mute",
		.default_value = 0,
		DEFREF(mute),
1077
		DEFBOOL,
1078
	}, {
1079
		.desc = "Capture crop left margin",
1080 1081 1082 1083 1084 1085 1086
		.name = "crop_left",
		.internal_id = PVR2_CID_CROPL,
		.default_value = 0,
		DEFREF(cropl),
		DEFINT(-129, 340),
		.get_min_value = ctrl_cropl_min_get,
		.get_max_value = ctrl_cropl_max_get,
1087
		.get_def_value = ctrl_get_cropcapdl,
1088
	}, {
1089
		.desc = "Capture crop top margin",
1090 1091 1092 1093 1094 1095 1096
		.name = "crop_top",
		.internal_id = PVR2_CID_CROPT,
		.default_value = 0,
		DEFREF(cropt),
		DEFINT(-35, 544),
		.get_min_value = ctrl_cropt_min_get,
		.get_max_value = ctrl_cropt_max_get,
1097
		.get_def_value = ctrl_get_cropcapdt,
1098
	}, {
1099
		.desc = "Capture crop width",
1100 1101 1102 1103
		.name = "crop_width",
		.internal_id = PVR2_CID_CROPW,
		.default_value = 720,
		DEFREF(cropw),
1104 1105
		.get_max_value = ctrl_cropw_max_get,
		.get_def_value = ctrl_get_cropcapdw,
1106
	}, {
1107
		.desc = "Capture crop height",
1108 1109 1110 1111
		.name = "crop_height",
		.internal_id = PVR2_CID_CROPH,
		.default_value = 480,
		DEFREF(croph),
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
		.get_max_value = ctrl_croph_max_get,
		.get_def_value = ctrl_get_cropcapdh,
	}, {
		.desc = "Capture capability pixel aspect numerator",
		.name = "cropcap_pixel_numerator",
		.internal_id = PVR2_CID_CROPCAPPAN,
		.get_value = ctrl_get_cropcappan,
	}, {
		.desc = "Capture capability pixel aspect denominator",
		.name = "cropcap_pixel_denominator",
		.internal_id = PVR2_CID_CROPCAPPAD,
		.get_value = ctrl_get_cropcappad,
	}, {
		.desc = "Capture capability bounds top",
		.name = "cropcap_bounds_top",
		.internal_id = PVR2_CID_CROPCAPBT,
		.get_value = ctrl_get_cropcapbt,
	}, {
		.desc = "Capture capability bounds left",
		.name = "cropcap_bounds_left",
		.internal_id = PVR2_CID_CROPCAPBL,
		.get_value = ctrl_get_cropcapbl,
	}, {
		.desc = "Capture capability bounds width",
		.name = "cropcap_bounds_width",
		.internal_id = PVR2_CID_CROPCAPBW,
		.get_value = ctrl_get_cropcapbw,
	}, {
		.desc = "Capture capability bounds height",
		.name = "cropcap_bounds_height",
		.internal_id = PVR2_CID_CROPCAPBH,
		.get_value = ctrl_get_cropcapbh,
1144 1145 1146 1147 1148
	},{
		.desc = "Video Source",
		.name = "input",
		.internal_id = PVR2_CID_INPUT,
		.default_value = PVR2_CVAL_INPUT_TV,
1149
		.check_value = ctrl_check_input,
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
		DEFREF(input),
		DEFENUM(control_values_input),
	},{
		.desc = "Audio Mode",
		.name = "audio_mode",
		.internal_id = PVR2_CID_AUDIOMODE,
		.default_value = V4L2_TUNER_MODE_STEREO,
		DEFREF(audiomode),
		DEFENUM(control_values_audiomode),
	},{
		.desc = "Horizontal capture resolution",
		.name = "resolution_hor",
		.internal_id = PVR2_CID_HRES,
		.default_value = 720,
		DEFREF(res_hor),
1165
		DEFINT(19,720),
1166 1167 1168 1169 1170 1171
	},{
		.desc = "Vertical capture resolution",
		.name = "resolution_ver",
		.internal_id = PVR2_CID_VRES,
		.default_value = 480,
		DEFREF(res_ver),
1172 1173 1174 1175 1176
		DEFINT(17,576),
		/* Hook in check for video standard and adjust maximum
		   depending on the standard. */
		.get_max_value = ctrl_vres_max_get,
		.get_min_value = ctrl_vres_min_get,
1177
	},{
1178
		.v4l_id = V4L2_CID_MPEG_AUDIO_SAMPLING_FREQ,
1179 1180
		.default_value = V4L2_MPEG_AUDIO_SAMPLING_FREQ_48000,
		.desc = "Audio Sampling Frequency",
1181 1182 1183 1184 1185 1186 1187
		.name = "srate",
		DEFREF(srate),
		DEFENUM(control_values_srate),
	},{
		.desc = "Tuner Frequency (Hz)",
		.name = "frequency",
		.internal_id = PVR2_CID_FREQUENCY,
1188
		.default_value = 0,
1189 1190 1191 1192
		.set_value = ctrl_freq_set,
		.get_value = ctrl_freq_get,
		.is_dirty = ctrl_freq_is_dirty,
		.clear_dirty = ctrl_freq_clear_dirty,
1193
		DEFINT(0,0),
1194 1195 1196 1197
		/* Hook in check for input value (tv/radio) and adjust
		   max/min values accordingly */
		.get_max_value = ctrl_freq_max_get,
		.get_min_value = ctrl_freq_min_get,
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
	},{
		.desc = "Channel",
		.name = "channel",
		.set_value = ctrl_channel_set,
		.get_value = ctrl_channel_get,
		DEFINT(0,FREQTABLE_SIZE),
	},{
		.desc = "Channel Program Frequency",
		.name = "freq_table_value",
		.set_value = ctrl_channelfreq_set,
		.get_value = ctrl_channelfreq_get,
1209
		DEFINT(0,0),
1210 1211 1212 1213
		/* Hook in check for input value (tv/radio) and adjust
		   max/min values accordingly */
		.get_max_value = ctrl_freq_max_get,
		.get_min_value = ctrl_freq_min_get,
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
	},{
		.desc = "Channel Program ID",
		.name = "freq_table_channel",
		.set_value = ctrl_channelprog_set,
		.get_value = ctrl_channelprog_get,
		DEFINT(0,FREQTABLE_SIZE),
	},{
		.desc = "Streaming Enabled",
		.name = "streaming_enabled",
		.get_value = ctrl_streamingenabled_get,
1224
		DEFBOOL,
1225 1226 1227 1228 1229
	},{
		.desc = "USB Speed",
		.name = "usb_speed",
		.get_value = ctrl_hsm_get,
		DEFENUM(control_values_hsm),
1230 1231 1232 1233 1234
	},{
		.desc = "Master State",
		.name = "master_state",
		.get_value = ctrl_masterstate_get,
		DEFENUM(pvr2_state_names),
1235 1236 1237 1238
	},{
		.desc = "Signal Present",
		.name = "signal_present",
		.get_value = ctrl_signal_get,
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
		DEFINT(0,65535),
	},{
		.desc = "Audio Modes Present",
		.name = "audio_modes_present",
		.get_value = ctrl_audio_modes_present_get,
		/* For this type we "borrow" the V4L2_TUNER_MODE enum from
		   v4l.  Nothing outside of this module cares about this,
		   but I reuse it in order to also reuse the
		   control_values_audiomode string table. */
		DEFMASK(((1 << V4L2_TUNER_MODE_MONO)|
			 (1 << V4L2_TUNER_MODE_STEREO)|
			 (1 << V4L2_TUNER_MODE_LANG1)|
			 (1 << V4L2_TUNER_MODE_LANG2)),
			control_values_audiomode),
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
	},{
		.desc = "Video Standards Available Mask",
		.name = "video_standard_mask_available",
		.internal_id = PVR2_CID_STDAVAIL,
		.skip_init = !0,
		.get_value = ctrl_stdavail_get,
		.set_value = ctrl_stdavail_set,
		.val_to_sym = ctrl_std_val_to_sym,
		.sym_to_val = ctrl_std_sym_to_val,
		.type = pvr2_ctl_bitmask,
	},{
		.desc = "Video Standards In Use Mask",
		.name = "video_standard_mask_active",
		.internal_id = PVR2_CID_STDCUR,
		.skip_init = !0,
		.get_value = ctrl_stdcur_get,
		.set_value = ctrl_stdcur_set,
		.is_dirty = ctrl_stdcur_is_dirty,
		.clear_dirty = ctrl_stdcur_clear_dirty,
		.val_to_sym = ctrl_std_val_to_sym,
		.sym_to_val = ctrl_std_sym_to_val,
		.type = pvr2_ctl_bitmask,
	},{
		.desc = "Video Standard Name",
		.name = "video_standard",
		.internal_id = PVR2_CID_STDENUM,
		.skip_init = !0,
		.get_value = ctrl_stdenumcur_get,
		.set_value = ctrl_stdenumcur_set,
		.is_dirty = ctrl_stdenumcur_is_dirty,
		.clear_dirty = ctrl_stdenumcur_clear_dirty,
		.type = pvr2_ctl_enum,
	}
};

1288
#define CTRLDEF_COUNT ARRAY_SIZE(control_defs)
1289 1290 1291 1292 1293 1294 1295 1296


const char *pvr2_config_get_name(enum pvr2_config cfg)
{
	switch (cfg) {
	case pvr2_config_empty: return "empty";
	case pvr2_config_mpeg: return "mpeg";
	case pvr2_config_vbi: return "vbi";
1297 1298
	case pvr2_config_pcm: return "pcm";
	case pvr2_config_rawvideo: return "raw video";
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
	}
	return "<unknown>";
}


struct usb_device *pvr2_hdw_get_dev(struct pvr2_hdw *hdw)
{
	return hdw->usb_dev;
}


unsigned long pvr2_hdw_get_sn(struct pvr2_hdw *hdw)
{
	return hdw->serial_number;
}

1315 1316 1317 1318 1319 1320 1321

const char *pvr2_hdw_get_bus_info(struct pvr2_hdw *hdw)
{
	return hdw->bus_info;
}


1322 1323 1324 1325 1326 1327
const char *pvr2_hdw_get_device_identifier(struct pvr2_hdw *hdw)
{
	return hdw->identifier;
}


1328 1329 1330 1331 1332 1333 1334
unsigned long pvr2_hdw_get_cur_freq(struct pvr2_hdw *hdw)
{
	return hdw->freqSelector ? hdw->freqValTelevision : hdw->freqValRadio;
}

/* Set the currently tuned frequency and account for all possible
   driver-core side effects of this action. */
1335
static void pvr2_hdw_set_cur_freq(struct pvr2_hdw *hdw,unsigned long val)
1336
{
1337
	if (hdw->input_val == PVR2_CVAL_INPUT_RADIO) {
1338 1339 1340 1341 1342 1343 1344 1345
		if (hdw->freqSelector) {
			/* Swing over to radio frequency selection */
			hdw->freqSelector = 0;
			hdw->freqDirty = !0;
		}
		if (hdw->freqValRadio != val) {
			hdw->freqValRadio = val;
			hdw->freqSlotRadio = 0;
1346
			hdw->freqDirty = !0;
1347
		}
1348
	} else {
1349 1350 1351 1352 1353 1354 1355 1356
		if (!(hdw->freqSelector)) {
			/* Swing over to television frequency selection */
			hdw->freqSelector = 1;
			hdw->freqDirty = !0;
		}
		if (hdw->freqValTelevision != val) {
			hdw->freqValTelevision = val;
			hdw->freqSlotTelevision = 0;
1357
			hdw->freqDirty = !0;
1358 1359 1360 1361
		}
	}
}

1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 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
int pvr2_hdw_get_unit_number(struct pvr2_hdw *hdw)
{
	return hdw->unit_number;
}


/* Attempt to locate one of the given set of files.  Messages are logged
   appropriate to what has been found.  The return value will be 0 or
   greater on success (it will be the index of the file name found) and
   fw_entry will be filled in.  Otherwise a negative error is returned on
   failure.  If the return value is -ENOENT then no viable firmware file
   could be located. */
static int pvr2_locate_firmware(struct pvr2_hdw *hdw,
				const struct firmware **fw_entry,
				const char *fwtypename,
				unsigned int fwcount,
				const char *fwnames[])
{
	unsigned int idx;
	int ret = -EINVAL;
	for (idx = 0; idx < fwcount; idx++) {
		ret = request_firmware(fw_entry,
				       fwnames[idx],
				       &hdw->usb_dev->dev);
		if (!ret) {
			trace_firmware("Located %s firmware: %s;"
				       " uploading...",
				       fwtypename,
				       fwnames[idx]);
			return idx;
		}
		if (ret == -ENOENT) continue;
		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
			   "request_firmware fatal error with code=%d",ret);
		return ret;
	}
	pvr2_trace(PVR2_TRACE_ERROR_LEGS,
		   "***WARNING***"
		   " Device %s firmware"
		   " seems to be missing.",
		   fwtypename);
	pvr2_trace(PVR2_TRACE_ERROR_LEGS,
		   "Did you install the pvrusb2 firmware files"
		   " in their proper location?");
	if (fwcount == 1) {
		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
			   "request_firmware unable to locate %s file %s",
			   fwtypename,fwnames[0]);
	} else {
		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
			   "request_firmware unable to locate"
			   " one of the following %s files:",
			   fwtypename);
		for (idx = 0; idx < fwcount; idx++) {
			pvr2_trace(PVR2_TRACE_ERROR_LEGS,
				   "request_firmware: Failed to find %s",
				   fwnames[idx]);
		}
	}
	return ret;
}


/*
 * pvr2_upload_firmware1().
 *
 * Send the 8051 firmware to the device.  After the upload, arrange for
 * device to re-enumerate.
 *
 * NOTE : the pointer to the firmware data given by request_firmware()
 * is not suitable for an usb transaction.
 *
 */
1435
static int pvr2_upload_firmware1(struct pvr2_hdw *hdw)
1436
{
1437
	const struct firmware *fw_entry = NULL;
1438 1439 1440 1441
	void  *fw_ptr;
	unsigned int pipe;
	int ret;
	u16 address;
1442

1443
	if (!hdw->hdw_desc->fx2_firmware.cnt) {
1444
		hdw->fw1_state = FW1_STATE_OK;
1445 1446 1447 1448
		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
			   "Connected device type defines"
			   " no firmware to upload; ignoring firmware");
		return -ENOTTY;
1449 1450
	}

1451 1452 1453 1454 1455
	hdw->fw1_state = FW1_STATE_FAILED; // default result

	trace_firmware("pvr2_upload_firmware1");

	ret = pvr2_locate_firmware(hdw,&fw_entry,"fx2 controller",
1456 1457
				   hdw->hdw_desc->fx2_firmware.cnt,
				   hdw->hdw_desc->fx2_firmware.lst);
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
	if (ret < 0) {
		if (ret == -ENOENT) hdw->fw1_state = FW1_STATE_MISSING;
		return ret;
	}

	usb_settoggle(hdw->usb_dev, 0 & 0xf, !(0 & USB_DIR_IN), 0);
	usb_clear_halt(hdw->usb_dev, usb_sndbulkpipe(hdw->usb_dev, 0 & 0x7f));

	pipe = usb_sndctrlpipe(hdw->usb_dev, 0);

	if (fw_entry->size != 0x2000){
		pvr2_trace(PVR2_TRACE_ERROR_LEGS,"wrong fx2 firmware size");
		release_firmware(fw_entry);
		return -ENOMEM;
	}

	fw_ptr = kmalloc(0x800, GFP_KERNEL);
	if (fw_ptr == NULL){
		release_firmware(fw_entry);
		return -ENOMEM;
	}

	/* We have to hold the CPU during firmware upload. */
	pvr2_hdw_cpureset_assert(hdw,1);

	/* upload the firmware to address 0000-1fff in 2048 (=0x800) bytes
	   chunk. */

	ret = 0;
	for(address = 0; address < fw_entry->size; address += 0x800) {
		memcpy(fw_ptr, fw_entry->data + address, 0x800);
		ret += usb_control_msg(hdw->usb_dev, pipe, 0xa0, 0x40, address,
				       0, fw_ptr, 0x800, HZ);
	}

	trace_firmware("Upload done, releasing device's CPU");

	/* Now release the CPU.  It will disconnect and reconnect later. */
	pvr2_hdw_cpureset_assert(hdw,0);

	kfree(fw_ptr);
	release_firmware(fw_entry);

	trace_firmware("Upload done (%d bytes sent)",ret);

	/* We should have written 8192 bytes */
	if (ret == 8192) {
		hdw->fw1_state = FW1_STATE_RELOAD;
		return 0;
	}

	return -EIO;
}


/*
 * pvr2_upload_firmware2()
 *
 * This uploads encoder firmware on endpoint 2.
 *
 */

int pvr2_upload_firmware2(struct pvr2_hdw *hdw)
{
1522
	const struct firmware *fw_entry = NULL;
1523
	void  *fw_ptr;
1524
	unsigned int pipe, fw_len, fw_done, bcnt, icnt;
1525 1526 1527 1528 1529 1530 1531
	int actual_length;
	int ret = 0;
	int fwidx;
	static const char *fw_files[] = {
		CX2341X_FIRM_ENC_FILENAME,
	};

1532
	if (hdw->hdw_desc->flag_skip_cx23416_firmware) {
1533 1534 1535
		return 0;
	}

1536 1537 1538
	trace_firmware("pvr2_upload_firmware2");

	ret = pvr2_locate_firmware(hdw,&fw_entry,"encoder",
1539
				   ARRAY_SIZE(fw_files), fw_files);
1540 1541 1542
	if (ret < 0) return ret;
	fwidx = ret;
	ret = 0;
1543 1544 1545 1546
	/* Since we're about to completely reinitialize the encoder,
	   invalidate our cached copy of its configuration state.  Next
	   time we configure the encoder, then we'll fully configure it. */
	hdw->enc_cur_valid = 0;
1547

1548 1549 1550 1551 1552 1553 1554 1555
	/* Encoder is about to be reset so note that as far as we're
	   concerned now, the encoder has never been run. */
	del_timer_sync(&hdw->encoder_run_timer);
	if (hdw->state_encoder_runok) {
		hdw->state_encoder_runok = 0;
		trace_stbit("state_encoder_runok",hdw->state_encoder_runok);
	}

1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
	/* First prepare firmware loading */
	ret |= pvr2_write_register(hdw, 0x0048, 0xffffffff); /*interrupt mask*/
	ret |= pvr2_hdw_gpio_chg_dir(hdw,0xffffffff,0x00000088); /*gpio dir*/
	ret |= pvr2_hdw_gpio_chg_out(hdw,0xffffffff,0x00000008); /*gpio output state*/
	ret |= pvr2_hdw_cmd_deep_reset(hdw);
	ret |= pvr2_write_register(hdw, 0xa064, 0x00000000); /*APU command*/
	ret |= pvr2_hdw_gpio_chg_dir(hdw,0xffffffff,0x00000408); /*gpio dir*/
	ret |= pvr2_hdw_gpio_chg_out(hdw,0xffffffff,0x00000008); /*gpio output state*/
	ret |= pvr2_write_register(hdw, 0x9058, 0xffffffed); /*VPU ctrl*/
	ret |= pvr2_write_register(hdw, 0x9054, 0xfffffffd); /*reset hw blocks*/
	ret |= pvr2_write_register(hdw, 0x07f8, 0x80000800); /*encoder SDRAM refresh*/
	ret |= pvr2_write_register(hdw, 0x07fc, 0x0000001a); /*encoder SDRAM pre-charge*/
	ret |= pvr2_write_register(hdw, 0x0700, 0x00000000); /*I2C clock*/
	ret |= pvr2_write_register(hdw, 0xaa00, 0x00000000); /*unknown*/
	ret |= pvr2_write_register(hdw, 0xaa04, 0x00057810); /*unknown*/
	ret |= pvr2_write_register(hdw, 0xaa10, 0x00148500); /*unknown*/
	ret |= pvr2_write_register(hdw, 0xaa18, 0x00840000); /*unknown*/
1573 1574
	ret |= pvr2_issue_simple_cmd(hdw,FX2CMD_FWPOST1);
	ret |= pvr2_issue_simple_cmd(hdw,FX2CMD_MEMSEL | (1 << 8) | (0 << 16));
1575 1576 1577 1578 1579

	if (ret) {
		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
			   "firmware2 upload prep failed, ret=%d",ret);
		release_firmware(fw_entry);
1580
		goto done;
1581 1582 1583 1584 1585 1586
	}

	/* Now send firmware */

	fw_len = fw_entry->size;

1587
	if (fw_len % sizeof(u32)) {
1588 1589
		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
			   "size of %s firmware"
1590
			   " must be a multiple of %zu bytes",
1591
			   fw_files[fwidx],sizeof(u32));
1592
		release_firmware(fw_entry);
1593 1594
		ret = -EINVAL;
		goto done;
1595 1596 1597 1598 1599 1600 1601
	}

	fw_ptr = kmalloc(FIRMWARE_CHUNK_SIZE, GFP_KERNEL);
	if (fw_ptr == NULL){
		release_firmware(fw_entry);
		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
			   "failed to allocate memory for firmware2 upload");
1602 1603
		ret = -ENOMEM;
		goto done;
1604 1605 1606 1607
	}

	pipe = usb_sndbulkpipe(hdw->usb_dev, PVR2_FIRMWARE_ENDPOINT);

1608 1609 1610 1611 1612 1613
	fw_done = 0;
	for (fw_done = 0; fw_done < fw_len;) {
		bcnt = fw_len - fw_done;
		if (bcnt > FIRMWARE_CHUNK_SIZE) bcnt = FIRMWARE_CHUNK_SIZE;
		memcpy(fw_ptr, fw_entry->data + fw_done, bcnt);
		/* Usbsnoop log shows that we must swap bytes... */
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
		/* Some background info: The data being swapped here is a
		   firmware image destined for the mpeg encoder chip that
		   lives at the other end of a USB endpoint.  The encoder
		   chip always talks in 32 bit chunks and its storage is
		   organized into 32 bit words.  However from the file
		   system to the encoder chip everything is purely a byte
		   stream.  The firmware file's contents are always 32 bit
		   swapped from what the encoder expects.  Thus the need
		   always exists to swap the bytes regardless of the endian
		   type of the host processor and therefore swab32() makes
		   the most sense. */
1625
		for (icnt = 0; icnt < bcnt/4 ; icnt++)
1626
			((u32 *)fw_ptr)[icnt] = swab32(((u32 *)fw_ptr)[icnt]);
1627 1628

		ret |= usb_bulk_msg(hdw->usb_dev, pipe, fw_ptr,bcnt,
1629
				    &actual_length, HZ);
1630 1631 1632
		ret |= (actual_length != bcnt);
		if (ret) break;
		fw_done += bcnt;
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
	}

	trace_firmware("upload of %s : %i / %i ",
		       fw_files[fwidx],fw_done,fw_len);

	kfree(fw_ptr);
	release_firmware(fw_entry);

	if (ret) {
		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
			   "firmware2 upload transfer failure");
1644
		goto done;
1645 1646 1647 1648 1649 1650
	}

	/* Finish upload */

	ret |= pvr2_write_register(hdw, 0x9054, 0xffffffff); /*reset hw blocks*/
	ret |= pvr2_write_register(hdw, 0x9058, 0xffffffe8); /*VPU ctrl*/
1651
	ret |= pvr2_issue_simple_cmd(hdw,FX2CMD_MEMSEL | (1 << 8) | (0 << 16));
1652 1653 1654 1655 1656

	if (ret) {
		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
			   "firmware2 upload post-proc failure");
	}
1657 1658

 done:
1659 1660 1661 1662 1663 1664
	if (hdw->hdw_desc->signal_routing_scheme ==
	    PVR2_ROUTING_SCHEME_GOTVIEW) {
		/* Ensure that GPIO 11 is set to output for GOTVIEW
		   hardware. */
		pvr2_hdw_gpio_chg_dir(hdw,(1 << 11),~0);
	}
1665 1666 1667 1668
	return ret;
}


1669 1670 1671 1672
static const char *pvr2_get_state_name(unsigned int st)
{
	if (st < ARRAY_SIZE(pvr2_state_names)) {
		return pvr2_state_names[st];
1673
	}
1674
	return "???";
1675 1676
}

1677
static int pvr2_decoder_enable(struct pvr2_hdw *hdw,int enablefl)
1678
{
1679 1680 1681
	if (hdw->decoder_ctrl) {
		hdw->decoder_ctrl->enable(hdw->decoder_ctrl->ctxt, enablefl);
		return 0;
1682
	}
1683 1684 1685 1686
	/* Even though we really only care about the video decoder chip at
	   this point, we'll broadcast stream on/off to all sub-devices
	   anyway, just in case somebody else wants to hear the
	   command... */
1687 1688
	pvr2_trace(PVR2_TRACE_CHIPS, "subdev v4l2 stream=%s",
		   (enablefl ? "on" : "off"));
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
	v4l2_device_call_all(&hdw->v4l2_dev, 0, video, s_stream, enablefl);
	if (hdw->decoder_client_id) {
		/* We get here if the encoder has been noticed.  Otherwise
		   we'll issue a warning to the user (which should
		   normally never happen). */
		return 0;
	}
	if (!hdw->flag_decoder_missed) {
		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
			   "WARNING: No decoder present");
		hdw->flag_decoder_missed = !0;
		trace_stbit("flag_decoder_missed",
			    hdw->flag_decoder_missed);
	}
	return -EIO;
1704 1705 1706
}


1707
void pvr2_hdw_set_decoder(struct pvr2_hdw *hdw,struct pvr2_decoder_ctrl *ptr)
1708
{
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
	if (hdw->decoder_ctrl == ptr) return;
	hdw->decoder_ctrl = ptr;
	if (hdw->decoder_ctrl && hdw->flag_decoder_missed) {
		hdw->flag_decoder_missed = 0;
		trace_stbit("flag_decoder_missed",
			    hdw->flag_decoder_missed);
		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
			   "Decoder has appeared");
		pvr2_hdw_state_sched(hdw);
	}
1719 1720 1721
}


1722
int pvr2_hdw_get_state(struct pvr2_hdw *hdw)
1723
{
1724
	return hdw->master_state;
1725 1726 1727
}


1728
static int pvr2_hdw_untrip_unlocked(struct pvr2_hdw *hdw)
1729
{
1730 1731 1732 1733 1734
	if (!hdw->flag_tripped) return 0;
	hdw->flag_tripped = 0;
	pvr2_trace(PVR2_TRACE_ERROR_LEGS,
		   "Clearing driver error statuss");
	return !0;
1735 1736 1737
}


1738
int pvr2_hdw_untrip(struct pvr2_hdw *hdw)
1739
{
1740
	int fl;
1741
	LOCK_TAKE(hdw->big_lock); do {
1742
		fl = pvr2_hdw_untrip_unlocked(hdw);
1743
	} while (0); LOCK_GIVE(hdw->big_lock);
1744 1745
	if (fl) pvr2_hdw_state_sched(hdw);
	return 0;
1746 1747 1748 1749 1750 1751 1752
}




int pvr2_hdw_get_streaming(struct pvr2_hdw *hdw)
{
1753
	return hdw->state_pipeline_req != 0;
1754 1755 1756 1757 1758
}


int pvr2_hdw_set_streaming(struct pvr2_hdw *hdw,int enable_flag)
{
1759
	int ret,st;
1760
	LOCK_TAKE(hdw->big_lock); do {
1761 1762 1763 1764 1765 1766 1767 1768
		pvr2_hdw_untrip_unlocked(hdw);
		if ((!enable_flag) != !(hdw->state_pipeline_req)) {
			hdw->state_pipeline_req = enable_flag != 0;
			pvr2_trace(PVR2_TRACE_START_STOP,
				   "/*--TRACE_STREAM--*/ %s",
				   enable_flag ? "enable" : "disable");
		}
		pvr2_hdw_state_sched(hdw);
1769
	} while (0); LOCK_GIVE(hdw->big_lock);
1770 1771 1772 1773 1774 1775 1776
	if ((ret = pvr2_hdw_wait(hdw,0)) < 0) return ret;
	if (enable_flag) {
		while ((st = hdw->master_state) != PVR2_STATE_RUN) {
			if (st != PVR2_STATE_READY) return -EIO;
			if ((ret = pvr2_hdw_wait(hdw,st)) < 0) return ret;
		}
	}
1777 1778 1779 1780 1781 1782
	return 0;
}


int pvr2_hdw_set_stream_type(struct pvr2_hdw *hdw,enum pvr2_config config)
{
1783
	int fl;
1784
	LOCK_TAKE(hdw->big_lock);
1785 1786 1787 1788 1789 1790 1791
	if ((fl = (hdw->desired_stream_type != config)) != 0) {
		hdw->desired_stream_type = config;
		hdw->state_pipeline_config = 0;
		trace_stbit("state_pipeline_config",
			    hdw->state_pipeline_config);
		pvr2_hdw_state_sched(hdw);
	}
1792
	LOCK_GIVE(hdw->big_lock);
1793 1794
	if (fl) return 0;
	return pvr2_hdw_wait(hdw,0);
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
}


static int get_default_tuner_type(struct pvr2_hdw *hdw)
{
	int unit_number = hdw->unit_number;
	int tp = -1;
	if ((unit_number >= 0) && (unit_number < PVR_NUM)) {
		tp = tuner[unit_number];
	}
	if (tp < 0) return -EINVAL;
	hdw->tuner_type = tp;
1807
	hdw->tuner_updated = !0;
1808 1809 1810 1811 1812 1813 1814 1815 1816 1817
	return 0;
}


static v4l2_std_id get_default_standard(struct pvr2_hdw *hdw)
{
	int unit_number = hdw->unit_number;
	int tp = 0;
	if ((unit_number >= 0) && (unit_number < PVR_NUM)) {
		tp = video_std[unit_number];
1818
		if (tp) return tp;
1819
	}
1820
	return 0;
1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
}


static unsigned int get_default_error_tolerance(struct pvr2_hdw *hdw)
{
	int unit_number = hdw->unit_number;
	int tp = 0;
	if ((unit_number >= 0) && (unit_number < PVR_NUM)) {
		tp = tolerance[unit_number];
	}
	return tp;
}


static int pvr2_hdw_check_firmware(struct pvr2_hdw *hdw)
{
	/* Try a harmless request to fetch the eeprom's address over
	   endpoint 1.  See what happens.  Only the full FX2 image can
	   respond to this.  If this probe fails then likely the FX2
	   firmware needs be loaded. */
	int result;
	LOCK_TAKE(hdw->ctl_lock); do {
1843
		hdw->cmd_buffer[0] = FX2CMD_GET_EEPROM_ADDR;
1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
		result = pvr2_send_request_ex(hdw,HZ*1,!0,
					   hdw->cmd_buffer,1,
					   hdw->cmd_buffer,1);
		if (result < 0) break;
	} while(0); LOCK_GIVE(hdw->ctl_lock);
	if (result) {
		pvr2_trace(PVR2_TRACE_INIT,
			   "Probe of device endpoint 1 result status %d",
			   result);
	} else {
		pvr2_trace(PVR2_TRACE_INIT,
			   "Probe of device endpoint 1 succeeded");
	}
	return result == 0;
}

1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
struct pvr2_std_hack {
	v4l2_std_id pat;  /* Pattern to match */
	v4l2_std_id msk;  /* Which bits we care about */
	v4l2_std_id std;  /* What additional standards or default to set */
};

/* This data structure labels specific combinations of standards from
   tveeprom that we'll try to recognize.  If we recognize one, then assume
   a specified default standard to use.  This is here because tveeprom only
   tells us about available standards not the intended default standard (if
   any) for the device in question.  We guess the default based on what has
   been reported as available.  Note that this is only for guessing a
   default - which can always be overridden explicitly - and if the user
   has otherwise named a default then that default will always be used in
   place of this table. */
1875
static const struct pvr2_std_hack std_eeprom_maps[] = {
1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893
	{	/* PAL(B/G) */
		.pat = V4L2_STD_B|V4L2_STD_GH,
		.std = V4L2_STD_PAL_B|V4L2_STD_PAL_B1|V4L2_STD_PAL_G,
	},
	{	/* NTSC(M) */
		.pat = V4L2_STD_MN,
		.std = V4L2_STD_NTSC_M,
	},
	{	/* PAL(I) */
		.pat = V4L2_STD_PAL_I,
		.std = V4L2_STD_PAL_I,
	},
	{	/* SECAM(L/L') */
		.pat = V4L2_STD_SECAM_L|V4L2_STD_SECAM_LC,
		.std = V4L2_STD_SECAM_L|V4L2_STD_SECAM_LC,
	},
	{	/* PAL(D/D1/K) */
		.pat = V4L2_STD_DK,
1894
		.std = V4L2_STD_PAL_D|V4L2_STD_PAL_D1|V4L2_STD_PAL_K,
1895 1896 1897
	},
};

1898 1899 1900 1901
static void pvr2_hdw_setup_std(struct pvr2_hdw *hdw)
{
	char buf[40];
	unsigned int bcnt;
1902
	v4l2_std_id std1,std2,std3;
1903 1904

	std1 = get_default_standard(hdw);
1905
	std3 = std1 ? 0 : hdw->hdw_desc->default_std_mask;
1906 1907

	bcnt = pvr2_std_id_to_str(buf,sizeof(buf),hdw->std_mask_eeprom);
1908
	pvr2_trace(PVR2_TRACE_STD,
1909 1910
		   "Supported video standard(s) reported available"
		   " in hardware: %.*s",
1911 1912 1913 1914
		   bcnt,buf);

	hdw->std_mask_avail = hdw->std_mask_eeprom;

1915
	std2 = (std1|std3) & ~hdw->std_mask_avail;
1916 1917
	if (std2) {
		bcnt = pvr2_std_id_to_str(buf,sizeof(buf),std2);
1918
		pvr2_trace(PVR2_TRACE_STD,
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928
			   "Expanding supported video standards"
			   " to include: %.*s",
			   bcnt,buf);
		hdw->std_mask_avail |= std2;
	}

	pvr2_hdw_internal_set_std_avail(hdw);

	if (std1) {
		bcnt = pvr2_std_id_to_str(buf,sizeof(buf),std1);
1929
		pvr2_trace(PVR2_TRACE_STD,
1930 1931 1932 1933 1934 1935 1936
			   "Initial video standard forced to %.*s",
			   bcnt,buf);
		hdw->std_mask_cur = std1;
		hdw->std_dirty = !0;
		pvr2_hdw_internal_find_stdenum(hdw);
		return;
	}
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
	if (std3) {
		bcnt = pvr2_std_id_to_str(buf,sizeof(buf),std3);
		pvr2_trace(PVR2_TRACE_STD,
			   "Initial video standard"
			   " (determined by device type): %.*s",bcnt,buf);
		hdw->std_mask_cur = std3;
		hdw->std_dirty = !0;
		pvr2_hdw_internal_find_stdenum(hdw);
		return;
	}
1947

1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
	{
		unsigned int idx;
		for (idx = 0; idx < ARRAY_SIZE(std_eeprom_maps); idx++) {
			if (std_eeprom_maps[idx].msk ?
			    ((std_eeprom_maps[idx].pat ^
			     hdw->std_mask_eeprom) &
			     std_eeprom_maps[idx].msk) :
			    (std_eeprom_maps[idx].pat !=
			     hdw->std_mask_eeprom)) continue;
			bcnt = pvr2_std_id_to_str(buf,sizeof(buf),
						  std_eeprom_maps[idx].std);
1959
			pvr2_trace(PVR2_TRACE_STD,
1960 1961 1962 1963 1964 1965 1966 1967 1968
				   "Initial video standard guessed as %.*s",
				   bcnt,buf);
			hdw->std_mask_cur = std_eeprom_maps[idx].std;
			hdw->std_dirty = !0;
			pvr2_hdw_internal_find_stdenum(hdw);
			return;
		}
	}

1969 1970 1971 1972 1973
	if (hdw->std_enum_cnt > 1) {
		// Autoselect the first listed standard
		hdw->std_enum_cur = 1;
		hdw->std_mask_cur = hdw->std_defs[hdw->std_enum_cur-1].id;
		hdw->std_dirty = !0;
1974
		pvr2_trace(PVR2_TRACE_STD,
1975 1976 1977 1978 1979
			   "Initial video standard auto-selected to %s",
			   hdw->std_defs[hdw->std_enum_cur-1].name);
		return;
	}

1980
	pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1981 1982 1983 1984
		   "Unable to select a viable initial video standard");
}


1985 1986 1987 1988
static unsigned int pvr2_copy_i2c_addr_list(
	unsigned short *dst, const unsigned char *src,
	unsigned int dst_max)
{
1989
	unsigned int cnt = 0;
1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
	if (!src) return 0;
	while (src[cnt] && (cnt + 1) < dst_max) {
		dst[cnt] = src[cnt];
		cnt++;
	}
	dst[cnt] = I2C_CLIENT_END;
	return cnt;
}


2000 2001
static int pvr2_hdw_load_subdev(struct pvr2_hdw *hdw,
				const struct pvr2_device_client_desc *cd)
2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014
{
	const char *fname;
	unsigned char mid;
	struct v4l2_subdev *sd;
	unsigned int i2ccnt;
	const unsigned char *p;
	/* Arbitrary count - max # i2c addresses we will probe */
	unsigned short i2caddr[25];

	mid = cd->module_id;
	fname = (mid < ARRAY_SIZE(module_names)) ? module_names[mid] : NULL;
	if (!fname) {
		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2015
			   "Module ID %u for device %s has no name",
2016 2017
			   mid,
			   hdw->hdw_desc->description);
2018
		return -EINVAL;
2019
	}
2020 2021 2022 2023
	pvr2_trace(PVR2_TRACE_INIT,
		   "Module ID %u (%s) for device %s being loaded...",
		   mid, fname,
		   hdw->hdw_desc->description);
2024 2025 2026 2027 2028 2029 2030 2031

	i2ccnt = pvr2_copy_i2c_addr_list(i2caddr, cd->i2c_address_list,
					 ARRAY_SIZE(i2caddr));
	if (!i2ccnt && ((p = (mid < ARRAY_SIZE(module_i2c_addresses)) ?
			 module_i2c_addresses[mid] : NULL) != NULL)) {
		/* Second chance: Try default i2c address list */
		i2ccnt = pvr2_copy_i2c_addr_list(i2caddr, p,
						 ARRAY_SIZE(i2caddr));
2032 2033 2034 2035 2036 2037
		if (i2ccnt) {
			pvr2_trace(PVR2_TRACE_INIT,
				   "Module ID %u:"
				   " Using default i2c address list",
				   mid);
		}
2038 2039 2040 2041
	}

	if (!i2ccnt) {
		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2042 2043 2044 2045
			   "Module ID %u (%s) for device %s:"
			   " No i2c addresses",
			   mid, fname, hdw->hdw_desc->description);
		return -EINVAL;
2046 2047 2048 2049 2050 2051 2052 2053 2054
	}

	/* Note how the 2nd and 3rd arguments are the same for both
	 * v4l2_i2c_new_subdev() and v4l2_i2c_new_probed_subdev().  Why?
	 * Well the 2nd argument is the module name to load, while the 3rd
	 * argument is documented in the framework as being the "chipid" -
	 * and every other place where I can find examples of this, the
	 * "chipid" appears to just be the module name again.  So here we
	 * just do the same thing. */
2055
	hdw->i2c_adap.class = 0;
2056
	if (i2ccnt == 1) {
2057 2058 2059 2060
		pvr2_trace(PVR2_TRACE_INIT,
			   "Module ID %u:"
			   " Setting up with specified i2c address 0x%x",
			   mid, i2caddr[0]);
2061 2062 2063 2064
		sd = v4l2_i2c_new_subdev(&hdw->i2c_adap,
					 fname, fname,
					 i2caddr[0]);
	} else {
2065 2066 2067 2068
		pvr2_trace(PVR2_TRACE_INIT,
			   "Module ID %u:"
			   " Setting up with address probe list",
			   mid);
2069 2070 2071 2072
		sd = v4l2_i2c_new_probed_subdev(&hdw->i2c_adap,
						fname, fname,
						i2caddr);
	}
2073
	hdw->i2c_adap.class = I2C_CLASS_TV_ANALOG;
2074

2075 2076
	if (!sd) {
		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2077 2078 2079
			   "Module ID %u (%s) for device %s failed to load",
			   mid, fname, hdw->hdw_desc->description);
		return -EIO;
2080 2081 2082 2083 2084 2085 2086
	}

	/* Tag this sub-device instance with the module ID we know about.
	   In other places we'll use that tag to determine if the instance
	   requires special handling. */
	sd->grp_id = mid;

2087 2088 2089 2090 2091
	/* If we have both old and new i2c layers enabled, make sure that
	   old layer isn't also tracking this module.  This is a debugging
	   aid, in normal situations there's no reason for both mechanisms
	   to be enabled. */
	pvr2_i2c_untrack_subdev(hdw, sd);
2092
	pvr2_trace(PVR2_TRACE_INFO, "Attached sub-driver %s", fname);
2093

2094

2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111
	/* client-specific setup... */
	switch (mid) {
	case PVR2_CLIENT_ID_CX25840:
		hdw->decoder_client_id = mid;
		{
			/*
			  Mike Isely <isely@pobox.com> 19-Nov-2006 - This
			  bit of nuttiness for cx25840 causes that module
			  to correctly set up its video scaling.  This is
			  really a problem in the cx25840 module itself,
			  but we work around it here.  The problem has not
			  been seen in ivtv because there VBI is supported
			  and set up.  We don't do VBI here (at least not
			  yet) and thus we never attempted to even set it
			  up.
			*/
			struct v4l2_format fmt;
2112 2113 2114 2115
			pvr2_trace(PVR2_TRACE_INIT,
				   "Module ID %u:"
				   " Executing cx25840 VBI hack",
				   mid);
2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126
			memset(&fmt, 0, sizeof(fmt));
			fmt.type = V4L2_BUF_TYPE_SLICED_VBI_CAPTURE;
			v4l2_device_call_all(&hdw->v4l2_dev, mid,
					     video, s_fmt, &fmt);
		}
		break;
	case PVR2_CLIENT_ID_SAA7115:
		hdw->decoder_client_id = mid;
		break;
	default: break;
	}
2127 2128

	return 0;
2129 2130 2131 2132 2133 2134 2135 2136
}


static void pvr2_hdw_load_modules(struct pvr2_hdw *hdw)
{
	unsigned int idx;
	const struct pvr2_string_table *cm;
	const struct pvr2_device_client_table *ct;
2137
	int okFl = !0;
2138 2139 2140 2141 2142 2143 2144 2145

	cm = &hdw->hdw_desc->client_modules;
	for (idx = 0; idx < cm->cnt; idx++) {
		request_module(cm->lst[idx]);
	}

	ct = &hdw->hdw_desc->client_table;
	for (idx = 0; idx < ct->cnt; idx++) {
2146
		if (pvr2_hdw_load_subdev(hdw, &ct->lst[idx]) < 0) okFl = 0;
2147
	}
2148
	if (!okFl) pvr2_hdw_render_useless(hdw);
2149 2150 2151
}


2152 2153 2154 2155 2156 2157
static void pvr2_hdw_setup_low(struct pvr2_hdw *hdw)
{
	int ret;
	unsigned int idx;
	struct pvr2_ctrl *cptr;
	int reloadFl = 0;
2158
	if (hdw->hdw_desc->fx2_firmware.cnt) {
2159 2160 2161 2162 2163 2164 2165 2166 2167 2168
		if (!reloadFl) {
			reloadFl =
				(hdw->usb_intf->cur_altsetting->desc.bNumEndpoints
				 == 0);
			if (reloadFl) {
				pvr2_trace(PVR2_TRACE_INIT,
					   "USB endpoint config looks strange"
					   "; possibly firmware needs to be"
					   " loaded");
			}
2169
		}
2170 2171 2172 2173 2174 2175 2176 2177
		if (!reloadFl) {
			reloadFl = !pvr2_hdw_check_firmware(hdw);
			if (reloadFl) {
				pvr2_trace(PVR2_TRACE_INIT,
					   "Check for FX2 firmware failed"
					   "; possibly firmware needs to be"
					   " loaded");
			}
2178
		}
2179 2180 2181 2182 2183 2184
		if (reloadFl) {
			if (pvr2_upload_firmware1(hdw) != 0) {
				pvr2_trace(PVR2_TRACE_ERROR_LEGS,
					   "Failure uploading firmware1");
			}
			return;
2185 2186 2187 2188 2189 2190
		}
	}
	hdw->fw1_state = FW1_STATE_OK;

	if (!pvr2_hdw_dev_ok(hdw)) return;

2191 2192
	hdw->force_dirty = !0;

2193
	if (!hdw->hdw_desc->flag_no_powerup) {
2194 2195
		pvr2_hdw_cmd_powerup(hdw);
		if (!pvr2_hdw_dev_ok(hdw)) return;
2196 2197
	}

2198 2199 2200 2201 2202 2203 2204 2205
	/* Take the IR chip out of reset, if appropriate */
	if (hdw->hdw_desc->ir_scheme == PVR2_IR_SCHEME_ZILOG) {
		pvr2_issue_simple_cmd(hdw,
				      FX2CMD_HCW_ZILOG_RESET |
				      (1 << 8) |
				      ((0) << 16));
	}

2206
	// This step MUST happen after the earlier powerup step.
2207
	pvr2_i2c_track_init(hdw);
2208 2209 2210
	pvr2_i2c_core_init(hdw);
	if (!pvr2_hdw_dev_ok(hdw)) return;

2211
	pvr2_hdw_load_modules(hdw);
2212
	if (!pvr2_hdw_dev_ok(hdw)) return;
2213

2214 2215
	v4l2_device_call_all(&hdw->v4l2_dev, 0, core, init, 0);

2216
	for (idx = 0; idx < CTRLDEF_COUNT; idx++) {
2217 2218 2219 2220 2221 2222
		cptr = hdw->controls + idx;
		if (cptr->info->skip_init) continue;
		if (!cptr->info->set_value) continue;
		cptr->info->set_value(cptr,~0,cptr->info->default_value);
	}

2223 2224 2225 2226 2227
	/* Set up special default values for the television and radio
	   frequencies here.  It's not really important what these defaults
	   are, but I set them to something usable in the Chicago area just
	   to make driver testing a little easier. */

2228 2229
	hdw->freqValTelevision = default_tv_freq;
	hdw->freqValRadio = default_radio_freq;
2230

2231 2232 2233 2234
	// Do not use pvr2_reset_ctl_endpoints() here.  It is not
	// thread-safe against the normal pvr2_send_request() mechanism.
	// (We should make it thread safe).

2235 2236
	if (hdw->hdw_desc->flag_has_hauppauge_rom) {
		ret = pvr2_hdw_get_eeprom_addr(hdw);
2237
		if (!pvr2_hdw_dev_ok(hdw)) return;
2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250
		if (ret < 0) {
			pvr2_trace(PVR2_TRACE_ERROR_LEGS,
				   "Unable to determine location of eeprom,"
				   " skipping");
		} else {
			hdw->eeprom_addr = ret;
			pvr2_eeprom_analyze(hdw);
			if (!pvr2_hdw_dev_ok(hdw)) return;
		}
	} else {
		hdw->tuner_type = hdw->hdw_desc->default_tuner_type;
		hdw->tuner_updated = !0;
		hdw->std_mask_eeprom = V4L2_STD_ALL;
2251 2252
	}

2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265
	if (hdw->serial_number) {
		idx = scnprintf(hdw->identifier, sizeof(hdw->identifier) - 1,
				"sn-%lu", hdw->serial_number);
	} else if (hdw->unit_number >= 0) {
		idx = scnprintf(hdw->identifier, sizeof(hdw->identifier) - 1,
				"unit-%c",
				hdw->unit_number + 'a');
	} else {
		idx = scnprintf(hdw->identifier, sizeof(hdw->identifier) - 1,
				"unit-??");
	}
	hdw->identifier[idx] = 0;

2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277
	pvr2_hdw_setup_std(hdw);

	if (!get_default_tuner_type(hdw)) {
		pvr2_trace(PVR2_TRACE_INIT,
			   "pvr2_hdw_setup: Tuner type overridden to %d",
			   hdw->tuner_type);
	}

	pvr2_i2c_core_check_stale(hdw);

	if (!pvr2_hdw_dev_ok(hdw)) return;

2278 2279 2280 2281 2282 2283 2284
	if (hdw->hdw_desc->signal_routing_scheme ==
	    PVR2_ROUTING_SCHEME_GOTVIEW) {
		/* Ensure that GPIO 11 is set to output for GOTVIEW
		   hardware. */
		pvr2_hdw_gpio_chg_dir(hdw,(1 << 11),~0);
	}

2285
	pvr2_hdw_commit_setup(hdw);
2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305

	hdw->vid_stream = pvr2_stream_create();
	if (!pvr2_hdw_dev_ok(hdw)) return;
	pvr2_trace(PVR2_TRACE_INIT,
		   "pvr2_hdw_setup: video stream is %p",hdw->vid_stream);
	if (hdw->vid_stream) {
		idx = get_default_error_tolerance(hdw);
		if (idx) {
			pvr2_trace(PVR2_TRACE_INIT,
				   "pvr2_hdw_setup: video stream %p"
				   " setting tolerance %u",
				   hdw->vid_stream,idx);
		}
		pvr2_stream_setup(hdw->vid_stream,hdw->usb_dev,
				  PVR2_VID_ENDPOINT,idx);
	}

	if (!pvr2_hdw_dev_ok(hdw)) return;

	hdw->flag_init_ok = !0;
2306 2307

	pvr2_hdw_state_sched(hdw);
2308 2309 2310
}


2311 2312 2313 2314
/* Set up the structure and attempt to put the device into a usable state.
   This can be a time-consuming operation, which is why it is not done
   internally as part of the create() step. */
static void pvr2_hdw_setup(struct pvr2_hdw *hdw)
2315 2316
{
	pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_setup(hdw=%p) begin",hdw);
2317
	do {
2318 2319 2320
		pvr2_hdw_setup_low(hdw);
		pvr2_trace(PVR2_TRACE_INIT,
			   "pvr2_hdw_setup(hdw=%p) done, ok=%d init_ok=%d",
2321
			   hdw,pvr2_hdw_dev_ok(hdw),hdw->flag_init_ok);
2322
		if (pvr2_hdw_dev_ok(hdw)) {
2323
			if (hdw->flag_init_ok) {
2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
				pvr2_trace(
					PVR2_TRACE_INFO,
					"Device initialization"
					" completed successfully.");
				break;
			}
			if (hdw->fw1_state == FW1_STATE_RELOAD) {
				pvr2_trace(
					PVR2_TRACE_INFO,
					"Device microcontroller firmware"
					" (re)loaded; it should now reset"
					" and reconnect.");
				break;
			}
			pvr2_trace(
				PVR2_TRACE_ERROR_LEGS,
				"Device initialization was not successful.");
			if (hdw->fw1_state == FW1_STATE_MISSING) {
				pvr2_trace(
					PVR2_TRACE_ERROR_LEGS,
					"Giving up since device"
					" microcontroller firmware"
					" appears to be missing.");
				break;
			}
		}
		if (procreload) {
			pvr2_trace(
				PVR2_TRACE_ERROR_LEGS,
				"Attempting pvrusb2 recovery by reloading"
				" primary firmware.");
			pvr2_trace(
				PVR2_TRACE_ERROR_LEGS,
				"If this works, device should disconnect"
				" and reconnect in a sane state.");
			hdw->fw1_state = FW1_STATE_UNKNOWN;
			pvr2_upload_firmware1(hdw);
		} else {
			pvr2_trace(
				PVR2_TRACE_ERROR_LEGS,
				"***WARNING*** pvrusb2 device hardware"
				" appears to be jammed"
				" and I can't clear it.");
			pvr2_trace(
				PVR2_TRACE_ERROR_LEGS,
				"You might need to power cycle"
				" the pvrusb2 device"
				" in order to recover.");
		}
2373
	} while (0);
2374 2375 2376 2377
	pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_setup(hdw=%p) end",hdw);
}


2378 2379 2380
/* Perform second stage initialization.  Set callback pointer first so that
   we can avoid a possible initialization race (if the kernel thread runs
   before the callback has been set). */
2381 2382 2383
int pvr2_hdw_initialize(struct pvr2_hdw *hdw,
			void (*callback_func)(void *),
			void *callback_data)
2384 2385
{
	LOCK_TAKE(hdw->big_lock); do {
2386 2387 2388 2389 2390 2391 2392 2393 2394
		if (hdw->flag_disconnected) {
			/* Handle a race here: If we're already
			   disconnected by this point, then give up.  If we
			   get past this then we'll remain connected for
			   the duration of initialization since the entire
			   initialization sequence is now protected by the
			   big_lock. */
			break;
		}
2395 2396
		hdw->state_data = callback_data;
		hdw->state_func = callback_func;
2397
		pvr2_hdw_setup(hdw);
2398
	} while (0); LOCK_GIVE(hdw->big_lock);
2399
	return hdw->flag_init_ok;
2400 2401 2402 2403 2404
}


/* Create, set up, and return a structure for interacting with the
   underlying hardware.  */
2405 2406 2407
struct pvr2_hdw *pvr2_hdw_create(struct usb_interface *intf,
				 const struct usb_device_id *devid)
{
2408
	unsigned int idx,cnt1,cnt2,m;
2409
	struct pvr2_hdw *hdw = NULL;
2410 2411
	int valid_std_mask;
	struct pvr2_ctrl *cptr;
2412
	struct usb_device *usb_dev;
2413
	const struct pvr2_device_desc *hdw_desc;
2414
	__u8 ifnum;
2415 2416
	struct v4l2_queryctrl qctrl;
	struct pvr2_ctl_info *ciptr;
2417

2418 2419
	usb_dev = interface_to_usbdev(intf);

2420
	hdw_desc = (const struct pvr2_device_desc *)(devid->driver_info);
2421

2422 2423 2424 2425 2426 2427 2428 2429 2430 2431
	if (hdw_desc == NULL) {
		pvr2_trace(PVR2_TRACE_INIT, "pvr2_hdw_create:"
			   " No device description pointer,"
			   " unable to continue.");
		pvr2_trace(PVR2_TRACE_INIT, "If you have a new device type,"
			   " please contact Mike Isely <isely@pobox.com>"
			   " to get it included in the driver\n");
		goto fail;
	}

2432
	hdw = kzalloc(sizeof(*hdw),GFP_KERNEL);
2433
	pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_create: hdw=%p, type \"%s\"",
2434
		   hdw,hdw_desc->description);
2435
	if (!hdw) goto fail;
2436 2437 2438 2439 2440 2441 2442 2443 2444

	init_timer(&hdw->quiescent_timer);
	hdw->quiescent_timer.data = (unsigned long)hdw;
	hdw->quiescent_timer.function = pvr2_hdw_quiescent_timeout;

	init_timer(&hdw->encoder_wait_timer);
	hdw->encoder_wait_timer.data = (unsigned long)hdw;
	hdw->encoder_wait_timer.function = pvr2_hdw_encoder_wait_timeout;

2445 2446 2447 2448
	init_timer(&hdw->encoder_run_timer);
	hdw->encoder_run_timer.data = (unsigned long)hdw;
	hdw->encoder_run_timer.function = pvr2_hdw_encoder_run_timeout;

2449 2450 2451 2452
	hdw->master_state = PVR2_STATE_DEAD;

	init_waitqueue_head(&hdw->state_wait_data);

2453
	hdw->tuner_signal_stale = !0;
2454
	cx2341x_fill_defaults(&hdw->enc_ctl_state);
2455

2456 2457 2458
	/* Calculate which inputs are OK */
	m = 0;
	if (hdw_desc->flag_has_analogtuner) m |= 1 << PVR2_CVAL_INPUT_TV;
2459 2460 2461
	if (hdw_desc->digital_control_scheme != PVR2_DIGITAL_SCHEME_NONE) {
		m |= 1 << PVR2_CVAL_INPUT_DTV;
	}
2462 2463 2464 2465
	if (hdw_desc->flag_has_svideo) m |= 1 << PVR2_CVAL_INPUT_SVIDEO;
	if (hdw_desc->flag_has_composite) m |= 1 << PVR2_CVAL_INPUT_COMPOSITE;
	if (hdw_desc->flag_has_fmradio) m |= 1 << PVR2_CVAL_INPUT_RADIO;
	hdw->input_avail_mask = m;
2466
	hdw->input_allowed_mask = hdw->input_avail_mask;
2467

2468 2469 2470 2471 2472 2473 2474 2475
	/* If not a hybrid device, pathway_state never changes.  So
	   initialize it here to what it should forever be. */
	if (!(hdw->input_avail_mask & (1 << PVR2_CVAL_INPUT_DTV))) {
		hdw->pathway_state = PVR2_PATHWAY_ANALOG;
	} else if (!(hdw->input_avail_mask & (1 << PVR2_CVAL_INPUT_TV))) {
		hdw->pathway_state = PVR2_PATHWAY_DIGITAL;
	}

2476
	hdw->control_cnt = CTRLDEF_COUNT;
2477
	hdw->control_cnt += MPEGDEF_COUNT;
2478
	hdw->controls = kzalloc(sizeof(struct pvr2_ctrl) * hdw->control_cnt,
2479 2480
				GFP_KERNEL);
	if (!hdw->controls) goto fail;
2481
	hdw->hdw_desc = hdw_desc;
2482 2483 2484 2485
	for (idx = 0; idx < hdw->control_cnt; idx++) {
		cptr = hdw->controls + idx;
		cptr->hdw = hdw;
	}
2486 2487 2488
	for (idx = 0; idx < 32; idx++) {
		hdw->std_mask_ptrs[idx] = hdw->std_mask_names[idx];
	}
2489
	for (idx = 0; idx < CTRLDEF_COUNT; idx++) {
2490 2491 2492
		cptr = hdw->controls + idx;
		cptr->info = control_defs+idx;
	}
2493 2494 2495 2496 2497 2498 2499 2500 2501

	/* Ensure that default input choice is a valid one. */
	m = hdw->input_avail_mask;
	if (m) for (idx = 0; idx < (sizeof(m) << 3); idx++) {
		if (!((1 << idx) & m)) continue;
		hdw->input_val = idx;
		break;
	}

2502
	/* Define and configure additional controls from cx2341x module. */
2503
	hdw->mpeg_ctrl_info = kzalloc(
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 2536 2537 2538
		sizeof(*(hdw->mpeg_ctrl_info)) * MPEGDEF_COUNT, GFP_KERNEL);
	if (!hdw->mpeg_ctrl_info) goto fail;
	for (idx = 0; idx < MPEGDEF_COUNT; idx++) {
		cptr = hdw->controls + idx + CTRLDEF_COUNT;
		ciptr = &(hdw->mpeg_ctrl_info[idx].info);
		ciptr->desc = hdw->mpeg_ctrl_info[idx].desc;
		ciptr->name = mpeg_ids[idx].strid;
		ciptr->v4l_id = mpeg_ids[idx].id;
		ciptr->skip_init = !0;
		ciptr->get_value = ctrl_cx2341x_get;
		ciptr->get_v4lflags = ctrl_cx2341x_getv4lflags;
		ciptr->is_dirty = ctrl_cx2341x_is_dirty;
		if (!idx) ciptr->clear_dirty = ctrl_cx2341x_clear_dirty;
		qctrl.id = ciptr->v4l_id;
		cx2341x_ctrl_query(&hdw->enc_ctl_state,&qctrl);
		if (!(qctrl.flags & V4L2_CTRL_FLAG_READ_ONLY)) {
			ciptr->set_value = ctrl_cx2341x_set;
		}
		strncpy(hdw->mpeg_ctrl_info[idx].desc,qctrl.name,
			PVR2_CTLD_INFO_DESC_SIZE);
		hdw->mpeg_ctrl_info[idx].desc[PVR2_CTLD_INFO_DESC_SIZE-1] = 0;
		ciptr->default_value = qctrl.default_value;
		switch (qctrl.type) {
		default:
		case V4L2_CTRL_TYPE_INTEGER:
			ciptr->type = pvr2_ctl_int;
			ciptr->def.type_int.min_value = qctrl.minimum;
			ciptr->def.type_int.max_value = qctrl.maximum;
			break;
		case V4L2_CTRL_TYPE_BOOLEAN:
			ciptr->type = pvr2_ctl_bool;
			break;
		case V4L2_CTRL_TYPE_MENU:
			ciptr->type = pvr2_ctl_enum;
			ciptr->def.type_enum.value_names =
2539 2540
				cx2341x_ctrl_get_menu(&hdw->enc_ctl_state,
								ciptr->v4l_id);
2541 2542 2543 2544 2545 2546 2547 2548
			for (cnt1 = 0;
			     ciptr->def.type_enum.value_names[cnt1] != NULL;
			     cnt1++) { }
			ciptr->def.type_enum.count = cnt1;
			break;
		}
		cptr->info = ciptr;
	}
2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588

	// Initialize video standard enum dynamic control
	cptr = pvr2_hdw_get_ctrl_by_id(hdw,PVR2_CID_STDENUM);
	if (cptr) {
		memcpy(&hdw->std_info_enum,cptr->info,
		       sizeof(hdw->std_info_enum));
		cptr->info = &hdw->std_info_enum;

	}
	// Initialize control data regarding video standard masks
	valid_std_mask = pvr2_std_get_usable();
	for (idx = 0; idx < 32; idx++) {
		if (!(valid_std_mask & (1 << idx))) continue;
		cnt1 = pvr2_std_id_to_str(
			hdw->std_mask_names[idx],
			sizeof(hdw->std_mask_names[idx])-1,
			1 << idx);
		hdw->std_mask_names[idx][cnt1] = 0;
	}
	cptr = pvr2_hdw_get_ctrl_by_id(hdw,PVR2_CID_STDAVAIL);
	if (cptr) {
		memcpy(&hdw->std_info_avail,cptr->info,
		       sizeof(hdw->std_info_avail));
		cptr->info = &hdw->std_info_avail;
		hdw->std_info_avail.def.type_bitmask.bit_names =
			hdw->std_mask_ptrs;
		hdw->std_info_avail.def.type_bitmask.valid_bits =
			valid_std_mask;
	}
	cptr = pvr2_hdw_get_ctrl_by_id(hdw,PVR2_CID_STDCUR);
	if (cptr) {
		memcpy(&hdw->std_info_cur,cptr->info,
		       sizeof(hdw->std_info_cur));
		cptr->info = &hdw->std_info_cur;
		hdw->std_info_cur.def.type_bitmask.bit_names =
			hdw->std_mask_ptrs;
		hdw->std_info_avail.def.type_bitmask.valid_bits =
			valid_std_mask;
	}

2589
	hdw->cropcap_stale = !0;
2590 2591
	hdw->eeprom_addr = -1;
	hdw->unit_number = -1;
2592 2593
	hdw->v4l_minor_number_video = -1;
	hdw->v4l_minor_number_vbi = -1;
2594
	hdw->v4l_minor_number_radio = -1;
2595 2596 2597 2598 2599 2600 2601 2602 2603
	hdw->ctl_write_buffer = kmalloc(PVR2_CTL_BUFFSIZE,GFP_KERNEL);
	if (!hdw->ctl_write_buffer) goto fail;
	hdw->ctl_read_buffer = kmalloc(PVR2_CTL_BUFFSIZE,GFP_KERNEL);
	if (!hdw->ctl_read_buffer) goto fail;
	hdw->ctl_write_urb = usb_alloc_urb(0,GFP_KERNEL);
	if (!hdw->ctl_write_urb) goto fail;
	hdw->ctl_read_urb = usb_alloc_urb(0,GFP_KERNEL);
	if (!hdw->ctl_read_urb) goto fail;

2604 2605 2606 2607 2608
	if (v4l2_device_register(&usb_dev->dev, &hdw->v4l2_dev) != 0) {
		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
			   "Error registering with v4l core, giving up");
		goto fail;
	}
2609
	mutex_lock(&pvr2_unit_mtx); do {
2610 2611 2612 2613 2614 2615
		for (idx = 0; idx < PVR_NUM; idx++) {
			if (unit_pointers[idx]) continue;
			hdw->unit_number = idx;
			unit_pointers[idx] = hdw;
			break;
		}
2616
	} while (0); mutex_unlock(&pvr2_unit_mtx);
2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628

	cnt1 = 0;
	cnt2 = scnprintf(hdw->name+cnt1,sizeof(hdw->name)-cnt1,"pvrusb2");
	cnt1 += cnt2;
	if (hdw->unit_number >= 0) {
		cnt2 = scnprintf(hdw->name+cnt1,sizeof(hdw->name)-cnt1,"_%c",
				 ('a' + hdw->unit_number));
		cnt1 += cnt2;
	}
	if (cnt1 >= sizeof(hdw->name)) cnt1 = sizeof(hdw->name)-1;
	hdw->name[cnt1] = 0;

2629 2630 2631 2632
	hdw->workqueue = create_singlethread_workqueue(hdw->name);
	INIT_WORK(&hdw->workpoll,pvr2_hdw_worker_poll);
	INIT_WORK(&hdw->worki2csync,pvr2_hdw_worker_i2c);

2633 2634 2635 2636 2637 2638 2639
	pvr2_trace(PVR2_TRACE_INIT,"Driver unit number is %d, name is %s",
		   hdw->unit_number,hdw->name);

	hdw->tuner_type = -1;
	hdw->flag_ok = !0;

	hdw->usb_intf = intf;
2640
	hdw->usb_dev = usb_dev;
2641

2642
	usb_make_path(hdw->usb_dev, hdw->bus_info, sizeof(hdw->bus_info));
2643

2644 2645 2646 2647 2648 2649 2650 2651 2652
	ifnum = hdw->usb_intf->cur_altsetting->desc.bInterfaceNumber;
	usb_set_interface(hdw->usb_dev,ifnum,0);

	mutex_init(&hdw->ctl_lock_mutex);
	mutex_init(&hdw->big_lock_mutex);

	return hdw;
 fail:
	if (hdw) {
2653
		del_timer_sync(&hdw->quiescent_timer);
2654
		del_timer_sync(&hdw->encoder_run_timer);
2655 2656 2657 2658 2659 2660
		del_timer_sync(&hdw->encoder_wait_timer);
		if (hdw->workqueue) {
			flush_workqueue(hdw->workqueue);
			destroy_workqueue(hdw->workqueue);
			hdw->workqueue = NULL;
		}
2661 2662
		usb_free_urb(hdw->ctl_read_urb);
		usb_free_urb(hdw->ctl_write_urb);
2663 2664 2665 2666
		kfree(hdw->ctl_read_buffer);
		kfree(hdw->ctl_write_buffer);
		kfree(hdw->controls);
		kfree(hdw->mpeg_ctrl_info);
2667 2668
		kfree(hdw->std_defs);
		kfree(hdw->std_enum_names);
2669 2670
		kfree(hdw);
	}
2671
	return NULL;
2672 2673 2674 2675 2676
}


/* Remove _all_ associations between this driver and the underlying USB
   layer. */
2677
static void pvr2_hdw_remove_usb_stuff(struct pvr2_hdw *hdw)
2678 2679 2680 2681 2682 2683
{
	if (hdw->flag_disconnected) return;
	pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_remove_usb_stuff: hdw=%p",hdw);
	if (hdw->ctl_read_urb) {
		usb_kill_urb(hdw->ctl_read_urb);
		usb_free_urb(hdw->ctl_read_urb);
2684
		hdw->ctl_read_urb = NULL;
2685 2686 2687 2688
	}
	if (hdw->ctl_write_urb) {
		usb_kill_urb(hdw->ctl_write_urb);
		usb_free_urb(hdw->ctl_write_urb);
2689
		hdw->ctl_write_urb = NULL;
2690 2691 2692
	}
	if (hdw->ctl_read_buffer) {
		kfree(hdw->ctl_read_buffer);
2693
		hdw->ctl_read_buffer = NULL;
2694 2695 2696
	}
	if (hdw->ctl_write_buffer) {
		kfree(hdw->ctl_write_buffer);
2697
		hdw->ctl_write_buffer = NULL;
2698 2699
	}
	hdw->flag_disconnected = !0;
2700 2701 2702 2703 2704 2705 2706
	/* If we don't do this, then there will be a dangling struct device
	   reference to our disappearing device persisting inside the V4L
	   core... */
	if (hdw->v4l2_dev.dev) {
		dev_set_drvdata(hdw->v4l2_dev.dev, NULL);
		hdw->v4l2_dev.dev = NULL;
	}
2707 2708
	hdw->usb_dev = NULL;
	hdw->usb_intf = NULL;
2709
	pvr2_hdw_render_useless(hdw);
2710 2711 2712 2713 2714 2715
}


/* Destroy hardware interaction structure */
void pvr2_hdw_destroy(struct pvr2_hdw *hdw)
{
2716
	if (!hdw) return;
2717
	pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_destroy: hdw=%p",hdw);
2718 2719 2720 2721 2722
	if (hdw->workqueue) {
		flush_workqueue(hdw->workqueue);
		destroy_workqueue(hdw->workqueue);
		hdw->workqueue = NULL;
	}
2723
	del_timer_sync(&hdw->quiescent_timer);
2724
	del_timer_sync(&hdw->encoder_run_timer);
2725
	del_timer_sync(&hdw->encoder_wait_timer);
2726 2727
	if (hdw->fw_buffer) {
		kfree(hdw->fw_buffer);
2728
		hdw->fw_buffer = NULL;
2729 2730 2731
	}
	if (hdw->vid_stream) {
		pvr2_stream_destroy(hdw->vid_stream);
2732
		hdw->vid_stream = NULL;
2733 2734 2735 2736 2737
	}
	if (hdw->decoder_ctrl) {
		hdw->decoder_ctrl->detach(hdw->decoder_ctrl->ctxt);
	}
	pvr2_i2c_core_done(hdw);
2738
	pvr2_i2c_track_done(hdw);
2739
	v4l2_device_unregister(&hdw->v4l2_dev);
2740
	pvr2_hdw_remove_usb_stuff(hdw);
2741
	mutex_lock(&pvr2_unit_mtx); do {
2742 2743 2744
		if ((hdw->unit_number >= 0) &&
		    (hdw->unit_number < PVR_NUM) &&
		    (unit_pointers[hdw->unit_number] == hdw)) {
2745
			unit_pointers[hdw->unit_number] = NULL;
2746
		}
2747
	} while (0); mutex_unlock(&pvr2_unit_mtx);
2748 2749 2750 2751
	kfree(hdw->controls);
	kfree(hdw->mpeg_ctrl_info);
	kfree(hdw->std_defs);
	kfree(hdw->std_enum_names);
2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775
	kfree(hdw);
}


int pvr2_hdw_dev_ok(struct pvr2_hdw *hdw)
{
	return (hdw && hdw->flag_ok);
}


/* Called when hardware has been unplugged */
void pvr2_hdw_disconnect(struct pvr2_hdw *hdw)
{
	pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_disconnect(hdw=%p)",hdw);
	LOCK_TAKE(hdw->big_lock);
	LOCK_TAKE(hdw->ctl_lock);
	pvr2_hdw_remove_usb_stuff(hdw);
	LOCK_GIVE(hdw->ctl_lock);
	LOCK_GIVE(hdw->big_lock);
}


// Attempt to autoselect an appropriate value for std_enum_cur given
// whatever is currently in std_mask_cur
2776
static void pvr2_hdw_internal_find_stdenum(struct pvr2_hdw *hdw)
2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790
{
	unsigned int idx;
	for (idx = 1; idx < hdw->std_enum_cnt; idx++) {
		if (hdw->std_defs[idx-1].id == hdw->std_mask_cur) {
			hdw->std_enum_cur = idx;
			return;
		}
	}
	hdw->std_enum_cur = 0;
}


// Calculate correct set of enumerated standards based on currently known
// set of available standards bits.
2791
static void pvr2_hdw_internal_set_std_avail(struct pvr2_hdw *hdw)
2792 2793 2794 2795 2796 2797 2798 2799 2800
{
	struct v4l2_standard *newstd;
	unsigned int std_cnt;
	unsigned int idx;

	newstd = pvr2_std_create_enum(&std_cnt,hdw->std_mask_avail);

	if (hdw->std_defs) {
		kfree(hdw->std_defs);
2801
		hdw->std_defs = NULL;
2802 2803 2804 2805
	}
	hdw->std_enum_cnt = 0;
	if (hdw->std_enum_names) {
		kfree(hdw->std_enum_names);
2806
		hdw->std_enum_names = NULL;
2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 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
	}

	if (!std_cnt) {
		pvr2_trace(
			PVR2_TRACE_ERROR_LEGS,
			"WARNING: Failed to identify any viable standards");
	}
	hdw->std_enum_names = kmalloc(sizeof(char *)*(std_cnt+1),GFP_KERNEL);
	hdw->std_enum_names[0] = "none";
	for (idx = 0; idx < std_cnt; idx++) {
		hdw->std_enum_names[idx+1] =
			newstd[idx].name;
	}
	// Set up the dynamic control for this standard
	hdw->std_info_enum.def.type_enum.value_names = hdw->std_enum_names;
	hdw->std_info_enum.def.type_enum.count = std_cnt+1;
	hdw->std_defs = newstd;
	hdw->std_enum_cnt = std_cnt+1;
	hdw->std_enum_cur = 0;
	hdw->std_info_cur.def.type_bitmask.valid_bits = hdw->std_mask_avail;
}


int pvr2_hdw_get_stdenum_value(struct pvr2_hdw *hdw,
			       struct v4l2_standard *std,
			       unsigned int idx)
{
	int ret = -EINVAL;
	if (!idx) return ret;
	LOCK_TAKE(hdw->big_lock); do {
		if (idx >= hdw->std_enum_cnt) break;
		idx--;
		memcpy(std,hdw->std_defs+idx,sizeof(*std));
		ret = 0;
	} while (0); LOCK_GIVE(hdw->big_lock);
	return ret;
}


/* Get the number of defined controls */
unsigned int pvr2_hdw_get_ctrl_count(struct pvr2_hdw *hdw)
{
2849
	return hdw->control_cnt;
2850 2851 2852 2853 2854 2855 2856
}


/* Retrieve a control handle given its index (0..count-1) */
struct pvr2_ctrl *pvr2_hdw_get_ctrl_by_index(struct pvr2_hdw *hdw,
					     unsigned int idx)
{
2857
	if (idx >= hdw->control_cnt) return NULL;
2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870
	return hdw->controls + idx;
}


/* Retrieve a control handle given its index (0..count-1) */
struct pvr2_ctrl *pvr2_hdw_get_ctrl_by_id(struct pvr2_hdw *hdw,
					  unsigned int ctl_id)
{
	struct pvr2_ctrl *cptr;
	unsigned int idx;
	int i;

	/* This could be made a lot more efficient, but for now... */
2871
	for (idx = 0; idx < hdw->control_cnt; idx++) {
2872 2873 2874 2875
		cptr = hdw->controls + idx;
		i = cptr->info->internal_id;
		if (i && (i == ctl_id)) return cptr;
	}
2876
	return NULL;
2877 2878 2879
}


2880
/* Given a V4L ID, retrieve the control structure associated with it. */
2881 2882 2883 2884 2885 2886 2887
struct pvr2_ctrl *pvr2_hdw_get_ctrl_v4l(struct pvr2_hdw *hdw,unsigned int ctl_id)
{
	struct pvr2_ctrl *cptr;
	unsigned int idx;
	int i;

	/* This could be made a lot more efficient, but for now... */
2888
	for (idx = 0; idx < hdw->control_cnt; idx++) {
2889 2890 2891 2892
		cptr = hdw->controls + idx;
		i = cptr->info->v4l_id;
		if (i && (i == ctl_id)) return cptr;
	}
2893
	return NULL;
2894 2895 2896
}


2897 2898 2899 2900 2901 2902 2903 2904 2905 2906
/* Given a V4L ID for its immediate predecessor, retrieve the control
   structure associated with it. */
struct pvr2_ctrl *pvr2_hdw_get_ctrl_nextv4l(struct pvr2_hdw *hdw,
					    unsigned int ctl_id)
{
	struct pvr2_ctrl *cptr,*cp2;
	unsigned int idx;
	int i;

	/* This could be made a lot more efficient, but for now... */
2907
	cp2 = NULL;
2908 2909 2910 2911 2912 2913 2914 2915 2916
	for (idx = 0; idx < hdw->control_cnt; idx++) {
		cptr = hdw->controls + idx;
		i = cptr->info->v4l_id;
		if (!i) continue;
		if (i <= ctl_id) continue;
		if (cp2 && (cp2->info->v4l_id < i)) continue;
		cp2 = cptr;
	}
	return cp2;
2917
	return NULL;
2918 2919 2920
}


2921 2922 2923 2924 2925
static const char *get_ctrl_typename(enum pvr2_ctl_type tp)
{
	switch (tp) {
	case pvr2_ctl_int: return "integer";
	case pvr2_ctl_enum: return "enum";
2926
	case pvr2_ctl_bool: return "boolean";
2927 2928 2929 2930 2931 2932
	case pvr2_ctl_bitmask: return "bitmask";
	}
	return "";
}


2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944
static void pvr2_subdev_set_control(struct pvr2_hdw *hdw, int id,
				    const char *name, int val)
{
	struct v4l2_control ctrl;
	pvr2_trace(PVR2_TRACE_CHIPS, "subdev v4l2 %s=%d", name, val);
	memset(&ctrl, 0, sizeof(ctrl));
	ctrl.id = id;
	ctrl.value = val;
	v4l2_device_call_all(&hdw->v4l2_dev, 0, core, s_ctrl, &ctrl);
}

#define PVR2_SUBDEV_SET_CONTROL(hdw, id, lab) \
2945
	if ((hdw)->lab##_dirty || (hdw)->force_dirty) {		\
2946 2947 2948
		pvr2_subdev_set_control(hdw, id, #lab, (hdw)->lab##_val); \
	}

2949
/* Execute whatever commands are required to update the state of all the
2950
   sub-devices so that they match our current control values. */
2951 2952
static void pvr2_subdev_update(struct pvr2_hdw *hdw)
{
2953 2954 2955 2956
	struct v4l2_subdev *sd;
	unsigned int id;
	pvr2_subdev_update_func fp;

2957 2958
	pvr2_trace(PVR2_TRACE_CHIPS, "subdev update...");

2959
	if (hdw->tuner_updated || hdw->force_dirty) {
2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971
		struct tuner_setup setup;
		pvr2_trace(PVR2_TRACE_CHIPS, "subdev tuner set_type(%d)",
			   hdw->tuner_type);
		if (((int)(hdw->tuner_type)) >= 0) {
			setup.addr = ADDR_UNSET;
			setup.type = hdw->tuner_type;
			setup.mode_mask = T_RADIO | T_ANALOG_TV;
			v4l2_device_call_all(&hdw->v4l2_dev, 0,
					     tuner, s_type_addr, &setup);
		}
	}

2972
	if (hdw->input_dirty || hdw->std_dirty || hdw->force_dirty) {
2973
		pvr2_trace(PVR2_TRACE_CHIPS, "subdev v4l2 set_standard");
2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996
		if (hdw->input_val == PVR2_CVAL_INPUT_RADIO) {
			v4l2_device_call_all(&hdw->v4l2_dev, 0,
					     tuner, s_radio);
		} else {
			v4l2_std_id vs;
			vs = hdw->std_mask_cur;
			v4l2_device_call_all(&hdw->v4l2_dev, 0,
					     tuner, s_std, vs);
		}
		hdw->tuner_signal_stale = !0;
		hdw->cropcap_stale = !0;
	}

	PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_BRIGHTNESS, brightness);
	PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_CONTRAST, contrast);
	PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_SATURATION, saturation);
	PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_HUE, hue);
	PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_AUDIO_MUTE, mute);
	PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_AUDIO_VOLUME, volume);
	PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_AUDIO_BALANCE, balance);
	PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_AUDIO_BASS, bass);
	PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_AUDIO_TREBLE, treble);

2997
	if (hdw->input_dirty || hdw->audiomode_dirty || hdw->force_dirty) {
2998 2999 3000 3001 3002 3003
		struct v4l2_tuner vt;
		memset(&vt, 0, sizeof(vt));
		vt.audmode = hdw->audiomode_val;
		v4l2_device_call_all(&hdw->v4l2_dev, 0, tuner, s_tuner, &vt);
	}

3004
	if (hdw->freqDirty || hdw->force_dirty) {
3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028
		unsigned long fv;
		struct v4l2_frequency freq;
		fv = pvr2_hdw_get_cur_freq(hdw);
		pvr2_trace(PVR2_TRACE_CHIPS, "subdev v4l2 set_freq(%lu)", fv);
		if (hdw->tuner_signal_stale) pvr2_hdw_status_poll(hdw);
		memset(&freq, 0, sizeof(freq));
		if (hdw->tuner_signal_info.capability & V4L2_TUNER_CAP_LOW) {
			/* ((fv * 1000) / 62500) */
			freq.frequency = (fv * 2) / 125;
		} else {
			freq.frequency = fv / 62500;
		}
		/* tuner-core currently doesn't seem to care about this, but
		   let's set it anyway for completeness. */
		if (hdw->input_val == PVR2_CVAL_INPUT_RADIO) {
			freq.type = V4L2_TUNER_RADIO;
		} else {
			freq.type = V4L2_TUNER_ANALOG_TV;
		}
		freq.tuner = 0;
		v4l2_device_call_all(&hdw->v4l2_dev, 0, tuner,
				     s_frequency, &freq);
	}

3029
	if (hdw->res_hor_dirty || hdw->res_ver_dirty || hdw->force_dirty) {
3030 3031 3032 3033 3034 3035 3036 3037 3038 3039
		struct v4l2_format fmt;
		memset(&fmt, 0, sizeof(fmt));
		fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
		fmt.fmt.pix.width = hdw->res_hor_val;
		fmt.fmt.pix.height = hdw->res_ver_val;
		pvr2_trace(PVR2_TRACE_CHIPS,"subdev v4l2 set_size(%dx%d)",
			   fmt.fmt.pix.width, fmt.fmt.pix.height);
		v4l2_device_call_all(&hdw->v4l2_dev, 0, video, s_fmt, &fmt);
	}

3040
	if (hdw->srate_dirty || hdw->force_dirty) {
3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059
		u32 val;
		pvr2_trace(PVR2_TRACE_CHIPS, "subdev v4l2 set_audio %d",
			   hdw->srate_val);
		switch (hdw->srate_val) {
		default:
		case V4L2_MPEG_AUDIO_SAMPLING_FREQ_48000:
			val = 48000;
			break;
		case V4L2_MPEG_AUDIO_SAMPLING_FREQ_44100:
			val = 44100;
			break;
		case V4L2_MPEG_AUDIO_SAMPLING_FREQ_32000:
			val = 32000;
			break;
		}
		v4l2_device_call_all(&hdw->v4l2_dev, 0,
				     audio, s_clock_freq, val);
	}

3060 3061 3062
	/* Unable to set crop parameters; there is apparently no equivalent
	   for VIDIOC_S_CROP */

3063 3064 3065 3066 3067 3068 3069
	v4l2_device_for_each_subdev(sd, &hdw->v4l2_dev) {
		id = sd->grp_id;
		if (id >= ARRAY_SIZE(pvr2_module_update_functions)) continue;
		fp = pvr2_module_update_functions[id];
		if (!fp) continue;
		(*fp)(hdw, sd);
	}
3070

3071
	if (hdw->tuner_signal_stale || hdw->cropcap_stale) {
3072 3073
		pvr2_hdw_status_poll(hdw);
	}
3074 3075 3076
}


3077 3078 3079 3080
/* Figure out if we need to commit control changes.  If so, mark internal
   state flags to indicate this fact and return true.  Otherwise do nothing
   else and return false. */
static int pvr2_hdw_commit_setup(struct pvr2_hdw *hdw)
3081 3082 3083 3084
{
	unsigned int idx;
	struct pvr2_ctrl *cptr;
	int value;
3085
	int commit_flag = hdw->force_dirty;
3086 3087 3088
	char buf[100];
	unsigned int bcnt,ccnt;

3089
	for (idx = 0; idx < hdw->control_cnt; idx++) {
3090
		cptr = hdw->controls + idx;
A
Al Viro 已提交
3091
		if (!cptr->info->is_dirty) continue;
3092
		if (!cptr->info->is_dirty(cptr)) continue;
3093
		commit_flag = !0;
3094

3095
		if (!(pvrusb2_debug & PVR2_TRACE_CTL)) continue;
3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115
		bcnt = scnprintf(buf,sizeof(buf),"\"%s\" <-- ",
				 cptr->info->name);
		value = 0;
		cptr->info->get_value(cptr,&value);
		pvr2_ctrl_value_to_sym_internal(cptr,~0,value,
						buf+bcnt,
						sizeof(buf)-bcnt,&ccnt);
		bcnt += ccnt;
		bcnt += scnprintf(buf+bcnt,sizeof(buf)-bcnt," <%s>",
				  get_ctrl_typename(cptr->info->type));
		pvr2_trace(PVR2_TRACE_CTL,
			   "/*--TRACE_COMMIT--*/ %.*s",
			   bcnt,buf);
	}

	if (!commit_flag) {
		/* Nothing has changed */
		return 0;
	}

3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134
	hdw->state_pipeline_config = 0;
	trace_stbit("state_pipeline_config",hdw->state_pipeline_config);
	pvr2_hdw_state_sched(hdw);

	return !0;
}


/* Perform all operations needed to commit all control changes.  This must
   be performed in synchronization with the pipeline state and is thus
   expected to be called as part of the driver's worker thread.  Return
   true if commit successful, otherwise return false to indicate that
   commit isn't possible at this time. */
static int pvr2_hdw_commit_execute(struct pvr2_hdw *hdw)
{
	unsigned int idx;
	struct pvr2_ctrl *cptr;
	int disruptive_change;

3135 3136
	/* Handle some required side effects when the video standard is
	   changed.... */
3137 3138
	if (hdw->std_dirty) {
		int nvres;
3139
		int gop_size;
3140 3141
		if (hdw->std_mask_cur & V4L2_STD_525_60) {
			nvres = 480;
3142
			gop_size = 15;
3143 3144
		} else {
			nvres = 576;
3145
			gop_size = 12;
3146
		}
3147 3148
		/* Rewrite the vertical resolution to be appropriate to the
		   video standard that has been selected. */
3149 3150 3151 3152
		if (nvres != hdw->res_ver_val) {
			hdw->res_ver_val = nvres;
			hdw->res_ver_dirty = !0;
		}
3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166
		/* Rewrite the GOP size to be appropriate to the video
		   standard that has been selected. */
		if (gop_size != hdw->enc_ctl_state.video_gop_size) {
			struct v4l2_ext_controls cs;
			struct v4l2_ext_control c1;
			memset(&cs, 0, sizeof(cs));
			memset(&c1, 0, sizeof(c1));
			cs.controls = &c1;
			cs.count = 1;
			c1.id = V4L2_CID_MPEG_VIDEO_GOP_SIZE;
			c1.value = gop_size;
			cx2341x_ext_ctrls(&hdw->enc_ctl_state, 0, &cs,
					  VIDIOC_S_EXT_CTRLS);
		}
3167 3168
	}

3169
	if (hdw->input_dirty && hdw->state_pathway_ok &&
3170 3171 3172 3173 3174
	    (((hdw->input_val == PVR2_CVAL_INPUT_DTV) ?
	      PVR2_PATHWAY_DIGITAL : PVR2_PATHWAY_ANALOG) !=
	     hdw->pathway_state)) {
		/* Change of mode being asked for... */
		hdw->state_pathway_ok = 0;
3175
		trace_stbit("state_pathway_ok",hdw->state_pathway_ok);
3176 3177 3178 3179 3180
	}
	if (!hdw->state_pathway_ok) {
		/* Can't commit anything until pathway is ok. */
		return 0;
	}
3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202
	/* The broadcast decoder can only scale down, so if
	 * res_*_dirty && crop window < output format ==> enlarge crop.
	 *
	 * The mpeg encoder receives fields of res_hor_val dots and
	 * res_ver_val halflines.  Limits: hor<=720, ver<=576.
	 */
	if (hdw->res_hor_dirty && hdw->cropw_val < hdw->res_hor_val) {
		hdw->cropw_val = hdw->res_hor_val;
		hdw->cropw_dirty = !0;
	} else if (hdw->cropw_dirty) {
		hdw->res_hor_dirty = !0;           /* must rescale */
		hdw->res_hor_val = min(720, hdw->cropw_val);
	}
	if (hdw->res_ver_dirty && hdw->croph_val < hdw->res_ver_val) {
		hdw->croph_val = hdw->res_ver_val;
		hdw->croph_dirty = !0;
	} else if (hdw->croph_dirty) {
		int nvres = hdw->std_mask_cur & V4L2_STD_525_60 ? 480 : 576;
		hdw->res_ver_dirty = !0;
		hdw->res_ver_val = min(nvres, hdw->croph_val);
	}

3203 3204 3205 3206 3207 3208 3209 3210 3211 3212
	/* If any of the below has changed, then we can't do the update
	   while the pipeline is running.  Pipeline must be paused first
	   and decoder -> encoder connection be made quiescent before we
	   can proceed. */
	disruptive_change =
		(hdw->std_dirty ||
		 hdw->enc_unsafe_stale ||
		 hdw->srate_dirty ||
		 hdw->res_ver_dirty ||
		 hdw->res_hor_dirty ||
3213 3214
		 hdw->cropw_dirty ||
		 hdw->croph_dirty ||
3215 3216 3217 3218 3219 3220 3221 3222
		 hdw->input_dirty ||
		 (hdw->active_stream_type != hdw->desired_stream_type));
	if (disruptive_change && !hdw->state_pipeline_idle) {
		/* Pipeline is not idle; we can't proceed.  Arrange to
		   cause pipeline to stop so that we can try this again
		   later.... */
		hdw->state_pipeline_pause = !0;
		return 0;
3223 3224
	}

3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237
	if (hdw->srate_dirty) {
		/* Write new sample rate into control structure since
		 * the master copy is stale.  We must track srate
		 * separate from the mpeg control structure because
		 * other logic also uses this value. */
		struct v4l2_ext_controls cs;
		struct v4l2_ext_control c1;
		memset(&cs,0,sizeof(cs));
		memset(&c1,0,sizeof(c1));
		cs.controls = &c1;
		cs.count = 1;
		c1.id = V4L2_CID_MPEG_AUDIO_SAMPLING_FREQ;
		c1.value = hdw->srate_val;
3238
		cx2341x_ext_ctrls(&hdw->enc_ctl_state, 0, &cs,VIDIOC_S_EXT_CTRLS);
3239
	}
3240

3241 3242 3243 3244 3245 3246
	/* Scan i2c core at this point - before we clear all the dirty
	   bits.  Various parts of the i2c core will notice dirty bits as
	   appropriate and arrange to broadcast or directly send updates to
	   the client drivers in order to keep everything in sync */
	pvr2_i2c_core_check_stale(hdw);

3247 3248 3249 3250 3251
	if (hdw->active_stream_type != hdw->desired_stream_type) {
		/* Handle any side effects of stream config here */
		hdw->active_stream_type = hdw->desired_stream_type;
	}

3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265
	if (hdw->hdw_desc->signal_routing_scheme ==
	    PVR2_ROUTING_SCHEME_GOTVIEW) {
		u32 b;
		/* Handle GOTVIEW audio switching */
		pvr2_hdw_gpio_get_out(hdw,&b);
		if (hdw->input_val == PVR2_CVAL_INPUT_RADIO) {
			/* Set GPIO 11 */
			pvr2_hdw_gpio_chg_out(hdw,(1 << 11),~0);
		} else {
			/* Clear GPIO 11 */
			pvr2_hdw_gpio_chg_out(hdw,(1 << 11),0);
		}
	}

3266 3267 3268
	/* Check and update state for all sub-devices. */
	pvr2_subdev_update(hdw);

3269
	hdw->tuner_updated = 0;
3270
	hdw->force_dirty = 0;
3271 3272 3273 3274 3275 3276
	for (idx = 0; idx < hdw->control_cnt; idx++) {
		cptr = hdw->controls + idx;
		if (!cptr->info->clear_dirty) continue;
		cptr->info->clear_dirty(cptr);
	}

3277 3278 3279
	/* Now execute i2c core update */
	pvr2_i2c_core_sync(hdw);

3280 3281 3282 3283 3284
	if ((hdw->pathway_state == PVR2_PATHWAY_ANALOG) &&
	    hdw->state_encoder_run) {
		/* If encoder isn't running or it can't be touched, then
		   this will get worked out later when we start the
		   encoder. */
3285 3286
		if (pvr2_encoder_adjust(hdw) < 0) return !0;
	}
3287

3288
	hdw->state_pipeline_config = !0;
3289 3290 3291
	/* Hardware state may have changed in a way to cause the cropping
	   capabilities to have changed.  So mark it stale, which will
	   cause a later re-fetch. */
3292 3293
	trace_stbit("state_pipeline_config",hdw->state_pipeline_config);
	return !0;
3294 3295 3296 3297 3298
}


int pvr2_hdw_commit_ctl(struct pvr2_hdw *hdw)
{
3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310
	int fl;
	LOCK_TAKE(hdw->big_lock);
	fl = pvr2_hdw_commit_setup(hdw);
	LOCK_GIVE(hdw->big_lock);
	if (!fl) return 0;
	return pvr2_hdw_wait(hdw,0);
}


static void pvr2_hdw_worker_i2c(struct work_struct *work)
{
	struct pvr2_hdw *hdw = container_of(work,struct pvr2_hdw,worki2csync);
3311
	LOCK_TAKE(hdw->big_lock); do {
3312
		pvr2_i2c_core_sync(hdw);
3313 3314 3315 3316
	} while (0); LOCK_GIVE(hdw->big_lock);
}


3317
static void pvr2_hdw_worker_poll(struct work_struct *work)
3318
{
3319 3320
	int fl = 0;
	struct pvr2_hdw *hdw = container_of(work,struct pvr2_hdw,workpoll);
3321
	LOCK_TAKE(hdw->big_lock); do {
3322
		fl = pvr2_hdw_state_eval(hdw);
3323
	} while (0); LOCK_GIVE(hdw->big_lock);
3324 3325 3326
	if (fl && hdw->state_func) {
		hdw->state_func(hdw->state_data);
	}
3327 3328 3329
}


3330
static int pvr2_hdw_wait(struct pvr2_hdw *hdw,int state)
3331
{
3332 3333 3334 3335 3336 3337 3338
	return wait_event_interruptible(
		hdw->state_wait_data,
		(hdw->state_stale == 0) &&
		(!state || (hdw->master_state != state)));
}


3339 3340 3341 3342 3343 3344 3345
/* Return name for this driver instance */
const char *pvr2_hdw_get_driver_name(struct pvr2_hdw *hdw)
{
	return hdw->name;
}


3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357
const char *pvr2_hdw_get_desc(struct pvr2_hdw *hdw)
{
	return hdw->hdw_desc->description;
}


const char *pvr2_hdw_get_type(struct pvr2_hdw *hdw)
{
	return hdw->hdw_desc->shortname;
}


3358 3359 3360 3361
int pvr2_hdw_is_hsm(struct pvr2_hdw *hdw)
{
	int result;
	LOCK_TAKE(hdw->ctl_lock); do {
3362
		hdw->cmd_buffer[0] = FX2CMD_GET_USB_SPEED;
3363 3364 3365 3366 3367 3368 3369 3370 3371 3372
		result = pvr2_send_request(hdw,
					   hdw->cmd_buffer,1,
					   hdw->cmd_buffer,1);
		if (result < 0) break;
		result = (hdw->cmd_buffer[0] != 0);
	} while(0); LOCK_GIVE(hdw->ctl_lock);
	return result;
}


3373 3374
/* Execute poll of tuner status */
void pvr2_hdw_execute_tuner_poll(struct pvr2_hdw *hdw)
3375 3376
{
	LOCK_TAKE(hdw->big_lock); do {
3377
		pvr2_hdw_status_poll(hdw);
3378
	} while (0); LOCK_GIVE(hdw->big_lock);
3379 3380 3381
}


3382 3383 3384 3385 3386
static int pvr2_hdw_check_cropcap(struct pvr2_hdw *hdw)
{
	if (!hdw->cropcap_stale) {
		return 0;
	}
3387
	pvr2_hdw_status_poll(hdw);
3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408
	if (hdw->cropcap_stale) {
		return -EIO;
	}
	return 0;
}


/* Return information about cropping capabilities */
int pvr2_hdw_get_cropcap(struct pvr2_hdw *hdw, struct v4l2_cropcap *pp)
{
	int stat = 0;
	LOCK_TAKE(hdw->big_lock);
	stat = pvr2_hdw_check_cropcap(hdw);
	if (!stat) {
		memcpy(pp, &hdw->cropcap_info, sizeof(hdw->cropcap_info));
	}
	LOCK_GIVE(hdw->big_lock);
	return stat;
}


3409 3410 3411 3412 3413
/* Return information about the tuner */
int pvr2_hdw_get_tuner_status(struct pvr2_hdw *hdw,struct v4l2_tuner *vtp)
{
	LOCK_TAKE(hdw->big_lock); do {
		if (hdw->tuner_signal_stale) {
3414
			pvr2_hdw_status_poll(hdw);
3415 3416 3417 3418
		}
		memcpy(vtp,&hdw->tuner_signal_info,sizeof(struct v4l2_tuner));
	} while (0); LOCK_GIVE(hdw->big_lock);
	return 0;
3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430
}


/* Get handle to video output stream */
struct pvr2_stream *pvr2_hdw_get_video_stream(struct pvr2_hdw *hp)
{
	return hp->vid_stream;
}


void pvr2_hdw_trigger_module_log(struct pvr2_hdw *hdw)
{
3431
	int nr = pvr2_hdw_get_unit_number(hdw);
3432
	LOCK_TAKE(hdw->big_lock); do {
3433
		printk(KERN_INFO "pvrusb2: =================  START STATUS CARD #%d  =================\n", nr);
3434
		hdw->log_requested = !0;
3435 3436
		pvr2_i2c_core_check_stale(hdw);
		pvr2_i2c_core_sync(hdw);
3437
		hdw->log_requested = 0;
3438
		v4l2_device_call_all(&hdw->v4l2_dev, 0, core, log_status);
3439
		pvr2_trace(PVR2_TRACE_INFO,"cx2341x config:");
3440
		cx2341x_log_status(&hdw->enc_ctl_state, "pvrusb2");
3441
		pvr2_hdw_state_log_state(hdw);
3442
		printk(KERN_INFO "pvrusb2: ==================  END STATUS CARD #%d  ==================\n", nr);
3443 3444 3445
	} while (0); LOCK_GIVE(hdw->big_lock);
}

3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524

/* Grab EEPROM contents, needed for direct method. */
#define EEPROM_SIZE 8192
#define trace_eeprom(...) pvr2_trace(PVR2_TRACE_EEPROM,__VA_ARGS__)
static u8 *pvr2_full_eeprom_fetch(struct pvr2_hdw *hdw)
{
	struct i2c_msg msg[2];
	u8 *eeprom;
	u8 iadd[2];
	u8 addr;
	u16 eepromSize;
	unsigned int offs;
	int ret;
	int mode16 = 0;
	unsigned pcnt,tcnt;
	eeprom = kmalloc(EEPROM_SIZE,GFP_KERNEL);
	if (!eeprom) {
		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
			   "Failed to allocate memory"
			   " required to read eeprom");
		return NULL;
	}

	trace_eeprom("Value for eeprom addr from controller was 0x%x",
		     hdw->eeprom_addr);
	addr = hdw->eeprom_addr;
	/* Seems that if the high bit is set, then the *real* eeprom
	   address is shifted right now bit position (noticed this in
	   newer PVR USB2 hardware) */
	if (addr & 0x80) addr >>= 1;

	/* FX2 documentation states that a 16bit-addressed eeprom is
	   expected if the I2C address is an odd number (yeah, this is
	   strange but it's what they do) */
	mode16 = (addr & 1);
	eepromSize = (mode16 ? EEPROM_SIZE : 256);
	trace_eeprom("Examining %d byte eeprom at location 0x%x"
		     " using %d bit addressing",eepromSize,addr,
		     mode16 ? 16 : 8);

	msg[0].addr = addr;
	msg[0].flags = 0;
	msg[0].len = mode16 ? 2 : 1;
	msg[0].buf = iadd;
	msg[1].addr = addr;
	msg[1].flags = I2C_M_RD;

	/* We have to do the actual eeprom data fetch ourselves, because
	   (1) we're only fetching part of the eeprom, and (2) if we were
	   getting the whole thing our I2C driver can't grab it in one
	   pass - which is what tveeprom is otherwise going to attempt */
	memset(eeprom,0,EEPROM_SIZE);
	for (tcnt = 0; tcnt < EEPROM_SIZE; tcnt += pcnt) {
		pcnt = 16;
		if (pcnt + tcnt > EEPROM_SIZE) pcnt = EEPROM_SIZE-tcnt;
		offs = tcnt + (eepromSize - EEPROM_SIZE);
		if (mode16) {
			iadd[0] = offs >> 8;
			iadd[1] = offs;
		} else {
			iadd[0] = offs;
		}
		msg[1].len = pcnt;
		msg[1].buf = eeprom+tcnt;
		if ((ret = i2c_transfer(&hdw->i2c_adap,
					msg,ARRAY_SIZE(msg))) != 2) {
			pvr2_trace(PVR2_TRACE_ERROR_LEGS,
				   "eeprom fetch set offs err=%d",ret);
			kfree(eeprom);
			return NULL;
		}
	}
	return eeprom;
}


void pvr2_hdw_cpufw_set_enabled(struct pvr2_hdw *hdw,
				int prom_flag,
				int enable_flag)
3525 3526 3527 3528 3529
{
	int ret;
	u16 address;
	unsigned int pipe;
	LOCK_TAKE(hdw->big_lock); do {
A
Al Viro 已提交
3530
		if ((hdw->fw_buffer == NULL) == !enable_flag) break;
3531 3532 3533 3534 3535

		if (!enable_flag) {
			pvr2_trace(PVR2_TRACE_FIRMWARE,
				   "Cleaning up after CPU firmware fetch");
			kfree(hdw->fw_buffer);
3536
			hdw->fw_buffer = NULL;
3537
			hdw->fw_size = 0;
3538 3539 3540 3541 3542
			if (hdw->fw_cpu_flag) {
				/* Now release the CPU.  It will disconnect
				   and reconnect later. */
				pvr2_hdw_cpureset_assert(hdw,0);
			}
3543 3544 3545
			break;
		}

3546 3547 3548 3549 3550 3551 3552 3553 3554 3555
		hdw->fw_cpu_flag = (prom_flag == 0);
		if (hdw->fw_cpu_flag) {
			pvr2_trace(PVR2_TRACE_FIRMWARE,
				   "Preparing to suck out CPU firmware");
			hdw->fw_size = 0x2000;
			hdw->fw_buffer = kzalloc(hdw->fw_size,GFP_KERNEL);
			if (!hdw->fw_buffer) {
				hdw->fw_size = 0;
				break;
			}
3556

3557 3558
			/* We have to hold the CPU during firmware upload. */
			pvr2_hdw_cpureset_assert(hdw,1);
3559

3560 3561
			/* download the firmware from address 0000-1fff in 2048
			   (=0x800) bytes chunk. */
3562

3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574
			pvr2_trace(PVR2_TRACE_FIRMWARE,
				   "Grabbing CPU firmware");
			pipe = usb_rcvctrlpipe(hdw->usb_dev, 0);
			for(address = 0; address < hdw->fw_size;
			    address += 0x800) {
				ret = usb_control_msg(hdw->usb_dev,pipe,
						      0xa0,0xc0,
						      address,0,
						      hdw->fw_buffer+address,
						      0x800,HZ);
				if (ret < 0) break;
			}
3575

3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590
			pvr2_trace(PVR2_TRACE_FIRMWARE,
				   "Done grabbing CPU firmware");
		} else {
			pvr2_trace(PVR2_TRACE_FIRMWARE,
				   "Sucking down EEPROM contents");
			hdw->fw_buffer = pvr2_full_eeprom_fetch(hdw);
			if (!hdw->fw_buffer) {
				pvr2_trace(PVR2_TRACE_FIRMWARE,
					   "EEPROM content suck failed.");
				break;
			}
			hdw->fw_size = EEPROM_SIZE;
			pvr2_trace(PVR2_TRACE_FIRMWARE,
				   "Done sucking down EEPROM contents");
		}
3591 3592 3593 3594 3595 3596 3597 3598

	} while (0); LOCK_GIVE(hdw->big_lock);
}


/* Return true if we're in a mode for retrieval CPU firmware */
int pvr2_hdw_cpufw_get_enabled(struct pvr2_hdw *hdw)
{
A
Al Viro 已提交
3599
	return hdw->fw_buffer != NULL;
3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 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
}


int pvr2_hdw_cpufw_get(struct pvr2_hdw *hdw,unsigned int offs,
		       char *buf,unsigned int cnt)
{
	int ret = -EINVAL;
	LOCK_TAKE(hdw->big_lock); do {
		if (!buf) break;
		if (!cnt) break;

		if (!hdw->fw_buffer) {
			ret = -EIO;
			break;
		}

		if (offs >= hdw->fw_size) {
			pvr2_trace(PVR2_TRACE_FIRMWARE,
				   "Read firmware data offs=%d EOF",
				   offs);
			ret = 0;
			break;
		}

		if (offs + cnt > hdw->fw_size) cnt = hdw->fw_size - offs;

		memcpy(buf,hdw->fw_buffer+offs,cnt);

		pvr2_trace(PVR2_TRACE_FIRMWARE,
			   "Read firmware data offs=%d cnt=%d",
			   offs,cnt);
		ret = cnt;
	} while (0); LOCK_GIVE(hdw->big_lock);

	return ret;
}


3638
int pvr2_hdw_v4l_get_minor_number(struct pvr2_hdw *hdw,
3639
				  enum pvr2_v4l_type index)
3640
{
3641
	switch (index) {
3642 3643 3644
	case pvr2_v4l_type_video: return hdw->v4l_minor_number_video;
	case pvr2_v4l_type_vbi: return hdw->v4l_minor_number_vbi;
	case pvr2_v4l_type_radio: return hdw->v4l_minor_number_radio;
3645 3646
	default: return -1;
	}
3647 3648 3649
}


3650
/* Store a v4l minor device number */
3651
void pvr2_hdw_v4l_store_minor_number(struct pvr2_hdw *hdw,
3652
				     enum pvr2_v4l_type index,int v)
3653
{
3654
	switch (index) {
3655 3656 3657
	case pvr2_v4l_type_video: hdw->v4l_minor_number_video = v;
	case pvr2_v4l_type_vbi: hdw->v4l_minor_number_vbi = v;
	case pvr2_v4l_type_radio: hdw->v4l_minor_number_radio = v;
3658 3659
	default: break;
	}
3660 3661 3662
}


3663
static void pvr2_ctl_write_complete(struct urb *urb)
3664 3665 3666 3667 3668 3669 3670 3671
{
	struct pvr2_hdw *hdw = urb->context;
	hdw->ctl_write_pend_flag = 0;
	if (hdw->ctl_read_pend_flag) return;
	complete(&hdw->ctl_done);
}


3672
static void pvr2_ctl_read_complete(struct urb *urb)
3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685
{
	struct pvr2_hdw *hdw = urb->context;
	hdw->ctl_read_pend_flag = 0;
	if (hdw->ctl_write_pend_flag) return;
	complete(&hdw->ctl_done);
}


static void pvr2_ctl_timeout(unsigned long data)
{
	struct pvr2_hdw *hdw = (struct pvr2_hdw *)data;
	if (hdw->ctl_write_pend_flag || hdw->ctl_read_pend_flag) {
		hdw->ctl_timeout_flag = !0;
3686
		if (hdw->ctl_write_pend_flag)
3687
			usb_unlink_urb(hdw->ctl_write_urb);
3688
		if (hdw->ctl_read_pend_flag)
3689 3690 3691 3692 3693
			usb_unlink_urb(hdw->ctl_read_urb);
	}
}


3694 3695 3696 3697
/* Issue a command and get a response from the device.  This extended
   version includes a probe flag (which if set means that device errors
   should not be logged or treated as fatal) and a timeout in jiffies.
   This can be used to non-lethally probe the health of endpoint 1. */
3698 3699 3700 3701
static int pvr2_send_request_ex(struct pvr2_hdw *hdw,
				unsigned int timeout,int probe_fl,
				void *write_data,unsigned int write_len,
				void *read_data,unsigned int read_len)
3702 3703 3704 3705 3706 3707 3708 3709 3710 3711
{
	unsigned int idx;
	int status = 0;
	struct timer_list timer;
	if (!hdw->ctl_lock_held) {
		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
			   "Attempted to execute control transfer"
			   " without lock!!");
		return -EDEADLK;
	}
3712
	if (!hdw->flag_ok && !probe_fl) {
3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 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 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919
		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
			   "Attempted to execute control transfer"
			   " when device not ok");
		return -EIO;
	}
	if (!(hdw->ctl_read_urb && hdw->ctl_write_urb)) {
		if (!probe_fl) {
			pvr2_trace(PVR2_TRACE_ERROR_LEGS,
				   "Attempted to execute control transfer"
				   " when USB is disconnected");
		}
		return -ENOTTY;
	}

	/* Ensure that we have sane parameters */
	if (!write_data) write_len = 0;
	if (!read_data) read_len = 0;
	if (write_len > PVR2_CTL_BUFFSIZE) {
		pvr2_trace(
			PVR2_TRACE_ERROR_LEGS,
			"Attempted to execute %d byte"
			" control-write transfer (limit=%d)",
			write_len,PVR2_CTL_BUFFSIZE);
		return -EINVAL;
	}
	if (read_len > PVR2_CTL_BUFFSIZE) {
		pvr2_trace(
			PVR2_TRACE_ERROR_LEGS,
			"Attempted to execute %d byte"
			" control-read transfer (limit=%d)",
			write_len,PVR2_CTL_BUFFSIZE);
		return -EINVAL;
	}
	if ((!write_len) && (!read_len)) {
		pvr2_trace(
			PVR2_TRACE_ERROR_LEGS,
			"Attempted to execute null control transfer?");
		return -EINVAL;
	}


	hdw->cmd_debug_state = 1;
	if (write_len) {
		hdw->cmd_debug_code = ((unsigned char *)write_data)[0];
	} else {
		hdw->cmd_debug_code = 0;
	}
	hdw->cmd_debug_write_len = write_len;
	hdw->cmd_debug_read_len = read_len;

	/* Initialize common stuff */
	init_completion(&hdw->ctl_done);
	hdw->ctl_timeout_flag = 0;
	hdw->ctl_write_pend_flag = 0;
	hdw->ctl_read_pend_flag = 0;
	init_timer(&timer);
	timer.expires = jiffies + timeout;
	timer.data = (unsigned long)hdw;
	timer.function = pvr2_ctl_timeout;

	if (write_len) {
		hdw->cmd_debug_state = 2;
		/* Transfer write data to internal buffer */
		for (idx = 0; idx < write_len; idx++) {
			hdw->ctl_write_buffer[idx] =
				((unsigned char *)write_data)[idx];
		}
		/* Initiate a write request */
		usb_fill_bulk_urb(hdw->ctl_write_urb,
				  hdw->usb_dev,
				  usb_sndbulkpipe(hdw->usb_dev,
						  PVR2_CTL_WRITE_ENDPOINT),
				  hdw->ctl_write_buffer,
				  write_len,
				  pvr2_ctl_write_complete,
				  hdw);
		hdw->ctl_write_urb->actual_length = 0;
		hdw->ctl_write_pend_flag = !0;
		status = usb_submit_urb(hdw->ctl_write_urb,GFP_KERNEL);
		if (status < 0) {
			pvr2_trace(PVR2_TRACE_ERROR_LEGS,
				   "Failed to submit write-control"
				   " URB status=%d",status);
			hdw->ctl_write_pend_flag = 0;
			goto done;
		}
	}

	if (read_len) {
		hdw->cmd_debug_state = 3;
		memset(hdw->ctl_read_buffer,0x43,read_len);
		/* Initiate a read request */
		usb_fill_bulk_urb(hdw->ctl_read_urb,
				  hdw->usb_dev,
				  usb_rcvbulkpipe(hdw->usb_dev,
						  PVR2_CTL_READ_ENDPOINT),
				  hdw->ctl_read_buffer,
				  read_len,
				  pvr2_ctl_read_complete,
				  hdw);
		hdw->ctl_read_urb->actual_length = 0;
		hdw->ctl_read_pend_flag = !0;
		status = usb_submit_urb(hdw->ctl_read_urb,GFP_KERNEL);
		if (status < 0) {
			pvr2_trace(PVR2_TRACE_ERROR_LEGS,
				   "Failed to submit read-control"
				   " URB status=%d",status);
			hdw->ctl_read_pend_flag = 0;
			goto done;
		}
	}

	/* Start timer */
	add_timer(&timer);

	/* Now wait for all I/O to complete */
	hdw->cmd_debug_state = 4;
	while (hdw->ctl_write_pend_flag || hdw->ctl_read_pend_flag) {
		wait_for_completion(&hdw->ctl_done);
	}
	hdw->cmd_debug_state = 5;

	/* Stop timer */
	del_timer_sync(&timer);

	hdw->cmd_debug_state = 6;
	status = 0;

	if (hdw->ctl_timeout_flag) {
		status = -ETIMEDOUT;
		if (!probe_fl) {
			pvr2_trace(PVR2_TRACE_ERROR_LEGS,
				   "Timed out control-write");
		}
		goto done;
	}

	if (write_len) {
		/* Validate results of write request */
		if ((hdw->ctl_write_urb->status != 0) &&
		    (hdw->ctl_write_urb->status != -ENOENT) &&
		    (hdw->ctl_write_urb->status != -ESHUTDOWN) &&
		    (hdw->ctl_write_urb->status != -ECONNRESET)) {
			/* USB subsystem is reporting some kind of failure
			   on the write */
			status = hdw->ctl_write_urb->status;
			if (!probe_fl) {
				pvr2_trace(PVR2_TRACE_ERROR_LEGS,
					   "control-write URB failure,"
					   " status=%d",
					   status);
			}
			goto done;
		}
		if (hdw->ctl_write_urb->actual_length < write_len) {
			/* Failed to write enough data */
			status = -EIO;
			if (!probe_fl) {
				pvr2_trace(PVR2_TRACE_ERROR_LEGS,
					   "control-write URB short,"
					   " expected=%d got=%d",
					   write_len,
					   hdw->ctl_write_urb->actual_length);
			}
			goto done;
		}
	}
	if (read_len) {
		/* Validate results of read request */
		if ((hdw->ctl_read_urb->status != 0) &&
		    (hdw->ctl_read_urb->status != -ENOENT) &&
		    (hdw->ctl_read_urb->status != -ESHUTDOWN) &&
		    (hdw->ctl_read_urb->status != -ECONNRESET)) {
			/* USB subsystem is reporting some kind of failure
			   on the read */
			status = hdw->ctl_read_urb->status;
			if (!probe_fl) {
				pvr2_trace(PVR2_TRACE_ERROR_LEGS,
					   "control-read URB failure,"
					   " status=%d",
					   status);
			}
			goto done;
		}
		if (hdw->ctl_read_urb->actual_length < read_len) {
			/* Failed to read enough data */
			status = -EIO;
			if (!probe_fl) {
				pvr2_trace(PVR2_TRACE_ERROR_LEGS,
					   "control-read URB short,"
					   " expected=%d got=%d",
					   read_len,
					   hdw->ctl_read_urb->actual_length);
			}
			goto done;
		}
		/* Transfer retrieved data out from internal buffer */
		for (idx = 0; idx < read_len; idx++) {
			((unsigned char *)read_data)[idx] =
				hdw->ctl_read_buffer[idx];
		}
	}

 done:

	hdw->cmd_debug_state = 0;
	if ((status < 0) && (!probe_fl)) {
3920
		pvr2_hdw_render_useless(hdw);
3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934
	}
	return status;
}


int pvr2_send_request(struct pvr2_hdw *hdw,
		      void *write_data,unsigned int write_len,
		      void *read_data,unsigned int read_len)
{
	return pvr2_send_request_ex(hdw,HZ*4,0,
				    write_data,write_len,
				    read_data,read_len);
}

3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995

static int pvr2_issue_simple_cmd(struct pvr2_hdw *hdw,u32 cmdcode)
{
	int ret;
	unsigned int cnt = 1;
	unsigned int args = 0;
	LOCK_TAKE(hdw->ctl_lock);
	hdw->cmd_buffer[0] = cmdcode & 0xffu;
	args = (cmdcode >> 8) & 0xffu;
	args = (args > 2) ? 2 : args;
	if (args) {
		cnt += args;
		hdw->cmd_buffer[1] = (cmdcode >> 16) & 0xffu;
		if (args > 1) {
			hdw->cmd_buffer[2] = (cmdcode >> 24) & 0xffu;
		}
	}
	if (pvrusb2_debug & PVR2_TRACE_INIT) {
		unsigned int idx;
		unsigned int ccnt,bcnt;
		char tbuf[50];
		cmdcode &= 0xffu;
		bcnt = 0;
		ccnt = scnprintf(tbuf+bcnt,
				 sizeof(tbuf)-bcnt,
				 "Sending FX2 command 0x%x",cmdcode);
		bcnt += ccnt;
		for (idx = 0; idx < ARRAY_SIZE(pvr2_fx2cmd_desc); idx++) {
			if (pvr2_fx2cmd_desc[idx].id == cmdcode) {
				ccnt = scnprintf(tbuf+bcnt,
						 sizeof(tbuf)-bcnt,
						 " \"%s\"",
						 pvr2_fx2cmd_desc[idx].desc);
				bcnt += ccnt;
				break;
			}
		}
		if (args) {
			ccnt = scnprintf(tbuf+bcnt,
					 sizeof(tbuf)-bcnt,
					 " (%u",hdw->cmd_buffer[1]);
			bcnt += ccnt;
			if (args > 1) {
				ccnt = scnprintf(tbuf+bcnt,
						 sizeof(tbuf)-bcnt,
						 ",%u",hdw->cmd_buffer[2]);
				bcnt += ccnt;
			}
			ccnt = scnprintf(tbuf+bcnt,
					 sizeof(tbuf)-bcnt,
					 ")");
			bcnt += ccnt;
		}
		pvr2_trace(PVR2_TRACE_INIT,"%.*s",bcnt,tbuf);
	}
	ret = pvr2_send_request(hdw,hdw->cmd_buffer,cnt,NULL,0);
	LOCK_GIVE(hdw->ctl_lock);
	return ret;
}


3996 3997 3998 3999 4000 4001
int pvr2_write_register(struct pvr2_hdw *hdw, u16 reg, u32 data)
{
	int ret;

	LOCK_TAKE(hdw->ctl_lock);

4002
	hdw->cmd_buffer[0] = FX2CMD_REG_WRITE;  /* write register prefix */
4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016
	PVR2_DECOMPOSE_LE(hdw->cmd_buffer,1,data);
	hdw->cmd_buffer[5] = 0;
	hdw->cmd_buffer[6] = (reg >> 8) & 0xff;
	hdw->cmd_buffer[7] = reg & 0xff;


	ret = pvr2_send_request(hdw, hdw->cmd_buffer, 8, hdw->cmd_buffer, 0);

	LOCK_GIVE(hdw->ctl_lock);

	return ret;
}


4017
static int pvr2_read_register(struct pvr2_hdw *hdw, u16 reg, u32 *data)
4018 4019 4020 4021 4022
{
	int ret = 0;

	LOCK_TAKE(hdw->ctl_lock);

4023
	hdw->cmd_buffer[0] = FX2CMD_REG_READ;  /* read register prefix */
4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040
	hdw->cmd_buffer[1] = 0;
	hdw->cmd_buffer[2] = 0;
	hdw->cmd_buffer[3] = 0;
	hdw->cmd_buffer[4] = 0;
	hdw->cmd_buffer[5] = 0;
	hdw->cmd_buffer[6] = (reg >> 8) & 0xff;
	hdw->cmd_buffer[7] = reg & 0xff;

	ret |= pvr2_send_request(hdw, hdw->cmd_buffer, 8, hdw->cmd_buffer, 4);
	*data = PVR2_COMPOSE_LE(hdw->cmd_buffer,0);

	LOCK_GIVE(hdw->ctl_lock);

	return ret;
}


4041
void pvr2_hdw_render_useless(struct pvr2_hdw *hdw)
4042 4043
{
	if (!hdw->flag_ok) return;
4044 4045
	pvr2_trace(PVR2_TRACE_ERROR_LEGS,
		   "Device being rendered inoperable");
4046
	if (hdw->vid_stream) {
4047
		pvr2_stream_setup(hdw->vid_stream,NULL,0,0);
4048
	}
4049 4050 4051
	hdw->flag_ok = 0;
	trace_stbit("flag_ok",hdw->flag_ok);
	pvr2_hdw_state_sched(hdw);
4052 4053 4054 4055 4056 4057 4058
}


void pvr2_hdw_device_reset(struct pvr2_hdw *hdw)
{
	int ret;
	pvr2_trace(PVR2_TRACE_INIT,"Performing a device reset...");
4059
	ret = usb_lock_device_for_reset(hdw->usb_dev,NULL);
4060
	if (ret == 0) {
4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102
		ret = usb_reset_device(hdw->usb_dev);
		usb_unlock_device(hdw->usb_dev);
	} else {
		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
			   "Failed to lock USB device ret=%d",ret);
	}
	if (init_pause_msec) {
		pvr2_trace(PVR2_TRACE_INFO,
			   "Waiting %u msec for hardware to settle",
			   init_pause_msec);
		msleep(init_pause_msec);
	}

}


void pvr2_hdw_cpureset_assert(struct pvr2_hdw *hdw,int val)
{
	char da[1];
	unsigned int pipe;
	int ret;

	if (!hdw->usb_dev) return;

	pvr2_trace(PVR2_TRACE_INIT,"cpureset_assert(%d)",val);

	da[0] = val ? 0x01 : 0x00;

	/* Write the CPUCS register on the 8051.  The lsb of the register
	   is the reset bit; a 1 asserts reset while a 0 clears it. */
	pipe = usb_sndctrlpipe(hdw->usb_dev, 0);
	ret = usb_control_msg(hdw->usb_dev,pipe,0xa0,0x40,0xe600,0,da,1,HZ);
	if (ret < 0) {
		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
			   "cpureset_assert(%d) error=%d",val,ret);
		pvr2_hdw_render_useless(hdw);
	}
}


int pvr2_hdw_cmd_deep_reset(struct pvr2_hdw *hdw)
{
4103
	return pvr2_issue_simple_cmd(hdw,FX2CMD_DEEP_RESET);
4104 4105 4106
}


4107 4108
int pvr2_hdw_cmd_powerup(struct pvr2_hdw *hdw)
{
4109
	return pvr2_issue_simple_cmd(hdw,FX2CMD_POWER_ON);
4110 4111
}

4112

4113 4114
int pvr2_hdw_cmd_powerdown(struct pvr2_hdw *hdw)
{
4115
	return pvr2_issue_simple_cmd(hdw,FX2CMD_POWER_OFF);
4116 4117
}

4118 4119 4120

int pvr2_hdw_cmd_decoder_reset(struct pvr2_hdw *hdw)
{
4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131
	pvr2_trace(PVR2_TRACE_INIT,
		   "Requesting decoder reset");
	if (hdw->decoder_ctrl) {
		if (!hdw->decoder_ctrl->force_reset) {
			pvr2_trace(PVR2_TRACE_INIT,
				   "Unable to reset decoder: not implemented");
			return -ENOTTY;
		}
		hdw->decoder_ctrl->force_reset(hdw->decoder_ctrl->ctxt);
		return 0;
	} else {
4132
	}
4133 4134 4135 4136
	if (hdw->decoder_client_id) {
		v4l2_device_call_all(&hdw->v4l2_dev, hdw->decoder_client_id,
				     core, reset, 0);
		return 0;
4137 4138
	}
	pvr2_trace(PVR2_TRACE_INIT,
4139 4140
		   "Unable to reset decoder: nothing attached");
	return -ENOTTY;
4141 4142 4143
}


4144
static int pvr2_hdw_cmd_hcw_demod_reset(struct pvr2_hdw *hdw, int onoff)
4145
{
4146 4147 4148 4149 4150
	hdw->flag_ok = !0;
	return pvr2_issue_simple_cmd(hdw,
				     FX2CMD_HCW_DEMOD_RESETIN |
				     (1 << 8) |
				     ((onoff ? 1 : 0) << 16));
4151 4152 4153
}


4154
static int pvr2_hdw_cmd_onair_fe_power_ctrl(struct pvr2_hdw *hdw, int onoff)
4155
{
4156 4157 4158 4159
	hdw->flag_ok = !0;
	return pvr2_issue_simple_cmd(hdw,(onoff ?
					  FX2CMD_ONAIR_DTV_POWER_ON :
					  FX2CMD_ONAIR_DTV_POWER_OFF));
4160 4161
}

4162 4163 4164

static int pvr2_hdw_cmd_onair_digital_path_ctrl(struct pvr2_hdw *hdw,
						int onoff)
4165
{
4166 4167 4168
	return pvr2_issue_simple_cmd(hdw,(onoff ?
					  FX2CMD_ONAIR_DTV_STREAMING_ON :
					  FX2CMD_ONAIR_DTV_STREAMING_OFF));
4169 4170
}

4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197

static void pvr2_hdw_cmd_modeswitch(struct pvr2_hdw *hdw,int digitalFl)
{
	int cmode;
	/* Compare digital/analog desired setting with current setting.  If
	   they don't match, fix it... */
	cmode = (digitalFl ? PVR2_PATHWAY_DIGITAL : PVR2_PATHWAY_ANALOG);
	if (cmode == hdw->pathway_state) {
		/* They match; nothing to do */
		return;
	}

	switch (hdw->hdw_desc->digital_control_scheme) {
	case PVR2_DIGITAL_SCHEME_HAUPPAUGE:
		pvr2_hdw_cmd_hcw_demod_reset(hdw,digitalFl);
		if (cmode == PVR2_PATHWAY_ANALOG) {
			/* If moving to analog mode, also force the decoder
			   to reset.  If no decoder is attached, then it's
			   ok to ignore this because if/when the decoder
			   attaches, it will reset itself at that time. */
			pvr2_hdw_cmd_decoder_reset(hdw);
		}
		break;
	case PVR2_DIGITAL_SCHEME_ONAIR:
		/* Supposedly we should always have the power on whether in
		   digital or analog mode.  But for now do what appears to
		   work... */
4198
		pvr2_hdw_cmd_onair_fe_power_ctrl(hdw,digitalFl);
4199 4200 4201 4202
		break;
	default: break;
	}

4203
	pvr2_hdw_untrip_unlocked(hdw);
4204 4205 4206 4207
	hdw->pathway_state = cmode;
}


4208
static void pvr2_led_ctrl_hauppauge(struct pvr2_hdw *hdw, int onoff)
4209 4210 4211 4212 4213 4214 4215
{
	/* change some GPIO data
	 *
	 * note: bit d7 of dir appears to control the LED,
	 * so we shut it off here.
	 *
	 */
4216
	if (onoff) {
4217
		pvr2_hdw_gpio_chg_dir(hdw, 0xffffffff, 0x00000481);
4218
	} else {
4219
		pvr2_hdw_gpio_chg_dir(hdw, 0xffffffff, 0x00000401);
4220
	}
4221
	pvr2_hdw_gpio_chg_out(hdw, 0xffffffff, 0x00000000);
4222
}
4223

4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249

typedef void (*led_method_func)(struct pvr2_hdw *,int);

static led_method_func led_methods[] = {
	[PVR2_LED_SCHEME_HAUPPAUGE] = pvr2_led_ctrl_hauppauge,
};


/* Toggle LED */
static void pvr2_led_ctrl(struct pvr2_hdw *hdw,int onoff)
{
	unsigned int scheme_id;
	led_method_func fp;

	if ((!onoff) == (!hdw->led_on)) return;

	hdw->led_on = onoff != 0;

	scheme_id = hdw->hdw_desc->led_scheme;
	if (scheme_id < ARRAY_SIZE(led_methods)) {
		fp = led_methods[scheme_id];
	} else {
		fp = NULL;
	}

	if (fp) (*fp)(hdw,onoff);
4250 4251 4252
}


4253
/* Stop / start video stream transport */
4254
static int pvr2_hdw_cmd_usbstream(struct pvr2_hdw *hdw,int runFl)
4255
{
4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291
	int ret;

	/* If we're in analog mode, then just issue the usual analog
	   command. */
	if (hdw->pathway_state == PVR2_PATHWAY_ANALOG) {
		return pvr2_issue_simple_cmd(hdw,
					     (runFl ?
					      FX2CMD_STREAMING_ON :
					      FX2CMD_STREAMING_OFF));
		/*Note: Not reached */
	}

	if (hdw->pathway_state != PVR2_PATHWAY_DIGITAL) {
		/* Whoops, we don't know what mode we're in... */
		return -EINVAL;
	}

	/* To get here we have to be in digital mode.  The mechanism here
	   is unfortunately different for different vendors.  So we switch
	   on the device's digital scheme attribute in order to figure out
	   what to do. */
	switch (hdw->hdw_desc->digital_control_scheme) {
	case PVR2_DIGITAL_SCHEME_HAUPPAUGE:
		return pvr2_issue_simple_cmd(hdw,
					     (runFl ?
					      FX2CMD_HCW_DTV_STREAMING_ON :
					      FX2CMD_HCW_DTV_STREAMING_OFF));
	case PVR2_DIGITAL_SCHEME_ONAIR:
		ret = pvr2_issue_simple_cmd(hdw,
					    (runFl ?
					     FX2CMD_STREAMING_ON :
					     FX2CMD_STREAMING_OFF));
		if (ret) return ret;
		return pvr2_hdw_cmd_onair_digital_path_ctrl(hdw,runFl);
	default:
		return -EINVAL;
4292
	}
4293 4294 4295
}


4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308
/* Evaluate whether or not state_pathway_ok can change */
static int state_eval_pathway_ok(struct pvr2_hdw *hdw)
{
	if (hdw->state_pathway_ok) {
		/* Nothing to do if pathway is already ok */
		return 0;
	}
	if (!hdw->state_pipeline_idle) {
		/* Not allowed to change anything if pipeline is not idle */
		return 0;
	}
	pvr2_hdw_cmd_modeswitch(hdw,hdw->input_val == PVR2_CVAL_INPUT_DTV);
	hdw->state_pathway_ok = !0;
4309
	trace_stbit("state_pathway_ok",hdw->state_pathway_ok);
4310 4311 4312 4313
	return !0;
}


4314 4315 4316 4317 4318 4319 4320 4321 4322
/* Evaluate whether or not state_encoder_ok can change */
static int state_eval_encoder_ok(struct pvr2_hdw *hdw)
{
	if (hdw->state_encoder_ok) return 0;
	if (hdw->flag_tripped) return 0;
	if (hdw->state_encoder_run) return 0;
	if (hdw->state_encoder_config) return 0;
	if (hdw->state_decoder_run) return 0;
	if (hdw->state_usbstream_run) return 0;
4323 4324 4325 4326 4327 4328
	if (hdw->pathway_state == PVR2_PATHWAY_DIGITAL) {
		if (!hdw->hdw_desc->flag_digital_requires_cx23416) return 0;
	} else if (hdw->pathway_state != PVR2_PATHWAY_ANALOG) {
		return 0;
	}

4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353
	if (pvr2_upload_firmware2(hdw) < 0) {
		hdw->flag_tripped = !0;
		trace_stbit("flag_tripped",hdw->flag_tripped);
		return !0;
	}
	hdw->state_encoder_ok = !0;
	trace_stbit("state_encoder_ok",hdw->state_encoder_ok);
	return !0;
}


/* Evaluate whether or not state_encoder_config can change */
static int state_eval_encoder_config(struct pvr2_hdw *hdw)
{
	if (hdw->state_encoder_config) {
		if (hdw->state_encoder_ok) {
			if (hdw->state_pipeline_req &&
			    !hdw->state_pipeline_pause) return 0;
		}
		hdw->state_encoder_config = 0;
		hdw->state_encoder_waitok = 0;
		trace_stbit("state_encoder_waitok",hdw->state_encoder_waitok);
		/* paranoia - solve race if timer just completed */
		del_timer_sync(&hdw->encoder_wait_timer);
	} else {
4354 4355 4356
		if (!hdw->state_pathway_ok ||
		    (hdw->pathway_state != PVR2_PATHWAY_ANALOG) ||
		    !hdw->state_encoder_ok ||
4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387
		    !hdw->state_pipeline_idle ||
		    hdw->state_pipeline_pause ||
		    !hdw->state_pipeline_req ||
		    !hdw->state_pipeline_config) {
			/* We must reset the enforced wait interval if
			   anything has happened that might have disturbed
			   the encoder.  This should be a rare case. */
			if (timer_pending(&hdw->encoder_wait_timer)) {
				del_timer_sync(&hdw->encoder_wait_timer);
			}
			if (hdw->state_encoder_waitok) {
				/* Must clear the state - therefore we did
				   something to a state bit and must also
				   return true. */
				hdw->state_encoder_waitok = 0;
				trace_stbit("state_encoder_waitok",
					    hdw->state_encoder_waitok);
				return !0;
			}
			return 0;
		}
		if (!hdw->state_encoder_waitok) {
			if (!timer_pending(&hdw->encoder_wait_timer)) {
				/* waitok flag wasn't set and timer isn't
				   running.  Check flag once more to avoid
				   a race then start the timer.  This is
				   the point when we measure out a minimal
				   quiet interval before doing something to
				   the encoder. */
				if (!hdw->state_encoder_waitok) {
					hdw->encoder_wait_timer.expires =
4388 4389 4390
						jiffies +
						(HZ * TIME_MSEC_ENCODER_WAIT
						 / 1000);
4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406
					add_timer(&hdw->encoder_wait_timer);
				}
			}
			/* We can't continue until we know we have been
			   quiet for the interval measured by this
			   timer. */
			return 0;
		}
		pvr2_encoder_configure(hdw);
		if (hdw->state_encoder_ok) hdw->state_encoder_config = !0;
	}
	trace_stbit("state_encoder_config",hdw->state_encoder_config);
	return !0;
}


4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497
/* Return true if the encoder should not be running. */
static int state_check_disable_encoder_run(struct pvr2_hdw *hdw)
{
	if (!hdw->state_encoder_ok) {
		/* Encoder isn't healthy at the moment, so stop it. */
		return !0;
	}
	if (!hdw->state_pathway_ok) {
		/* Mode is not understood at the moment (i.e. it wants to
		   change), so encoder must be stopped. */
		return !0;
	}

	switch (hdw->pathway_state) {
	case PVR2_PATHWAY_ANALOG:
		if (!hdw->state_decoder_run) {
			/* We're in analog mode and the decoder is not
			   running; thus the encoder should be stopped as
			   well. */
			return !0;
		}
		break;
	case PVR2_PATHWAY_DIGITAL:
		if (hdw->state_encoder_runok) {
			/* This is a funny case.  We're in digital mode so
			   really the encoder should be stopped.  However
			   if it really is running, only kill it after
			   runok has been set.  This gives a chance for the
			   onair quirk to function (encoder must run
			   briefly first, at least once, before onair
			   digital streaming can work). */
			return !0;
		}
		break;
	default:
		/* Unknown mode; so encoder should be stopped. */
		return !0;
	}

	/* If we get here, we haven't found a reason to stop the
	   encoder. */
	return 0;
}


/* Return true if the encoder should be running. */
static int state_check_enable_encoder_run(struct pvr2_hdw *hdw)
{
	if (!hdw->state_encoder_ok) {
		/* Don't run the encoder if it isn't healthy... */
		return 0;
	}
	if (!hdw->state_pathway_ok) {
		/* Don't run the encoder if we don't (yet) know what mode
		   we need to be in... */
		return 0;
	}

	switch (hdw->pathway_state) {
	case PVR2_PATHWAY_ANALOG:
		if (hdw->state_decoder_run) {
			/* In analog mode, if the decoder is running, then
			   run the encoder. */
			return !0;
		}
		break;
	case PVR2_PATHWAY_DIGITAL:
		if ((hdw->hdw_desc->digital_control_scheme ==
		     PVR2_DIGITAL_SCHEME_ONAIR) &&
		    !hdw->state_encoder_runok) {
			/* This is a quirk.  OnAir hardware won't stream
			   digital until the encoder has been run at least
			   once, for a minimal period of time (empiricially
			   measured to be 1/4 second).  So if we're on
			   OnAir hardware and the encoder has never been
			   run at all, then start the encoder.  Normal
			   state machine logic in the driver will
			   automatically handle the remaining bits. */
			return !0;
		}
		break;
	default:
		/* For completeness (unknown mode; encoder won't run ever) */
		break;
	}
	/* If we get here, then we haven't found any reason to run the
	   encoder, so don't run it. */
	return 0;
}


4498 4499 4500 4501
/* Evaluate whether or not state_encoder_run can change */
static int state_eval_encoder_run(struct pvr2_hdw *hdw)
{
	if (hdw->state_encoder_run) {
4502
		if (!state_check_disable_encoder_run(hdw)) return 0;
4503
		if (hdw->state_encoder_ok) {
4504
			del_timer_sync(&hdw->encoder_run_timer);
4505 4506 4507 4508
			if (pvr2_encoder_stop(hdw) < 0) return !0;
		}
		hdw->state_encoder_run = 0;
	} else {
4509
		if (!state_check_enable_encoder_run(hdw)) return 0;
4510 4511
		if (pvr2_encoder_start(hdw) < 0) return !0;
		hdw->state_encoder_run = !0;
4512 4513
		if (!hdw->state_encoder_runok) {
			hdw->encoder_run_timer.expires =
4514
				jiffies + (HZ * TIME_MSEC_ENCODER_OK / 1000);
4515 4516
			add_timer(&hdw->encoder_run_timer);
		}
4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544
	}
	trace_stbit("state_encoder_run",hdw->state_encoder_run);
	return !0;
}


/* Timeout function for quiescent timer. */
static void pvr2_hdw_quiescent_timeout(unsigned long data)
{
	struct pvr2_hdw *hdw = (struct pvr2_hdw *)data;
	hdw->state_decoder_quiescent = !0;
	trace_stbit("state_decoder_quiescent",hdw->state_decoder_quiescent);
	hdw->state_stale = !0;
	queue_work(hdw->workqueue,&hdw->workpoll);
}


/* Timeout function for encoder wait timer. */
static void pvr2_hdw_encoder_wait_timeout(unsigned long data)
{
	struct pvr2_hdw *hdw = (struct pvr2_hdw *)data;
	hdw->state_encoder_waitok = !0;
	trace_stbit("state_encoder_waitok",hdw->state_encoder_waitok);
	hdw->state_stale = !0;
	queue_work(hdw->workqueue,&hdw->workpoll);
}


4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557
/* Timeout function for encoder run timer. */
static void pvr2_hdw_encoder_run_timeout(unsigned long data)
{
	struct pvr2_hdw *hdw = (struct pvr2_hdw *)data;
	if (!hdw->state_encoder_runok) {
		hdw->state_encoder_runok = !0;
		trace_stbit("state_encoder_runok",hdw->state_encoder_runok);
		hdw->state_stale = !0;
		queue_work(hdw->workqueue,&hdw->workpoll);
	}
}


4558 4559 4560 4561 4562 4563
/* Evaluate whether or not state_decoder_run can change */
static int state_eval_decoder_run(struct pvr2_hdw *hdw)
{
	if (hdw->state_decoder_run) {
		if (hdw->state_encoder_ok) {
			if (hdw->state_pipeline_req &&
4564 4565
			    !hdw->state_pipeline_pause &&
			    hdw->state_pathway_ok) return 0;
4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588
		}
		if (!hdw->flag_decoder_missed) {
			pvr2_decoder_enable(hdw,0);
		}
		hdw->state_decoder_quiescent = 0;
		hdw->state_decoder_run = 0;
		/* paranoia - solve race if timer just completed */
		del_timer_sync(&hdw->quiescent_timer);
	} else {
		if (!hdw->state_decoder_quiescent) {
			if (!timer_pending(&hdw->quiescent_timer)) {
				/* We don't do something about the
				   quiescent timer until right here because
				   we also want to catch cases where the
				   decoder was already not running (like
				   after initialization) as opposed to
				   knowing that we had just stopped it.
				   The second flag check is here to cover a
				   race - the timer could have run and set
				   this flag just after the previous check
				   but before we did the pending check. */
				if (!hdw->state_decoder_quiescent) {
					hdw->quiescent_timer.expires =
4589 4590 4591
						jiffies +
						(HZ * TIME_MSEC_DECODER_WAIT
						 / 1000);
4592 4593 4594 4595 4596 4597 4598 4599
					add_timer(&hdw->quiescent_timer);
				}
			}
			/* Don't allow decoder to start again until it has
			   been quiesced first.  This little detail should
			   hopefully further stabilize the encoder. */
			return 0;
		}
4600 4601 4602
		if (!hdw->state_pathway_ok ||
		    (hdw->pathway_state != PVR2_PATHWAY_ANALOG) ||
		    !hdw->state_pipeline_req ||
4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622
		    hdw->state_pipeline_pause ||
		    !hdw->state_pipeline_config ||
		    !hdw->state_encoder_config ||
		    !hdw->state_encoder_ok) return 0;
		del_timer_sync(&hdw->quiescent_timer);
		if (hdw->flag_decoder_missed) return 0;
		if (pvr2_decoder_enable(hdw,!0) < 0) return 0;
		hdw->state_decoder_quiescent = 0;
		hdw->state_decoder_run = !0;
	}
	trace_stbit("state_decoder_quiescent",hdw->state_decoder_quiescent);
	trace_stbit("state_decoder_run",hdw->state_decoder_run);
	return !0;
}


/* Evaluate whether or not state_usbstream_run can change */
static int state_eval_usbstream_run(struct pvr2_hdw *hdw)
{
	if (hdw->state_usbstream_run) {
4623
		int fl = !0;
4624
		if (hdw->pathway_state == PVR2_PATHWAY_ANALOG) {
4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635
			fl = (hdw->state_encoder_ok &&
			      hdw->state_encoder_run);
		} else if ((hdw->pathway_state == PVR2_PATHWAY_DIGITAL) &&
			   (hdw->hdw_desc->flag_digital_requires_cx23416)) {
			fl = hdw->state_encoder_ok;
		}
		if (fl &&
		    hdw->state_pipeline_req &&
		    !hdw->state_pipeline_pause &&
		    hdw->state_pathway_ok) {
			return 0;
4636 4637 4638 4639
		}
		pvr2_hdw_cmd_usbstream(hdw,0);
		hdw->state_usbstream_run = 0;
	} else {
4640 4641 4642 4643 4644 4645
		if (!hdw->state_pipeline_req ||
		    hdw->state_pipeline_pause ||
		    !hdw->state_pathway_ok) return 0;
		if (hdw->pathway_state == PVR2_PATHWAY_ANALOG) {
			if (!hdw->state_encoder_ok ||
			    !hdw->state_encoder_run) return 0;
4646 4647 4648
		} else if ((hdw->pathway_state == PVR2_PATHWAY_DIGITAL) &&
			   (hdw->hdw_desc->flag_digital_requires_cx23416)) {
			if (!hdw->state_encoder_ok) return 0;
4649 4650 4651 4652 4653 4654 4655 4656 4657 4658
			if (hdw->state_encoder_run) return 0;
			if (hdw->hdw_desc->digital_control_scheme ==
			    PVR2_DIGITAL_SCHEME_ONAIR) {
				/* OnAir digital receivers won't stream
				   unless the analog encoder has run first.
				   Why?  I have no idea.  But don't even
				   try until we know the analog side is
				   known to have run. */
				if (!hdw->state_encoder_runok) return 0;
			}
4659
		}
4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704
		if (pvr2_hdw_cmd_usbstream(hdw,!0) < 0) return 0;
		hdw->state_usbstream_run = !0;
	}
	trace_stbit("state_usbstream_run",hdw->state_usbstream_run);
	return !0;
}


/* Attempt to configure pipeline, if needed */
static int state_eval_pipeline_config(struct pvr2_hdw *hdw)
{
	if (hdw->state_pipeline_config ||
	    hdw->state_pipeline_pause) return 0;
	pvr2_hdw_commit_execute(hdw);
	return !0;
}


/* Update pipeline idle and pipeline pause tracking states based on other
   inputs.  This must be called whenever the other relevant inputs have
   changed. */
static int state_update_pipeline_state(struct pvr2_hdw *hdw)
{
	unsigned int st;
	int updatedFl = 0;
	/* Update pipeline state */
	st = !(hdw->state_encoder_run ||
	       hdw->state_decoder_run ||
	       hdw->state_usbstream_run ||
	       (!hdw->state_decoder_quiescent));
	if (!st != !hdw->state_pipeline_idle) {
		hdw->state_pipeline_idle = st;
		updatedFl = !0;
	}
	if (hdw->state_pipeline_idle && hdw->state_pipeline_pause) {
		hdw->state_pipeline_pause = 0;
		updatedFl = !0;
	}
	return updatedFl;
}


typedef int (*state_eval_func)(struct pvr2_hdw *);

/* Set of functions to be run to evaluate various states in the driver. */
4705
static const state_eval_func eval_funcs[] = {
4706
	state_eval_pathway_ok,
4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753
	state_eval_pipeline_config,
	state_eval_encoder_ok,
	state_eval_encoder_config,
	state_eval_decoder_run,
	state_eval_encoder_run,
	state_eval_usbstream_run,
};


/* Process various states and return true if we did anything interesting. */
static int pvr2_hdw_state_update(struct pvr2_hdw *hdw)
{
	unsigned int i;
	int state_updated = 0;
	int check_flag;

	if (!hdw->state_stale) return 0;
	if ((hdw->fw1_state != FW1_STATE_OK) ||
	    !hdw->flag_ok) {
		hdw->state_stale = 0;
		return !0;
	}
	/* This loop is the heart of the entire driver.  It keeps trying to
	   evaluate various bits of driver state until nothing changes for
	   one full iteration.  Each "bit of state" tracks some global
	   aspect of the driver, e.g. whether decoder should run, if
	   pipeline is configured, usb streaming is on, etc.  We separately
	   evaluate each of those questions based on other driver state to
	   arrive at the correct running configuration. */
	do {
		check_flag = 0;
		state_update_pipeline_state(hdw);
		/* Iterate over each bit of state */
		for (i = 0; (i<ARRAY_SIZE(eval_funcs)) && hdw->flag_ok; i++) {
			if ((*eval_funcs[i])(hdw)) {
				check_flag = !0;
				state_updated = !0;
				state_update_pipeline_state(hdw);
			}
		}
	} while (check_flag && hdw->flag_ok);
	hdw->state_stale = 0;
	trace_stbit("state_stale",hdw->state_stale);
	return state_updated;
}


4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771
static unsigned int print_input_mask(unsigned int msk,
				     char *buf,unsigned int acnt)
{
	unsigned int idx,ccnt;
	unsigned int tcnt = 0;
	for (idx = 0; idx < ARRAY_SIZE(control_values_input); idx++) {
		if (!((1 << idx) & msk)) continue;
		ccnt = scnprintf(buf+tcnt,
				 acnt-tcnt,
				 "%s%s",
				 (tcnt ? ", " : ""),
				 control_values_input[idx]);
		tcnt += ccnt;
	}
	return tcnt;
}


4772 4773 4774 4775 4776 4777 4778 4779 4780 4781
static const char *pvr2_pathway_state_name(int id)
{
	switch (id) {
	case PVR2_PATHWAY_ANALOG: return "analog";
	case PVR2_PATHWAY_DIGITAL: return "digital";
	default: return "unknown";
	}
}


4782 4783 4784 4785 4786 4787 4788
static unsigned int pvr2_hdw_report_unlocked(struct pvr2_hdw *hdw,int which,
					     char *buf,unsigned int acnt)
{
	switch (which) {
	case 0:
		return scnprintf(
			buf,acnt,
4789
			"driver:%s%s%s%s%s <mode=%s>",
4790 4791 4792 4793 4794
			(hdw->flag_ok ? " <ok>" : " <fail>"),
			(hdw->flag_init_ok ? " <init>" : " <uninitialized>"),
			(hdw->flag_disconnected ? " <disconnected>" :
			 " <connected>"),
			(hdw->flag_tripped ? " <tripped>" : ""),
4795 4796 4797
			(hdw->flag_decoder_missed ? " <no decoder>" : ""),
			pvr2_pathway_state_name(hdw->pathway_state));

4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809
	case 1:
		return scnprintf(
			buf,acnt,
			"pipeline:%s%s%s%s",
			(hdw->state_pipeline_idle ? " <idle>" : ""),
			(hdw->state_pipeline_config ?
			 " <configok>" : " <stale>"),
			(hdw->state_pipeline_req ? " <req>" : ""),
			(hdw->state_pipeline_pause ? " <pause>" : ""));
	case 2:
		return scnprintf(
			buf,acnt,
4810
			"worker:%s%s%s%s%s%s%s",
4811 4812 4813 4814 4815 4816 4817 4818 4819
			(hdw->state_decoder_run ?
			 " <decode:run>" :
			 (hdw->state_decoder_quiescent ?
			  "" : " <decode:stop>")),
			(hdw->state_decoder_quiescent ?
			 " <decode:quiescent>" : ""),
			(hdw->state_encoder_ok ?
			 "" : " <encode:init>"),
			(hdw->state_encoder_run ?
4820 4821 4822 4823 4824 4825
			 (hdw->state_encoder_runok ?
			  " <encode:run>" :
			  " <encode:firstrun>") :
			 (hdw->state_encoder_runok ?
			  " <encode:stop>" :
			  " <encode:virgin>")),
4826 4827 4828
			(hdw->state_encoder_config ?
			 " <encode:configok>" :
			 (hdw->state_encoder_waitok ?
4829
			  "" : " <encode:waitok>")),
4830
			(hdw->state_usbstream_run ?
4831 4832
			 " <usb:run>" : " <usb:stop>"),
			(hdw->state_pathway_ok ?
4833
			 " <pathway:ok>" : ""));
4834 4835 4836 4837 4838
	case 3:
		return scnprintf(
			buf,acnt,
			"state: %s",
			pvr2_get_state_name(hdw->master_state));
4839
	case 4: {
4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861
		unsigned int tcnt = 0;
		unsigned int ccnt;

		ccnt = scnprintf(buf,
				 acnt,
				 "Hardware supported inputs: ");
		tcnt += ccnt;
		tcnt += print_input_mask(hdw->input_avail_mask,
					 buf+tcnt,
					 acnt-tcnt);
		if (hdw->input_avail_mask != hdw->input_allowed_mask) {
			ccnt = scnprintf(buf+tcnt,
					 acnt-tcnt,
					 "; allowed inputs: ");
			tcnt += ccnt;
			tcnt += print_input_mask(hdw->input_allowed_mask,
						 buf+tcnt,
						 acnt-tcnt);
		}
		return tcnt;
	}
	case 5: {
4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878
		struct pvr2_stream_stats stats;
		if (!hdw->vid_stream) break;
		pvr2_stream_get_stats(hdw->vid_stream,
				      &stats,
				      0);
		return scnprintf(
			buf,acnt,
			"Bytes streamed=%u"
			" URBs: queued=%u idle=%u ready=%u"
			" processed=%u failed=%u",
			stats.bytes_processed,
			stats.buffers_in_queue,
			stats.buffers_in_idle,
			stats.buffers_in_ready,
			stats.buffers_processed,
			stats.buffers_failed);
	}
4879 4880 4881 4882 4883 4884 4885 4886
	case 6: {
		struct v4l2_subdev *sd;
		unsigned int tcnt = 0;
		unsigned int ccnt;
		const char *p;
		unsigned int id;
		ccnt = scnprintf(buf,
				 acnt,
4887
				 "Associated v4l2_subdev drivers:");
4888 4889 4890 4891 4892 4893 4894
		tcnt += ccnt;
		v4l2_device_for_each_subdev(sd, &hdw->v4l2_dev) {
			id = sd->grp_id;
			p = NULL;
			if (id < ARRAY_SIZE(module_names)) {
				p = module_names[id];
			}
4895 4896 4897 4898 4899 4900 4901 4902 4903 4904
			if (p) {
				ccnt = scnprintf(buf + tcnt,
						 acnt - tcnt,
						 " %s", p);
			} else {
				ccnt = scnprintf(buf + tcnt,
						 acnt - tcnt,
						 " (unknown id=%u)", id);
			}
			tcnt += ccnt;
4905 4906 4907
		}
		return tcnt;
	}
4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952
	default: break;
	}
	return 0;
}


unsigned int pvr2_hdw_state_report(struct pvr2_hdw *hdw,
				   char *buf,unsigned int acnt)
{
	unsigned int bcnt,ccnt,idx;
	bcnt = 0;
	LOCK_TAKE(hdw->big_lock);
	for (idx = 0; ; idx++) {
		ccnt = pvr2_hdw_report_unlocked(hdw,idx,buf,acnt);
		if (!ccnt) break;
		bcnt += ccnt; acnt -= ccnt; buf += ccnt;
		if (!acnt) break;
		buf[0] = '\n'; ccnt = 1;
		bcnt += ccnt; acnt -= ccnt; buf += ccnt;
	}
	LOCK_GIVE(hdw->big_lock);
	return bcnt;
}


static void pvr2_hdw_state_log_state(struct pvr2_hdw *hdw)
{
	char buf[128];
	unsigned int idx,ccnt;

	for (idx = 0; ; idx++) {
		ccnt = pvr2_hdw_report_unlocked(hdw,idx,buf,sizeof(buf));
		if (!ccnt) break;
		printk(KERN_INFO "%s %.*s\n",hdw->name,ccnt,buf);
	}
}


/* Evaluate and update the driver's current state, taking various actions
   as appropriate for the update. */
static int pvr2_hdw_state_eval(struct pvr2_hdw *hdw)
{
	unsigned int st;
	int state_updated = 0;
	int callback_flag = 0;
4953
	int analog_mode;
4954 4955 4956 4957 4958 4959 4960 4961 4962 4963

	pvr2_trace(PVR2_TRACE_STBITS,
		   "Drive state check START");
	if (pvrusb2_debug & PVR2_TRACE_STBITS) {
		pvr2_hdw_state_log_state(hdw);
	}

	/* Process all state and get back over disposition */
	state_updated = pvr2_hdw_state_update(hdw);

4964 4965
	analog_mode = (hdw->pathway_state != PVR2_PATHWAY_DIGITAL);

4966 4967 4968 4969 4970
	/* Update master state based upon all other states. */
	if (!hdw->flag_ok) {
		st = PVR2_STATE_DEAD;
	} else if (hdw->fw1_state != FW1_STATE_OK) {
		st = PVR2_STATE_COLD;
4971 4972 4973
	} else if ((analog_mode ||
		    hdw->hdw_desc->flag_digital_requires_cx23416) &&
		   !hdw->state_encoder_ok) {
4974
		st = PVR2_STATE_WARM;
4975 4976
	} else if (hdw->flag_tripped ||
		   (analog_mode && hdw->flag_decoder_missed)) {
4977
		st = PVR2_STATE_ERROR;
4978
	} else if (hdw->state_usbstream_run &&
4979
		   (!analog_mode ||
4980
		    (hdw->state_encoder_run && hdw->state_decoder_run))) {
4981 4982 4983 4984 4985 4986 4987 4988 4989
		st = PVR2_STATE_RUN;
	} else {
		st = PVR2_STATE_READY;
	}
	if (hdw->master_state != st) {
		pvr2_trace(PVR2_TRACE_STATE,
			   "Device state change from %s to %s",
			   pvr2_get_state_name(hdw->master_state),
			   pvr2_get_state_name(st));
4990
		pvr2_led_ctrl(hdw,st == PVR2_STATE_RUN);
4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019
		hdw->master_state = st;
		state_updated = !0;
		callback_flag = !0;
	}
	if (state_updated) {
		/* Trigger anyone waiting on any state changes here. */
		wake_up(&hdw->state_wait_data);
	}

	if (pvrusb2_debug & PVR2_TRACE_STBITS) {
		pvr2_hdw_state_log_state(hdw);
	}
	pvr2_trace(PVR2_TRACE_STBITS,
		   "Drive state check DONE callback=%d",callback_flag);

	return callback_flag;
}


/* Cause kernel thread to check / update driver state */
static void pvr2_hdw_state_sched(struct pvr2_hdw *hdw)
{
	if (hdw->state_stale) return;
	hdw->state_stale = !0;
	trace_stbit("state_stale",hdw->state_stale);
	queue_work(hdw->workqueue,&hdw->workpoll);
}


5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078
int pvr2_hdw_gpio_get_dir(struct pvr2_hdw *hdw,u32 *dp)
{
	return pvr2_read_register(hdw,PVR2_GPIO_DIR,dp);
}


int pvr2_hdw_gpio_get_out(struct pvr2_hdw *hdw,u32 *dp)
{
	return pvr2_read_register(hdw,PVR2_GPIO_OUT,dp);
}


int pvr2_hdw_gpio_get_in(struct pvr2_hdw *hdw,u32 *dp)
{
	return pvr2_read_register(hdw,PVR2_GPIO_IN,dp);
}


int pvr2_hdw_gpio_chg_dir(struct pvr2_hdw *hdw,u32 msk,u32 val)
{
	u32 cval,nval;
	int ret;
	if (~msk) {
		ret = pvr2_read_register(hdw,PVR2_GPIO_DIR,&cval);
		if (ret) return ret;
		nval = (cval & ~msk) | (val & msk);
		pvr2_trace(PVR2_TRACE_GPIO,
			   "GPIO direction changing 0x%x:0x%x"
			   " from 0x%x to 0x%x",
			   msk,val,cval,nval);
	} else {
		nval = val;
		pvr2_trace(PVR2_TRACE_GPIO,
			   "GPIO direction changing to 0x%x",nval);
	}
	return pvr2_write_register(hdw,PVR2_GPIO_DIR,nval);
}


int pvr2_hdw_gpio_chg_out(struct pvr2_hdw *hdw,u32 msk,u32 val)
{
	u32 cval,nval;
	int ret;
	if (~msk) {
		ret = pvr2_read_register(hdw,PVR2_GPIO_OUT,&cval);
		if (ret) return ret;
		nval = (cval & ~msk) | (val & msk);
		pvr2_trace(PVR2_TRACE_GPIO,
			   "GPIO output changing 0x%x:0x%x from 0x%x to 0x%x",
			   msk,val,cval,nval);
	} else {
		nval = val;
		pvr2_trace(PVR2_TRACE_GPIO,
			   "GPIO output changing to 0x%x",nval);
	}
	return pvr2_write_register(hdw,PVR2_GPIO_OUT,nval);
}


5079 5080
void pvr2_hdw_status_poll(struct pvr2_hdw *hdw)
{
5081 5082
	struct v4l2_tuner *vtp = &hdw->tuner_signal_info;
	memset(vtp, 0, sizeof(*vtp));
5083
	hdw->tuner_signal_stale = 0;
5084
	pvr2_i2c_core_status_poll(hdw);
5085 5086 5087 5088 5089 5090
	/* Note: There apparently is no replacement for VIDIOC_CROPCAP
	   using v4l2-subdev - therefore we can't support that AT ALL right
	   now.  (Of course, no sub-drivers seem to implement it either.
	   But now it's a a chicken and egg problem...) */
	v4l2_device_call_all(&hdw->v4l2_dev, 0, tuner, g_tuner,
			     &hdw->tuner_signal_info);
5091
	pvr2_trace(PVR2_TRACE_CHIPS, "subdev status poll"
5092 5093 5094 5095 5096
		   " type=%u strength=%u audio=0x%x cap=0x%x"
		   " low=%u hi=%u",
		   vtp->type,
		   vtp->signal, vtp->rxsubchans, vtp->capability,
		   vtp->rangelow, vtp->rangehigh);
5097 5098 5099 5100

	/* We have to do this to avoid getting into constant polling if
	   there's nobody to answer a poll of cropcap info. */
	hdw->cropcap_stale = 0;
5101 5102 5103
}


5104 5105 5106 5107 5108 5109
unsigned int pvr2_hdw_get_input_available(struct pvr2_hdw *hdw)
{
	return hdw->input_avail_mask;
}


5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177
unsigned int pvr2_hdw_get_input_allowed(struct pvr2_hdw *hdw)
{
	return hdw->input_allowed_mask;
}


static int pvr2_hdw_set_input(struct pvr2_hdw *hdw,int v)
{
	if (hdw->input_val != v) {
		hdw->input_val = v;
		hdw->input_dirty = !0;
	}

	/* Handle side effects - if we switch to a mode that needs the RF
	   tuner, then select the right frequency choice as well and mark
	   it dirty. */
	if (hdw->input_val == PVR2_CVAL_INPUT_RADIO) {
		hdw->freqSelector = 0;
		hdw->freqDirty = !0;
	} else if ((hdw->input_val == PVR2_CVAL_INPUT_TV) ||
		   (hdw->input_val == PVR2_CVAL_INPUT_DTV)) {
		hdw->freqSelector = 1;
		hdw->freqDirty = !0;
	}
	return 0;
}


int pvr2_hdw_set_input_allowed(struct pvr2_hdw *hdw,
			       unsigned int change_mask,
			       unsigned int change_val)
{
	int ret = 0;
	unsigned int nv,m,idx;
	LOCK_TAKE(hdw->big_lock);
	do {
		nv = hdw->input_allowed_mask & ~change_mask;
		nv |= (change_val & change_mask);
		nv &= hdw->input_avail_mask;
		if (!nv) {
			/* No legal modes left; return error instead. */
			ret = -EPERM;
			break;
		}
		hdw->input_allowed_mask = nv;
		if ((1 << hdw->input_val) & hdw->input_allowed_mask) {
			/* Current mode is still in the allowed mask, so
			   we're done. */
			break;
		}
		/* Select and switch to a mode that is still in the allowed
		   mask */
		if (!hdw->input_allowed_mask) {
			/* Nothing legal; give up */
			break;
		}
		m = hdw->input_allowed_mask;
		for (idx = 0; idx < (sizeof(m) << 3); idx++) {
			if (!((1 << idx) & m)) continue;
			pvr2_hdw_set_input(hdw,idx);
			break;
		}
	} while (0);
	LOCK_GIVE(hdw->big_lock);
	return ret;
}


5178
/* Find I2C address of eeprom */
5179
static int pvr2_hdw_get_eeprom_addr(struct pvr2_hdw *hdw)
5180 5181 5182
{
	int result;
	LOCK_TAKE(hdw->ctl_lock); do {
5183
		hdw->cmd_buffer[0] = FX2CMD_GET_EEPROM_ADDR;
5184 5185 5186 5187 5188 5189 5190 5191 5192 5193
		result = pvr2_send_request(hdw,
					   hdw->cmd_buffer,1,
					   hdw->cmd_buffer,1);
		if (result < 0) break;
		result = hdw->cmd_buffer[0];
	} while(0); LOCK_GIVE(hdw->ctl_lock);
	return result;
}


5194
int pvr2_hdw_register_access(struct pvr2_hdw *hdw,
5195 5196
			     struct v4l2_dbg_match *match, u64 reg_id,
			     int setFl, u64 *val_ptr)
5197 5198 5199
{
#ifdef CONFIG_VIDEO_ADV_DEBUG
	struct pvr2_i2c_client *cp;
5200
	struct v4l2_dbg_register req;
5201 5202
	int stat = 0;
	int okFl = 0;
5203

5204 5205
	if (!capable(CAP_SYS_ADMIN)) return -EPERM;

5206
	req.match = *match;
5207 5208
	req.reg = reg_id;
	if (setFl) req.val = *val_ptr;
5209 5210 5211 5212
	/* It would be nice to know if a sub-device answered the request */
	v4l2_device_call_all(&hdw->v4l2_dev, 0, core, g_register, &req);
	if (!setFl) *val_ptr = req.val;
	if (!okFl) mutex_lock(&hdw->i2c_list_lock); do {
5213
		list_for_each_entry(cp, &hdw->i2c_clients, list) {
5214 5215
			if (!v4l2_chip_match_i2c_client(
				    cp->client,
5216
				    &req.match)) {
5217 5218
				continue;
			}
5219
			stat = pvr2_i2c_client_cmd(
5220 5221
				cp,(setFl ? VIDIOC_DBG_S_REGISTER :
				    VIDIOC_DBG_G_REGISTER),&req);
5222
			if (!setFl) *val_ptr = req.val;
5223 5224
			okFl = !0;
			break;
5225 5226
		}
	} while (0); mutex_unlock(&hdw->i2c_list_lock);
5227 5228 5229
	if (okFl) {
		return stat;
	}
5230 5231 5232 5233 5234 5235 5236
	return -EINVAL;
#else
	return -ENOSYS;
#endif
}


5237 5238 5239 5240 5241 5242 5243 5244 5245
/*
  Stuff for Emacs to see, in order to encourage consistent editing style:
  *** Local Variables: ***
  *** mode: c ***
  *** fill-column: 75 ***
  *** tab-width: 8 ***
  *** c-basic-offset: 8 ***
  *** End: ***
  */