xref: /linux/drivers/media/usb/pvrusb2/pvrusb2-hdw.c (revision 189f164e573e18d9f8876dbd3ad8fcbe11f93037)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *
4  *  Copyright (C) 2005 Mike Isely <isely@pobox.com>
5  */
6 
7 #include <linux/errno.h>
8 #include <linux/string.h>
9 #include <linux/slab.h>
10 #include <linux/module.h>
11 #include <linux/firmware.h>
12 #include <linux/videodev2.h>
13 #include <media/v4l2-common.h>
14 #include <media/tuner.h>
15 #include "pvrusb2.h"
16 #include "pvrusb2-std.h"
17 #include "pvrusb2-util.h"
18 #include "pvrusb2-hdw.h"
19 #include "pvrusb2-i2c-core.h"
20 #include "pvrusb2-eeprom.h"
21 #include "pvrusb2-hdw-internal.h"
22 #include "pvrusb2-encoder.h"
23 #include "pvrusb2-debug.h"
24 #include "pvrusb2-fx2-cmd.h"
25 #include "pvrusb2-wm8775.h"
26 #include "pvrusb2-video-v4l.h"
27 #include "pvrusb2-cx2584x-v4l.h"
28 #include "pvrusb2-cs53l32a.h"
29 #include "pvrusb2-audio.h"
30 
31 #define TV_MIN_FREQ     55250000L
32 #define TV_MAX_FREQ    850000000L
33 
34 /* This defines a minimum interval that the decoder must remain quiet
35    before we are allowed to start it running. */
36 #define TIME_MSEC_DECODER_WAIT 50
37 
38 /* This defines a minimum interval that the decoder must be allowed to run
39    before we can safely begin using its streaming output. */
40 #define TIME_MSEC_DECODER_STABILIZATION_WAIT 300
41 
42 /* This defines a minimum interval that the encoder must remain quiet
43    before we are allowed to configure it. */
44 #define TIME_MSEC_ENCODER_WAIT 50
45 
46 /* This defines the minimum interval that the encoder must successfully run
47    before we consider that the encoder has run at least once since its
48    firmware has been loaded.  This measurement is in important for cases
49    where we can't do something until we know that the encoder has been run
50    at least once. */
51 #define TIME_MSEC_ENCODER_OK 250
52 
53 static struct pvr2_hdw *unit_pointers[PVR_NUM] = {[ 0 ... PVR_NUM-1 ] = NULL};
54 static DEFINE_MUTEX(pvr2_unit_mtx);
55 
56 static int ctlchg;
57 static int procreload;
58 static int tuner[PVR_NUM] = { [0 ... PVR_NUM-1] = -1 };
59 static int tolerance[PVR_NUM] = { [0 ... PVR_NUM-1] = 0 };
60 static int video_std[PVR_NUM] = { [0 ... PVR_NUM-1] = 0 };
61 static int init_pause_msec;
62 
63 module_param(ctlchg, int, S_IRUGO|S_IWUSR);
64 MODULE_PARM_DESC(ctlchg, "0=optimize ctl change 1=always accept new ctl value");
65 module_param(init_pause_msec, int, S_IRUGO|S_IWUSR);
66 MODULE_PARM_DESC(init_pause_msec, "hardware initialization settling delay");
67 module_param(procreload, int, S_IRUGO|S_IWUSR);
68 MODULE_PARM_DESC(procreload,
69 		 "Attempt init failure recovery with firmware reload");
70 module_param_array(tuner,    int, NULL, 0444);
71 MODULE_PARM_DESC(tuner,"specify installed tuner type");
72 module_param_array(video_std,    int, NULL, 0444);
73 MODULE_PARM_DESC(video_std,"specify initial video standard");
74 module_param_array(tolerance,    int, NULL, 0444);
75 MODULE_PARM_DESC(tolerance,"specify stream error tolerance");
76 
77 /* US Broadcast channel 3 (61.25 MHz), to help with testing */
78 static int default_tv_freq    = 61250000L;
79 /* 104.3 MHz, a usable FM station for my area */
80 static int default_radio_freq = 104300000L;
81 
82 module_param_named(tv_freq, default_tv_freq, int, 0444);
83 MODULE_PARM_DESC(tv_freq, "specify initial television frequency");
84 module_param_named(radio_freq, default_radio_freq, int, 0444);
85 MODULE_PARM_DESC(radio_freq, "specify initial radio frequency");
86 
87 #define PVR2_CTL_WRITE_ENDPOINT  0x01
88 #define PVR2_CTL_READ_ENDPOINT   0x81
89 
90 #define PVR2_GPIO_IN 0x9008
91 #define PVR2_GPIO_OUT 0x900c
92 #define PVR2_GPIO_DIR 0x9020
93 
94 #define trace_firmware(...) pvr2_trace(PVR2_TRACE_FIRMWARE,__VA_ARGS__)
95 
96 #define PVR2_FIRMWARE_ENDPOINT   0x02
97 
98 /* size of a firmware chunk */
99 #define FIRMWARE_CHUNK_SIZE 0x2000
100 
101 typedef void (*pvr2_subdev_update_func)(struct pvr2_hdw *,
102 					struct v4l2_subdev *);
103 
104 static const pvr2_subdev_update_func pvr2_module_update_functions[] = {
105 	[PVR2_CLIENT_ID_WM8775] = pvr2_wm8775_subdev_update,
106 	[PVR2_CLIENT_ID_SAA7115] = pvr2_saa7115_subdev_update,
107 	[PVR2_CLIENT_ID_MSP3400] = pvr2_msp3400_subdev_update,
108 	[PVR2_CLIENT_ID_CX25840] = pvr2_cx25840_subdev_update,
109 	[PVR2_CLIENT_ID_CS53L32A] = pvr2_cs53l32a_subdev_update,
110 };
111 
112 static const char *module_names[] = {
113 	[PVR2_CLIENT_ID_MSP3400] = "msp3400",
114 	[PVR2_CLIENT_ID_CX25840] = "cx25840",
115 	[PVR2_CLIENT_ID_SAA7115] = "saa7115",
116 	[PVR2_CLIENT_ID_TUNER] = "tuner",
117 	[PVR2_CLIENT_ID_DEMOD] = "tuner",
118 	[PVR2_CLIENT_ID_CS53L32A] = "cs53l32a",
119 	[PVR2_CLIENT_ID_WM8775] = "wm8775",
120 };
121 
122 
123 static const unsigned char *module_i2c_addresses[] = {
124 	[PVR2_CLIENT_ID_TUNER] = "\x60\x61\x62\x63",
125 	[PVR2_CLIENT_ID_DEMOD] = "\x43",
126 	[PVR2_CLIENT_ID_MSP3400] = "\x40",
127 	[PVR2_CLIENT_ID_SAA7115] = "\x21",
128 	[PVR2_CLIENT_ID_WM8775] = "\x1b",
129 	[PVR2_CLIENT_ID_CX25840] = "\x44",
130 	[PVR2_CLIENT_ID_CS53L32A] = "\x11",
131 };
132 
133 
134 static const char *ir_scheme_names[] = {
135 	[PVR2_IR_SCHEME_NONE] = "none",
136 	[PVR2_IR_SCHEME_29XXX] = "29xxx",
137 	[PVR2_IR_SCHEME_24XXX] = "24xxx (29xxx emulation)",
138 	[PVR2_IR_SCHEME_24XXX_MCE] = "24xxx (MCE device)",
139 	[PVR2_IR_SCHEME_ZILOG] = "Zilog",
140 };
141 
142 
143 /* Define the list of additional controls we'll dynamically construct based
144    on query of the cx2341x module. */
145 struct pvr2_mpeg_ids {
146 	const char *strid;
147 	int id;
148 };
149 static const struct pvr2_mpeg_ids mpeg_ids[] = {
150 	{
151 		.strid = "audio_layer",
152 		.id = V4L2_CID_MPEG_AUDIO_ENCODING,
153 	},{
154 		.strid = "audio_bitrate",
155 		.id = V4L2_CID_MPEG_AUDIO_L2_BITRATE,
156 	},{
157 		/* Already using audio_mode elsewhere :-( */
158 		.strid = "mpeg_audio_mode",
159 		.id = V4L2_CID_MPEG_AUDIO_MODE,
160 	},{
161 		.strid = "mpeg_audio_mode_extension",
162 		.id = V4L2_CID_MPEG_AUDIO_MODE_EXTENSION,
163 	},{
164 		.strid = "audio_emphasis",
165 		.id = V4L2_CID_MPEG_AUDIO_EMPHASIS,
166 	},{
167 		.strid = "audio_crc",
168 		.id = V4L2_CID_MPEG_AUDIO_CRC,
169 	},{
170 		.strid = "video_aspect",
171 		.id = V4L2_CID_MPEG_VIDEO_ASPECT,
172 	},{
173 		.strid = "video_b_frames",
174 		.id = V4L2_CID_MPEG_VIDEO_B_FRAMES,
175 	},{
176 		.strid = "video_gop_size",
177 		.id = V4L2_CID_MPEG_VIDEO_GOP_SIZE,
178 	},{
179 		.strid = "video_gop_closure",
180 		.id = V4L2_CID_MPEG_VIDEO_GOP_CLOSURE,
181 	},{
182 		.strid = "video_bitrate_mode",
183 		.id = V4L2_CID_MPEG_VIDEO_BITRATE_MODE,
184 	},{
185 		.strid = "video_bitrate",
186 		.id = V4L2_CID_MPEG_VIDEO_BITRATE,
187 	},{
188 		.strid = "video_bitrate_peak",
189 		.id = V4L2_CID_MPEG_VIDEO_BITRATE_PEAK,
190 	},{
191 		.strid = "video_temporal_decimation",
192 		.id = V4L2_CID_MPEG_VIDEO_TEMPORAL_DECIMATION,
193 	},{
194 		.strid = "stream_type",
195 		.id = V4L2_CID_MPEG_STREAM_TYPE,
196 	},{
197 		.strid = "video_spatial_filter_mode",
198 		.id = V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE,
199 	},{
200 		.strid = "video_spatial_filter",
201 		.id = V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER,
202 	},{
203 		.strid = "video_luma_spatial_filter_type",
204 		.id = V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE,
205 	},{
206 		.strid = "video_chroma_spatial_filter_type",
207 		.id = V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE,
208 	},{
209 		.strid = "video_temporal_filter_mode",
210 		.id = V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE,
211 	},{
212 		.strid = "video_temporal_filter",
213 		.id = V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER,
214 	},{
215 		.strid = "video_median_filter_type",
216 		.id = V4L2_CID_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE,
217 	},{
218 		.strid = "video_luma_median_filter_top",
219 		.id = V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_TOP,
220 	},{
221 		.strid = "video_luma_median_filter_bottom",
222 		.id = V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_BOTTOM,
223 	},{
224 		.strid = "video_chroma_median_filter_top",
225 		.id = V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_TOP,
226 	},{
227 		.strid = "video_chroma_median_filter_bottom",
228 		.id = V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_BOTTOM,
229 	}
230 };
231 #define MPEGDEF_COUNT ARRAY_SIZE(mpeg_ids)
232 
233 
234 static const char *control_values_srate[] = {
235 	[V4L2_MPEG_AUDIO_SAMPLING_FREQ_44100]   = "44.1 kHz",
236 	[V4L2_MPEG_AUDIO_SAMPLING_FREQ_48000]   = "48 kHz",
237 	[V4L2_MPEG_AUDIO_SAMPLING_FREQ_32000]   = "32 kHz",
238 };
239 
240 
241 
242 static const char *control_values_input[] = {
243 	[PVR2_CVAL_INPUT_TV]        = "television",  /*xawtv needs this name*/
244 	[PVR2_CVAL_INPUT_DTV]       = "dtv",
245 	[PVR2_CVAL_INPUT_RADIO]     = "radio",
246 	[PVR2_CVAL_INPUT_SVIDEO]    = "s-video",
247 	[PVR2_CVAL_INPUT_COMPOSITE] = "composite",
248 };
249 
250 
251 static const char *control_values_audiomode[] = {
252 	[V4L2_TUNER_MODE_MONO]   = "Mono",
253 	[V4L2_TUNER_MODE_STEREO] = "Stereo",
254 	[V4L2_TUNER_MODE_LANG1]  = "Lang1",
255 	[V4L2_TUNER_MODE_LANG2]  = "Lang2",
256 	[V4L2_TUNER_MODE_LANG1_LANG2] = "Lang1+Lang2",
257 };
258 
259 
260 static const char *control_values_hsm[] = {
261 	[PVR2_CVAL_HSM_FAIL] = "Fail",
262 	[PVR2_CVAL_HSM_HIGH] = "High",
263 	[PVR2_CVAL_HSM_FULL] = "Full",
264 };
265 
266 
267 static const char *pvr2_state_names[] = {
268 	[PVR2_STATE_NONE] =    "none",
269 	[PVR2_STATE_DEAD] =    "dead",
270 	[PVR2_STATE_COLD] =    "cold",
271 	[PVR2_STATE_WARM] =    "warm",
272 	[PVR2_STATE_ERROR] =   "error",
273 	[PVR2_STATE_READY] =   "ready",
274 	[PVR2_STATE_RUN] =     "run",
275 };
276 
277 
278 struct pvr2_fx2cmd_descdef {
279 	unsigned char id;
280 	unsigned char *desc;
281 };
282 
283 static const struct pvr2_fx2cmd_descdef pvr2_fx2cmd_desc[] = {
284 	{FX2CMD_MEM_WRITE_DWORD, "write encoder dword"},
285 	{FX2CMD_MEM_READ_DWORD, "read encoder dword"},
286 	{FX2CMD_HCW_ZILOG_RESET, "zilog IR reset control"},
287 	{FX2CMD_MEM_READ_64BYTES, "read encoder 64bytes"},
288 	{FX2CMD_REG_WRITE, "write encoder register"},
289 	{FX2CMD_REG_READ, "read encoder register"},
290 	{FX2CMD_MEMSEL, "encoder memsel"},
291 	{FX2CMD_I2C_WRITE, "i2c write"},
292 	{FX2CMD_I2C_READ, "i2c read"},
293 	{FX2CMD_GET_USB_SPEED, "get USB speed"},
294 	{FX2CMD_STREAMING_ON, "stream on"},
295 	{FX2CMD_STREAMING_OFF, "stream off"},
296 	{FX2CMD_FWPOST1, "fwpost1"},
297 	{FX2CMD_POWER_OFF, "power off"},
298 	{FX2CMD_POWER_ON, "power on"},
299 	{FX2CMD_DEEP_RESET, "deep reset"},
300 	{FX2CMD_GET_EEPROM_ADDR, "get rom addr"},
301 	{FX2CMD_GET_IR_CODE, "get IR code"},
302 	{FX2CMD_HCW_DEMOD_RESETIN, "hcw demod resetin"},
303 	{FX2CMD_HCW_DTV_STREAMING_ON, "hcw dtv stream on"},
304 	{FX2CMD_HCW_DTV_STREAMING_OFF, "hcw dtv stream off"},
305 	{FX2CMD_ONAIR_DTV_STREAMING_ON, "onair dtv stream on"},
306 	{FX2CMD_ONAIR_DTV_STREAMING_OFF, "onair dtv stream off"},
307 	{FX2CMD_ONAIR_DTV_POWER_ON, "onair dtv power on"},
308 	{FX2CMD_ONAIR_DTV_POWER_OFF, "onair dtv power off"},
309 	{FX2CMD_HCW_DEMOD_RESET_PIN, "hcw demod reset pin"},
310 	{FX2CMD_HCW_MAKO_SLEEP_PIN, "hcw mako sleep pin"},
311 };
312 
313 
314 static int pvr2_hdw_set_input(struct pvr2_hdw *hdw,int v);
315 static void pvr2_hdw_state_sched(struct pvr2_hdw *);
316 static int pvr2_hdw_state_eval(struct pvr2_hdw *);
317 static void pvr2_hdw_set_cur_freq(struct pvr2_hdw *,unsigned long);
318 static void pvr2_hdw_worker_poll(struct work_struct *work);
319 static int pvr2_hdw_wait(struct pvr2_hdw *,int state);
320 static int pvr2_hdw_untrip_unlocked(struct pvr2_hdw *);
321 static void pvr2_hdw_state_log_state(struct pvr2_hdw *);
322 static int pvr2_hdw_cmd_usbstream(struct pvr2_hdw *hdw,int runFl);
323 static int pvr2_hdw_commit_setup(struct pvr2_hdw *hdw);
324 static int pvr2_hdw_get_eeprom_addr(struct pvr2_hdw *hdw);
325 static void pvr2_hdw_quiescent_timeout(struct timer_list *);
326 static void pvr2_hdw_decoder_stabilization_timeout(struct timer_list *);
327 static void pvr2_hdw_encoder_wait_timeout(struct timer_list *);
328 static void pvr2_hdw_encoder_run_timeout(struct timer_list *);
329 static int pvr2_issue_simple_cmd(struct pvr2_hdw *,u32);
330 static int pvr2_send_request_ex(struct pvr2_hdw *hdw,
331 				unsigned int timeout,int probe_fl,
332 				void *write_data,unsigned int write_len,
333 				void *read_data,unsigned int read_len);
334 static int pvr2_hdw_check_cropcap(struct pvr2_hdw *hdw);
335 static v4l2_std_id pvr2_hdw_get_detected_std(struct pvr2_hdw *hdw);
336 
trace_stbit(const char * name,int val)337 static void trace_stbit(const char *name,int val)
338 {
339 	pvr2_trace(PVR2_TRACE_STBITS,
340 		   "State bit %s <-- %s",
341 		   name,(val ? "true" : "false"));
342 }
343 
ctrl_channelfreq_get(struct pvr2_ctrl * cptr,int * vp)344 static int ctrl_channelfreq_get(struct pvr2_ctrl *cptr,int *vp)
345 {
346 	struct pvr2_hdw *hdw = cptr->hdw;
347 	if ((hdw->freqProgSlot > 0) && (hdw->freqProgSlot <= FREQTABLE_SIZE)) {
348 		*vp = hdw->freqTable[hdw->freqProgSlot-1];
349 	} else {
350 		*vp = 0;
351 	}
352 	return 0;
353 }
354 
ctrl_channelfreq_set(struct pvr2_ctrl * cptr,int m,int v)355 static int ctrl_channelfreq_set(struct pvr2_ctrl *cptr,int m,int v)
356 {
357 	struct pvr2_hdw *hdw = cptr->hdw;
358 	unsigned int slotId = hdw->freqProgSlot;
359 	if ((slotId > 0) && (slotId <= FREQTABLE_SIZE)) {
360 		hdw->freqTable[slotId-1] = v;
361 		/* Handle side effects correctly - if we're tuned to this
362 		   slot, then forgot the slot id relation since the stored
363 		   frequency has been changed. */
364 		if (hdw->freqSelector) {
365 			if (hdw->freqSlotRadio == slotId) {
366 				hdw->freqSlotRadio = 0;
367 			}
368 		} else {
369 			if (hdw->freqSlotTelevision == slotId) {
370 				hdw->freqSlotTelevision = 0;
371 			}
372 		}
373 	}
374 	return 0;
375 }
376 
ctrl_channelprog_get(struct pvr2_ctrl * cptr,int * vp)377 static int ctrl_channelprog_get(struct pvr2_ctrl *cptr,int *vp)
378 {
379 	*vp = cptr->hdw->freqProgSlot;
380 	return 0;
381 }
382 
ctrl_channelprog_set(struct pvr2_ctrl * cptr,int m,int v)383 static int ctrl_channelprog_set(struct pvr2_ctrl *cptr,int m,int v)
384 {
385 	struct pvr2_hdw *hdw = cptr->hdw;
386 	if ((v >= 0) && (v <= FREQTABLE_SIZE)) {
387 		hdw->freqProgSlot = v;
388 	}
389 	return 0;
390 }
391 
ctrl_channel_get(struct pvr2_ctrl * cptr,int * vp)392 static int ctrl_channel_get(struct pvr2_ctrl *cptr,int *vp)
393 {
394 	struct pvr2_hdw *hdw = cptr->hdw;
395 	*vp = hdw->freqSelector ? hdw->freqSlotRadio : hdw->freqSlotTelevision;
396 	return 0;
397 }
398 
ctrl_channel_set(struct pvr2_ctrl * cptr,int m,int slotId)399 static int ctrl_channel_set(struct pvr2_ctrl *cptr,int m,int slotId)
400 {
401 	unsigned freq = 0;
402 	struct pvr2_hdw *hdw = cptr->hdw;
403 	if ((slotId < 0) || (slotId > FREQTABLE_SIZE)) return 0;
404 	if (slotId > 0) {
405 		freq = hdw->freqTable[slotId-1];
406 		if (!freq) return 0;
407 		pvr2_hdw_set_cur_freq(hdw,freq);
408 	}
409 	if (hdw->freqSelector) {
410 		hdw->freqSlotRadio = slotId;
411 	} else {
412 		hdw->freqSlotTelevision = slotId;
413 	}
414 	return 0;
415 }
416 
ctrl_freq_get(struct pvr2_ctrl * cptr,int * vp)417 static int ctrl_freq_get(struct pvr2_ctrl *cptr,int *vp)
418 {
419 	*vp = pvr2_hdw_get_cur_freq(cptr->hdw);
420 	return 0;
421 }
422 
ctrl_freq_is_dirty(struct pvr2_ctrl * cptr)423 static int ctrl_freq_is_dirty(struct pvr2_ctrl *cptr)
424 {
425 	return cptr->hdw->freqDirty != 0;
426 }
427 
ctrl_freq_clear_dirty(struct pvr2_ctrl * cptr)428 static void ctrl_freq_clear_dirty(struct pvr2_ctrl *cptr)
429 {
430 	cptr->hdw->freqDirty = 0;
431 }
432 
ctrl_freq_set(struct pvr2_ctrl * cptr,int m,int v)433 static int ctrl_freq_set(struct pvr2_ctrl *cptr,int m,int v)
434 {
435 	pvr2_hdw_set_cur_freq(cptr->hdw,v);
436 	return 0;
437 }
438 
ctrl_cropl_min_get(struct pvr2_ctrl * cptr,int * left)439 static int ctrl_cropl_min_get(struct pvr2_ctrl *cptr, int *left)
440 {
441 	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
442 	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
443 	if (stat != 0) {
444 		return stat;
445 	}
446 	*left = cap->bounds.left;
447 	return 0;
448 }
449 
ctrl_cropl_max_get(struct pvr2_ctrl * cptr,int * left)450 static int ctrl_cropl_max_get(struct pvr2_ctrl *cptr, int *left)
451 {
452 	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
453 	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
454 	if (stat != 0) {
455 		return stat;
456 	}
457 	*left = cap->bounds.left;
458 	if (cap->bounds.width > cptr->hdw->cropw_val) {
459 		*left += cap->bounds.width - cptr->hdw->cropw_val;
460 	}
461 	return 0;
462 }
463 
ctrl_cropt_min_get(struct pvr2_ctrl * cptr,int * top)464 static int ctrl_cropt_min_get(struct pvr2_ctrl *cptr, int *top)
465 {
466 	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
467 	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
468 	if (stat != 0) {
469 		return stat;
470 	}
471 	*top = cap->bounds.top;
472 	return 0;
473 }
474 
ctrl_cropt_max_get(struct pvr2_ctrl * cptr,int * top)475 static int ctrl_cropt_max_get(struct pvr2_ctrl *cptr, int *top)
476 {
477 	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
478 	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
479 	if (stat != 0) {
480 		return stat;
481 	}
482 	*top = cap->bounds.top;
483 	if (cap->bounds.height > cptr->hdw->croph_val) {
484 		*top += cap->bounds.height - cptr->hdw->croph_val;
485 	}
486 	return 0;
487 }
488 
ctrl_cropw_max_get(struct pvr2_ctrl * cptr,int * width)489 static int ctrl_cropw_max_get(struct pvr2_ctrl *cptr, int *width)
490 {
491 	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
492 	int stat, bleftend, cleft;
493 
494 	stat = pvr2_hdw_check_cropcap(cptr->hdw);
495 	if (stat != 0) {
496 		return stat;
497 	}
498 	bleftend = cap->bounds.left+cap->bounds.width;
499 	cleft = cptr->hdw->cropl_val;
500 
501 	*width = cleft < bleftend ? bleftend-cleft : 0;
502 	return 0;
503 }
504 
ctrl_croph_max_get(struct pvr2_ctrl * cptr,int * height)505 static int ctrl_croph_max_get(struct pvr2_ctrl *cptr, int *height)
506 {
507 	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
508 	int stat, btopend, ctop;
509 
510 	stat = pvr2_hdw_check_cropcap(cptr->hdw);
511 	if (stat != 0) {
512 		return stat;
513 	}
514 	btopend = cap->bounds.top+cap->bounds.height;
515 	ctop = cptr->hdw->cropt_val;
516 
517 	*height = ctop < btopend ? btopend-ctop : 0;
518 	return 0;
519 }
520 
ctrl_get_cropcapbl(struct pvr2_ctrl * cptr,int * val)521 static int ctrl_get_cropcapbl(struct pvr2_ctrl *cptr, int *val)
522 {
523 	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
524 	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
525 	if (stat != 0) {
526 		return stat;
527 	}
528 	*val = cap->bounds.left;
529 	return 0;
530 }
531 
ctrl_get_cropcapbt(struct pvr2_ctrl * cptr,int * val)532 static int ctrl_get_cropcapbt(struct pvr2_ctrl *cptr, int *val)
533 {
534 	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
535 	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
536 	if (stat != 0) {
537 		return stat;
538 	}
539 	*val = cap->bounds.top;
540 	return 0;
541 }
542 
ctrl_get_cropcapbw(struct pvr2_ctrl * cptr,int * val)543 static int ctrl_get_cropcapbw(struct pvr2_ctrl *cptr, int *val)
544 {
545 	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
546 	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
547 	if (stat != 0) {
548 		return stat;
549 	}
550 	*val = cap->bounds.width;
551 	return 0;
552 }
553 
ctrl_get_cropcapbh(struct pvr2_ctrl * cptr,int * val)554 static int ctrl_get_cropcapbh(struct pvr2_ctrl *cptr, int *val)
555 {
556 	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
557 	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
558 	if (stat != 0) {
559 		return stat;
560 	}
561 	*val = cap->bounds.height;
562 	return 0;
563 }
564 
ctrl_get_cropcapdl(struct pvr2_ctrl * cptr,int * val)565 static int ctrl_get_cropcapdl(struct pvr2_ctrl *cptr, int *val)
566 {
567 	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
568 	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
569 	if (stat != 0) {
570 		return stat;
571 	}
572 	*val = cap->defrect.left;
573 	return 0;
574 }
575 
ctrl_get_cropcapdt(struct pvr2_ctrl * cptr,int * val)576 static int ctrl_get_cropcapdt(struct pvr2_ctrl *cptr, int *val)
577 {
578 	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
579 	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
580 	if (stat != 0) {
581 		return stat;
582 	}
583 	*val = cap->defrect.top;
584 	return 0;
585 }
586 
ctrl_get_cropcapdw(struct pvr2_ctrl * cptr,int * val)587 static int ctrl_get_cropcapdw(struct pvr2_ctrl *cptr, int *val)
588 {
589 	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
590 	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
591 	if (stat != 0) {
592 		return stat;
593 	}
594 	*val = cap->defrect.width;
595 	return 0;
596 }
597 
ctrl_get_cropcapdh(struct pvr2_ctrl * cptr,int * val)598 static int ctrl_get_cropcapdh(struct pvr2_ctrl *cptr, int *val)
599 {
600 	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
601 	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
602 	if (stat != 0) {
603 		return stat;
604 	}
605 	*val = cap->defrect.height;
606 	return 0;
607 }
608 
ctrl_get_cropcappan(struct pvr2_ctrl * cptr,int * val)609 static int ctrl_get_cropcappan(struct pvr2_ctrl *cptr, int *val)
610 {
611 	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
612 	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
613 	if (stat != 0) {
614 		return stat;
615 	}
616 	*val = cap->pixelaspect.numerator;
617 	return 0;
618 }
619 
ctrl_get_cropcappad(struct pvr2_ctrl * cptr,int * val)620 static int ctrl_get_cropcappad(struct pvr2_ctrl *cptr, int *val)
621 {
622 	struct v4l2_cropcap *cap = &cptr->hdw->cropcap_info;
623 	int stat = pvr2_hdw_check_cropcap(cptr->hdw);
624 	if (stat != 0) {
625 		return stat;
626 	}
627 	*val = cap->pixelaspect.denominator;
628 	return 0;
629 }
630 
ctrl_vres_max_get(struct pvr2_ctrl * cptr,int * vp)631 static int ctrl_vres_max_get(struct pvr2_ctrl *cptr,int *vp)
632 {
633 	/* Actual maximum depends on the video standard in effect. */
634 	if (cptr->hdw->std_mask_cur & V4L2_STD_525_60) {
635 		*vp = 480;
636 	} else {
637 		*vp = 576;
638 	}
639 	return 0;
640 }
641 
ctrl_vres_min_get(struct pvr2_ctrl * cptr,int * vp)642 static int ctrl_vres_min_get(struct pvr2_ctrl *cptr,int *vp)
643 {
644 	/* Actual minimum depends on device digitizer type. */
645 	if (cptr->hdw->hdw_desc->flag_has_cx25840) {
646 		*vp = 75;
647 	} else {
648 		*vp = 17;
649 	}
650 	return 0;
651 }
652 
ctrl_get_input(struct pvr2_ctrl * cptr,int * vp)653 static int ctrl_get_input(struct pvr2_ctrl *cptr,int *vp)
654 {
655 	*vp = cptr->hdw->input_val;
656 	return 0;
657 }
658 
ctrl_check_input(struct pvr2_ctrl * cptr,int v)659 static int ctrl_check_input(struct pvr2_ctrl *cptr,int v)
660 {
661 	if (v < 0 || v > PVR2_CVAL_INPUT_MAX)
662 		return 0;
663 	return ((1UL << v) & cptr->hdw->input_allowed_mask) != 0;
664 }
665 
ctrl_set_input(struct pvr2_ctrl * cptr,int m,int v)666 static int ctrl_set_input(struct pvr2_ctrl *cptr,int m,int v)
667 {
668 	return pvr2_hdw_set_input(cptr->hdw,v);
669 }
670 
ctrl_isdirty_input(struct pvr2_ctrl * cptr)671 static int ctrl_isdirty_input(struct pvr2_ctrl *cptr)
672 {
673 	return cptr->hdw->input_dirty != 0;
674 }
675 
ctrl_cleardirty_input(struct pvr2_ctrl * cptr)676 static void ctrl_cleardirty_input(struct pvr2_ctrl *cptr)
677 {
678 	cptr->hdw->input_dirty = 0;
679 }
680 
681 
ctrl_freq_max_get(struct pvr2_ctrl * cptr,int * vp)682 static int ctrl_freq_max_get(struct pvr2_ctrl *cptr, int *vp)
683 {
684 	unsigned long fv;
685 	struct pvr2_hdw *hdw = cptr->hdw;
686 	if (hdw->tuner_signal_stale) {
687 		pvr2_hdw_status_poll(hdw);
688 	}
689 	fv = hdw->tuner_signal_info.rangehigh;
690 	if (!fv) {
691 		/* Safety fallback */
692 		*vp = TV_MAX_FREQ;
693 		return 0;
694 	}
695 	if (hdw->tuner_signal_info.capability & V4L2_TUNER_CAP_LOW) {
696 		fv = (fv * 125) / 2;
697 	} else {
698 		fv = fv * 62500;
699 	}
700 	*vp = fv;
701 	return 0;
702 }
703 
ctrl_freq_min_get(struct pvr2_ctrl * cptr,int * vp)704 static int ctrl_freq_min_get(struct pvr2_ctrl *cptr, int *vp)
705 {
706 	unsigned long fv;
707 	struct pvr2_hdw *hdw = cptr->hdw;
708 	if (hdw->tuner_signal_stale) {
709 		pvr2_hdw_status_poll(hdw);
710 	}
711 	fv = hdw->tuner_signal_info.rangelow;
712 	if (!fv) {
713 		/* Safety fallback */
714 		*vp = TV_MIN_FREQ;
715 		return 0;
716 	}
717 	if (hdw->tuner_signal_info.capability & V4L2_TUNER_CAP_LOW) {
718 		fv = (fv * 125) / 2;
719 	} else {
720 		fv = fv * 62500;
721 	}
722 	*vp = fv;
723 	return 0;
724 }
725 
ctrl_cx2341x_is_dirty(struct pvr2_ctrl * cptr)726 static int ctrl_cx2341x_is_dirty(struct pvr2_ctrl *cptr)
727 {
728 	return cptr->hdw->enc_stale != 0;
729 }
730 
ctrl_cx2341x_clear_dirty(struct pvr2_ctrl * cptr)731 static void ctrl_cx2341x_clear_dirty(struct pvr2_ctrl *cptr)
732 {
733 	cptr->hdw->enc_stale = 0;
734 	cptr->hdw->enc_unsafe_stale = 0;
735 }
736 
ctrl_cx2341x_get(struct pvr2_ctrl * cptr,int * vp)737 static int ctrl_cx2341x_get(struct pvr2_ctrl *cptr,int *vp)
738 {
739 	int ret;
740 	struct v4l2_ext_controls cs;
741 	struct v4l2_ext_control c1;
742 	memset(&cs,0,sizeof(cs));
743 	memset(&c1,0,sizeof(c1));
744 	cs.controls = &c1;
745 	cs.count = 1;
746 	c1.id = cptr->info->v4l_id;
747 	ret = cx2341x_ext_ctrls(&cptr->hdw->enc_ctl_state, 0, &cs,
748 				VIDIOC_G_EXT_CTRLS);
749 	if (ret) return ret;
750 	*vp = c1.value;
751 	return 0;
752 }
753 
ctrl_cx2341x_set(struct pvr2_ctrl * cptr,int m,int v)754 static int ctrl_cx2341x_set(struct pvr2_ctrl *cptr,int m,int v)
755 {
756 	int ret;
757 	struct pvr2_hdw *hdw = cptr->hdw;
758 	struct v4l2_ext_controls cs;
759 	struct v4l2_ext_control c1;
760 	memset(&cs,0,sizeof(cs));
761 	memset(&c1,0,sizeof(c1));
762 	cs.controls = &c1;
763 	cs.count = 1;
764 	c1.id = cptr->info->v4l_id;
765 	c1.value = v;
766 	ret = cx2341x_ext_ctrls(&hdw->enc_ctl_state,
767 				hdw->state_encoder_run, &cs,
768 				VIDIOC_S_EXT_CTRLS);
769 	if (ret == -EBUSY) {
770 		/* Oops.  cx2341x is telling us it's not safe to change
771 		   this control while we're capturing.  Make a note of this
772 		   fact so that the pipeline will be stopped the next time
773 		   controls are committed.  Then go on ahead and store this
774 		   change anyway. */
775 		ret = cx2341x_ext_ctrls(&hdw->enc_ctl_state,
776 					0, &cs,
777 					VIDIOC_S_EXT_CTRLS);
778 		if (!ret) hdw->enc_unsafe_stale = !0;
779 	}
780 	if (ret) return ret;
781 	hdw->enc_stale = !0;
782 	return 0;
783 }
784 
ctrl_cx2341x_getv4lflags(struct pvr2_ctrl * cptr)785 static unsigned int ctrl_cx2341x_getv4lflags(struct pvr2_ctrl *cptr)
786 {
787 	struct v4l2_queryctrl qctrl = {};
788 	struct pvr2_ctl_info *info;
789 	qctrl.id = cptr->info->v4l_id;
790 	cx2341x_ctrl_query(&cptr->hdw->enc_ctl_state,&qctrl);
791 	/* Strip out the const so we can adjust a function pointer.  It's
792 	   OK to do this here because we know this is a dynamically created
793 	   control, so the underlying storage for the info pointer is (a)
794 	   private to us, and (b) not in read-only storage.  Either we do
795 	   this or we significantly complicate the underlying control
796 	   implementation. */
797 	info = (struct pvr2_ctl_info *)(cptr->info);
798 	if (qctrl.flags & V4L2_CTRL_FLAG_READ_ONLY) {
799 		if (info->set_value) {
800 			info->set_value = NULL;
801 		}
802 	} else {
803 		if (!(info->set_value)) {
804 			info->set_value = ctrl_cx2341x_set;
805 		}
806 	}
807 	return qctrl.flags;
808 }
809 
ctrl_streamingenabled_get(struct pvr2_ctrl * cptr,int * vp)810 static int ctrl_streamingenabled_get(struct pvr2_ctrl *cptr,int *vp)
811 {
812 	*vp = cptr->hdw->state_pipeline_req;
813 	return 0;
814 }
815 
ctrl_masterstate_get(struct pvr2_ctrl * cptr,int * vp)816 static int ctrl_masterstate_get(struct pvr2_ctrl *cptr,int *vp)
817 {
818 	*vp = cptr->hdw->master_state;
819 	return 0;
820 }
821 
ctrl_hsm_get(struct pvr2_ctrl * cptr,int * vp)822 static int ctrl_hsm_get(struct pvr2_ctrl *cptr,int *vp)
823 {
824 	int result = pvr2_hdw_is_hsm(cptr->hdw);
825 	*vp = PVR2_CVAL_HSM_FULL;
826 	if (result < 0) *vp = PVR2_CVAL_HSM_FAIL;
827 	if (result) *vp = PVR2_CVAL_HSM_HIGH;
828 	return 0;
829 }
830 
ctrl_stddetect_get(struct pvr2_ctrl * cptr,int * vp)831 static int ctrl_stddetect_get(struct pvr2_ctrl *cptr, int *vp)
832 {
833 	*vp = pvr2_hdw_get_detected_std(cptr->hdw);
834 	return 0;
835 }
836 
ctrl_stdavail_get(struct pvr2_ctrl * cptr,int * vp)837 static int ctrl_stdavail_get(struct pvr2_ctrl *cptr,int *vp)
838 {
839 	*vp = cptr->hdw->std_mask_avail;
840 	return 0;
841 }
842 
ctrl_stdavail_set(struct pvr2_ctrl * cptr,int m,int v)843 static int ctrl_stdavail_set(struct pvr2_ctrl *cptr,int m,int v)
844 {
845 	struct pvr2_hdw *hdw = cptr->hdw;
846 	v4l2_std_id ns;
847 	ns = hdw->std_mask_avail;
848 	ns = (ns & ~m) | (v & m);
849 	if (ns == hdw->std_mask_avail) return 0;
850 	hdw->std_mask_avail = ns;
851 	hdw->std_info_cur.def.type_bitmask.valid_bits = hdw->std_mask_avail;
852 	return 0;
853 }
854 
ctrl_std_val_to_sym(struct pvr2_ctrl * cptr,int msk,int val,char * bufPtr,unsigned int bufSize,unsigned int * len)855 static int ctrl_std_val_to_sym(struct pvr2_ctrl *cptr,int msk,int val,
856 			       char *bufPtr,unsigned int bufSize,
857 			       unsigned int *len)
858 {
859 	*len = pvr2_std_id_to_str(bufPtr,bufSize,msk & val);
860 	return 0;
861 }
862 
ctrl_std_sym_to_val(struct pvr2_ctrl * cptr,const char * bufPtr,unsigned int bufSize,int * mskp,int * valp)863 static int ctrl_std_sym_to_val(struct pvr2_ctrl *cptr,
864 			       const char *bufPtr,unsigned int bufSize,
865 			       int *mskp,int *valp)
866 {
867 	v4l2_std_id id;
868 	if (!pvr2_std_str_to_id(&id, bufPtr, bufSize))
869 		return -EINVAL;
870 	if (mskp) *mskp = id;
871 	if (valp) *valp = id;
872 	return 0;
873 }
874 
ctrl_stdcur_get(struct pvr2_ctrl * cptr,int * vp)875 static int ctrl_stdcur_get(struct pvr2_ctrl *cptr,int *vp)
876 {
877 	*vp = cptr->hdw->std_mask_cur;
878 	return 0;
879 }
880 
ctrl_stdcur_set(struct pvr2_ctrl * cptr,int m,int v)881 static int ctrl_stdcur_set(struct pvr2_ctrl *cptr,int m,int v)
882 {
883 	struct pvr2_hdw *hdw = cptr->hdw;
884 	v4l2_std_id ns;
885 	ns = hdw->std_mask_cur;
886 	ns = (ns & ~m) | (v & m);
887 	if (ns == hdw->std_mask_cur) return 0;
888 	hdw->std_mask_cur = ns;
889 	hdw->std_dirty = !0;
890 	return 0;
891 }
892 
ctrl_stdcur_is_dirty(struct pvr2_ctrl * cptr)893 static int ctrl_stdcur_is_dirty(struct pvr2_ctrl *cptr)
894 {
895 	return cptr->hdw->std_dirty != 0;
896 }
897 
ctrl_stdcur_clear_dirty(struct pvr2_ctrl * cptr)898 static void ctrl_stdcur_clear_dirty(struct pvr2_ctrl *cptr)
899 {
900 	cptr->hdw->std_dirty = 0;
901 }
902 
ctrl_signal_get(struct pvr2_ctrl * cptr,int * vp)903 static int ctrl_signal_get(struct pvr2_ctrl *cptr,int *vp)
904 {
905 	struct pvr2_hdw *hdw = cptr->hdw;
906 	pvr2_hdw_status_poll(hdw);
907 	*vp = hdw->tuner_signal_info.signal;
908 	return 0;
909 }
910 
ctrl_audio_modes_present_get(struct pvr2_ctrl * cptr,int * vp)911 static int ctrl_audio_modes_present_get(struct pvr2_ctrl *cptr,int *vp)
912 {
913 	int val = 0;
914 	unsigned int subchan;
915 	struct pvr2_hdw *hdw = cptr->hdw;
916 	pvr2_hdw_status_poll(hdw);
917 	subchan = hdw->tuner_signal_info.rxsubchans;
918 	if (subchan & V4L2_TUNER_SUB_MONO) {
919 		val |= (1 << V4L2_TUNER_MODE_MONO);
920 	}
921 	if (subchan & V4L2_TUNER_SUB_STEREO) {
922 		val |= (1 << V4L2_TUNER_MODE_STEREO);
923 	}
924 	if (subchan & V4L2_TUNER_SUB_LANG1) {
925 		val |= (1 << V4L2_TUNER_MODE_LANG1);
926 	}
927 	if (subchan & V4L2_TUNER_SUB_LANG2) {
928 		val |= (1 << V4L2_TUNER_MODE_LANG2);
929 	}
930 	*vp = val;
931 	return 0;
932 }
933 
934 
935 #define DEFINT(vmin,vmax) \
936 	.type = pvr2_ctl_int, \
937 	.def.type_int.min_value = vmin, \
938 	.def.type_int.max_value = vmax
939 
940 #define DEFENUM(tab) \
941 	.type = pvr2_ctl_enum, \
942 	.def.type_enum.count = ARRAY_SIZE(tab), \
943 	.def.type_enum.value_names = tab
944 
945 #define DEFBOOL \
946 	.type = pvr2_ctl_bool
947 
948 #define DEFMASK(msk,tab) \
949 	.type = pvr2_ctl_bitmask, \
950 	.def.type_bitmask.valid_bits = msk, \
951 	.def.type_bitmask.bit_names = tab
952 
953 #define DEFREF(vname) \
954 	.set_value = ctrl_set_##vname, \
955 	.get_value = ctrl_get_##vname, \
956 	.is_dirty = ctrl_isdirty_##vname, \
957 	.clear_dirty = ctrl_cleardirty_##vname
958 
959 
960 #define VCREATE_FUNCS(vname) \
961 static int ctrl_get_##vname(struct pvr2_ctrl *cptr,int *vp) \
962 {*vp = cptr->hdw->vname##_val; return 0;} \
963 static int ctrl_set_##vname(struct pvr2_ctrl *cptr,int m,int v) \
964 {cptr->hdw->vname##_val = v; cptr->hdw->vname##_dirty = !0; return 0;} \
965 static int ctrl_isdirty_##vname(struct pvr2_ctrl *cptr) \
966 {return cptr->hdw->vname##_dirty != 0;} \
967 static void ctrl_cleardirty_##vname(struct pvr2_ctrl *cptr) \
968 {cptr->hdw->vname##_dirty = 0;}
969 
970 VCREATE_FUNCS(brightness)
971 VCREATE_FUNCS(contrast)
972 VCREATE_FUNCS(saturation)
973 VCREATE_FUNCS(hue)
974 VCREATE_FUNCS(volume)
975 VCREATE_FUNCS(balance)
976 VCREATE_FUNCS(bass)
977 VCREATE_FUNCS(treble)
978 VCREATE_FUNCS(mute)
979 VCREATE_FUNCS(cropl)
980 VCREATE_FUNCS(cropt)
981 VCREATE_FUNCS(cropw)
982 VCREATE_FUNCS(croph)
983 VCREATE_FUNCS(audiomode)
984 VCREATE_FUNCS(res_hor)
985 VCREATE_FUNCS(res_ver)
986 VCREATE_FUNCS(srate)
987 
988 /* Table definition of all controls which can be manipulated */
989 static const struct pvr2_ctl_info control_defs[] = {
990 	{
991 		.v4l_id = V4L2_CID_BRIGHTNESS,
992 		.desc = "Brightness",
993 		.name = "brightness",
994 		.default_value = 128,
995 		DEFREF(brightness),
996 		DEFINT(0,255),
997 	},{
998 		.v4l_id = V4L2_CID_CONTRAST,
999 		.desc = "Contrast",
1000 		.name = "contrast",
1001 		.default_value = 68,
1002 		DEFREF(contrast),
1003 		DEFINT(0,127),
1004 	},{
1005 		.v4l_id = V4L2_CID_SATURATION,
1006 		.desc = "Saturation",
1007 		.name = "saturation",
1008 		.default_value = 64,
1009 		DEFREF(saturation),
1010 		DEFINT(0,127),
1011 	},{
1012 		.v4l_id = V4L2_CID_HUE,
1013 		.desc = "Hue",
1014 		.name = "hue",
1015 		.default_value = 0,
1016 		DEFREF(hue),
1017 		DEFINT(-128,127),
1018 	},{
1019 		.v4l_id = V4L2_CID_AUDIO_VOLUME,
1020 		.desc = "Volume",
1021 		.name = "volume",
1022 		.default_value = 62000,
1023 		DEFREF(volume),
1024 		DEFINT(0,65535),
1025 	},{
1026 		.v4l_id = V4L2_CID_AUDIO_BALANCE,
1027 		.desc = "Balance",
1028 		.name = "balance",
1029 		.default_value = 0,
1030 		DEFREF(balance),
1031 		DEFINT(-32768,32767),
1032 	},{
1033 		.v4l_id = V4L2_CID_AUDIO_BASS,
1034 		.desc = "Bass",
1035 		.name = "bass",
1036 		.default_value = 0,
1037 		DEFREF(bass),
1038 		DEFINT(-32768,32767),
1039 	},{
1040 		.v4l_id = V4L2_CID_AUDIO_TREBLE,
1041 		.desc = "Treble",
1042 		.name = "treble",
1043 		.default_value = 0,
1044 		DEFREF(treble),
1045 		DEFINT(-32768,32767),
1046 	},{
1047 		.v4l_id = V4L2_CID_AUDIO_MUTE,
1048 		.desc = "Mute",
1049 		.name = "mute",
1050 		.default_value = 0,
1051 		DEFREF(mute),
1052 		DEFBOOL,
1053 	}, {
1054 		.desc = "Capture crop left margin",
1055 		.name = "crop_left",
1056 		.internal_id = PVR2_CID_CROPL,
1057 		.default_value = 0,
1058 		DEFREF(cropl),
1059 		DEFINT(-129, 340),
1060 		.get_min_value = ctrl_cropl_min_get,
1061 		.get_max_value = ctrl_cropl_max_get,
1062 		.get_def_value = ctrl_get_cropcapdl,
1063 	}, {
1064 		.desc = "Capture crop top margin",
1065 		.name = "crop_top",
1066 		.internal_id = PVR2_CID_CROPT,
1067 		.default_value = 0,
1068 		DEFREF(cropt),
1069 		DEFINT(-35, 544),
1070 		.get_min_value = ctrl_cropt_min_get,
1071 		.get_max_value = ctrl_cropt_max_get,
1072 		.get_def_value = ctrl_get_cropcapdt,
1073 	}, {
1074 		.desc = "Capture crop width",
1075 		.name = "crop_width",
1076 		.internal_id = PVR2_CID_CROPW,
1077 		.default_value = 720,
1078 		DEFREF(cropw),
1079 		DEFINT(0, 864),
1080 		.get_max_value = ctrl_cropw_max_get,
1081 		.get_def_value = ctrl_get_cropcapdw,
1082 	}, {
1083 		.desc = "Capture crop height",
1084 		.name = "crop_height",
1085 		.internal_id = PVR2_CID_CROPH,
1086 		.default_value = 480,
1087 		DEFREF(croph),
1088 		DEFINT(0, 576),
1089 		.get_max_value = ctrl_croph_max_get,
1090 		.get_def_value = ctrl_get_cropcapdh,
1091 	}, {
1092 		.desc = "Capture capability pixel aspect numerator",
1093 		.name = "cropcap_pixel_numerator",
1094 		.internal_id = PVR2_CID_CROPCAPPAN,
1095 		.get_value = ctrl_get_cropcappan,
1096 	}, {
1097 		.desc = "Capture capability pixel aspect denominator",
1098 		.name = "cropcap_pixel_denominator",
1099 		.internal_id = PVR2_CID_CROPCAPPAD,
1100 		.get_value = ctrl_get_cropcappad,
1101 	}, {
1102 		.desc = "Capture capability bounds top",
1103 		.name = "cropcap_bounds_top",
1104 		.internal_id = PVR2_CID_CROPCAPBT,
1105 		.get_value = ctrl_get_cropcapbt,
1106 	}, {
1107 		.desc = "Capture capability bounds left",
1108 		.name = "cropcap_bounds_left",
1109 		.internal_id = PVR2_CID_CROPCAPBL,
1110 		.get_value = ctrl_get_cropcapbl,
1111 	}, {
1112 		.desc = "Capture capability bounds width",
1113 		.name = "cropcap_bounds_width",
1114 		.internal_id = PVR2_CID_CROPCAPBW,
1115 		.get_value = ctrl_get_cropcapbw,
1116 	}, {
1117 		.desc = "Capture capability bounds height",
1118 		.name = "cropcap_bounds_height",
1119 		.internal_id = PVR2_CID_CROPCAPBH,
1120 		.get_value = ctrl_get_cropcapbh,
1121 	},{
1122 		.desc = "Video Source",
1123 		.name = "input",
1124 		.internal_id = PVR2_CID_INPUT,
1125 		.default_value = PVR2_CVAL_INPUT_TV,
1126 		.check_value = ctrl_check_input,
1127 		DEFREF(input),
1128 		DEFENUM(control_values_input),
1129 	},{
1130 		.desc = "Audio Mode",
1131 		.name = "audio_mode",
1132 		.internal_id = PVR2_CID_AUDIOMODE,
1133 		.default_value = V4L2_TUNER_MODE_STEREO,
1134 		DEFREF(audiomode),
1135 		DEFENUM(control_values_audiomode),
1136 	},{
1137 		.desc = "Horizontal capture resolution",
1138 		.name = "resolution_hor",
1139 		.internal_id = PVR2_CID_HRES,
1140 		.default_value = 720,
1141 		DEFREF(res_hor),
1142 		DEFINT(19,720),
1143 	},{
1144 		.desc = "Vertical capture resolution",
1145 		.name = "resolution_ver",
1146 		.internal_id = PVR2_CID_VRES,
1147 		.default_value = 480,
1148 		DEFREF(res_ver),
1149 		DEFINT(17,576),
1150 		/* Hook in check for video standard and adjust maximum
1151 		   depending on the standard. */
1152 		.get_max_value = ctrl_vres_max_get,
1153 		.get_min_value = ctrl_vres_min_get,
1154 	},{
1155 		.v4l_id = V4L2_CID_MPEG_AUDIO_SAMPLING_FREQ,
1156 		.default_value = V4L2_MPEG_AUDIO_SAMPLING_FREQ_48000,
1157 		.desc = "Audio Sampling Frequency",
1158 		.name = "srate",
1159 		DEFREF(srate),
1160 		DEFENUM(control_values_srate),
1161 	},{
1162 		.desc = "Tuner Frequency (Hz)",
1163 		.name = "frequency",
1164 		.internal_id = PVR2_CID_FREQUENCY,
1165 		.default_value = 0,
1166 		.set_value = ctrl_freq_set,
1167 		.get_value = ctrl_freq_get,
1168 		.is_dirty = ctrl_freq_is_dirty,
1169 		.clear_dirty = ctrl_freq_clear_dirty,
1170 		DEFINT(0,0),
1171 		/* Hook in check for input value (tv/radio) and adjust
1172 		   max/min values accordingly */
1173 		.get_max_value = ctrl_freq_max_get,
1174 		.get_min_value = ctrl_freq_min_get,
1175 	},{
1176 		.desc = "Channel",
1177 		.name = "channel",
1178 		.set_value = ctrl_channel_set,
1179 		.get_value = ctrl_channel_get,
1180 		DEFINT(0,FREQTABLE_SIZE),
1181 	},{
1182 		.desc = "Channel Program Frequency",
1183 		.name = "freq_table_value",
1184 		.set_value = ctrl_channelfreq_set,
1185 		.get_value = ctrl_channelfreq_get,
1186 		DEFINT(0,0),
1187 		/* Hook in check for input value (tv/radio) and adjust
1188 		   max/min values accordingly */
1189 		.get_max_value = ctrl_freq_max_get,
1190 		.get_min_value = ctrl_freq_min_get,
1191 	},{
1192 		.desc = "Channel Program ID",
1193 		.name = "freq_table_channel",
1194 		.set_value = ctrl_channelprog_set,
1195 		.get_value = ctrl_channelprog_get,
1196 		DEFINT(0,FREQTABLE_SIZE),
1197 	},{
1198 		.desc = "Streaming Enabled",
1199 		.name = "streaming_enabled",
1200 		.get_value = ctrl_streamingenabled_get,
1201 		DEFBOOL,
1202 	},{
1203 		.desc = "USB Speed",
1204 		.name = "usb_speed",
1205 		.get_value = ctrl_hsm_get,
1206 		DEFENUM(control_values_hsm),
1207 	},{
1208 		.desc = "Master State",
1209 		.name = "master_state",
1210 		.get_value = ctrl_masterstate_get,
1211 		DEFENUM(pvr2_state_names),
1212 	},{
1213 		.desc = "Signal Present",
1214 		.name = "signal_present",
1215 		.get_value = ctrl_signal_get,
1216 		DEFINT(0,65535),
1217 	},{
1218 		.desc = "Audio Modes Present",
1219 		.name = "audio_modes_present",
1220 		.get_value = ctrl_audio_modes_present_get,
1221 		/* For this type we "borrow" the V4L2_TUNER_MODE enum from
1222 		   v4l.  Nothing outside of this module cares about this,
1223 		   but I reuse it in order to also reuse the
1224 		   control_values_audiomode string table. */
1225 		DEFMASK(((1 << V4L2_TUNER_MODE_MONO)|
1226 			 (1 << V4L2_TUNER_MODE_STEREO)|
1227 			 (1 << V4L2_TUNER_MODE_LANG1)|
1228 			 (1 << V4L2_TUNER_MODE_LANG2)),
1229 			control_values_audiomode),
1230 	},{
1231 		.desc = "Video Standards Available Mask",
1232 		.name = "video_standard_mask_available",
1233 		.internal_id = PVR2_CID_STDAVAIL,
1234 		.skip_init = !0,
1235 		.get_value = ctrl_stdavail_get,
1236 		.set_value = ctrl_stdavail_set,
1237 		.val_to_sym = ctrl_std_val_to_sym,
1238 		.sym_to_val = ctrl_std_sym_to_val,
1239 		.type = pvr2_ctl_bitmask,
1240 	},{
1241 		.desc = "Video Standards In Use Mask",
1242 		.name = "video_standard_mask_active",
1243 		.internal_id = PVR2_CID_STDCUR,
1244 		.skip_init = !0,
1245 		.get_value = ctrl_stdcur_get,
1246 		.set_value = ctrl_stdcur_set,
1247 		.is_dirty = ctrl_stdcur_is_dirty,
1248 		.clear_dirty = ctrl_stdcur_clear_dirty,
1249 		.val_to_sym = ctrl_std_val_to_sym,
1250 		.sym_to_val = ctrl_std_sym_to_val,
1251 		.type = pvr2_ctl_bitmask,
1252 	},{
1253 		.desc = "Video Standards Detected Mask",
1254 		.name = "video_standard_mask_detected",
1255 		.internal_id = PVR2_CID_STDDETECT,
1256 		.skip_init = !0,
1257 		.get_value = ctrl_stddetect_get,
1258 		.val_to_sym = ctrl_std_val_to_sym,
1259 		.sym_to_val = ctrl_std_sym_to_val,
1260 		.type = pvr2_ctl_bitmask,
1261 	}
1262 };
1263 
1264 #define CTRLDEF_COUNT ARRAY_SIZE(control_defs)
1265 
1266 
pvr2_config_get_name(enum pvr2_config cfg)1267 const char *pvr2_config_get_name(enum pvr2_config cfg)
1268 {
1269 	switch (cfg) {
1270 	case pvr2_config_empty: return "empty";
1271 	case pvr2_config_mpeg: return "mpeg";
1272 	case pvr2_config_vbi: return "vbi";
1273 	case pvr2_config_pcm: return "pcm";
1274 	case pvr2_config_rawvideo: return "raw video";
1275 	}
1276 	return "<unknown>";
1277 }
1278 
1279 
pvr2_hdw_get_dev(struct pvr2_hdw * hdw)1280 struct usb_device *pvr2_hdw_get_dev(struct pvr2_hdw *hdw)
1281 {
1282 	return hdw->usb_dev;
1283 }
1284 
1285 
pvr2_hdw_get_sn(struct pvr2_hdw * hdw)1286 unsigned long pvr2_hdw_get_sn(struct pvr2_hdw *hdw)
1287 {
1288 	return hdw->serial_number;
1289 }
1290 
1291 
pvr2_hdw_get_bus_info(struct pvr2_hdw * hdw)1292 const char *pvr2_hdw_get_bus_info(struct pvr2_hdw *hdw)
1293 {
1294 	return hdw->bus_info;
1295 }
1296 
1297 
pvr2_hdw_get_device_identifier(struct pvr2_hdw * hdw)1298 const char *pvr2_hdw_get_device_identifier(struct pvr2_hdw *hdw)
1299 {
1300 	return hdw->identifier;
1301 }
1302 
1303 
pvr2_hdw_get_cur_freq(struct pvr2_hdw * hdw)1304 unsigned long pvr2_hdw_get_cur_freq(struct pvr2_hdw *hdw)
1305 {
1306 	return hdw->freqSelector ? hdw->freqValTelevision : hdw->freqValRadio;
1307 }
1308 
1309 /* Set the currently tuned frequency and account for all possible
1310    driver-core side effects of this action. */
pvr2_hdw_set_cur_freq(struct pvr2_hdw * hdw,unsigned long val)1311 static void pvr2_hdw_set_cur_freq(struct pvr2_hdw *hdw,unsigned long val)
1312 {
1313 	if (hdw->input_val == PVR2_CVAL_INPUT_RADIO) {
1314 		if (hdw->freqSelector) {
1315 			/* Swing over to radio frequency selection */
1316 			hdw->freqSelector = 0;
1317 			hdw->freqDirty = !0;
1318 		}
1319 		if (hdw->freqValRadio != val) {
1320 			hdw->freqValRadio = val;
1321 			hdw->freqSlotRadio = 0;
1322 			hdw->freqDirty = !0;
1323 		}
1324 	} else {
1325 		if (!(hdw->freqSelector)) {
1326 			/* Swing over to television frequency selection */
1327 			hdw->freqSelector = 1;
1328 			hdw->freqDirty = !0;
1329 		}
1330 		if (hdw->freqValTelevision != val) {
1331 			hdw->freqValTelevision = val;
1332 			hdw->freqSlotTelevision = 0;
1333 			hdw->freqDirty = !0;
1334 		}
1335 	}
1336 }
1337 
pvr2_hdw_get_unit_number(struct pvr2_hdw * hdw)1338 int pvr2_hdw_get_unit_number(struct pvr2_hdw *hdw)
1339 {
1340 	return hdw->unit_number;
1341 }
1342 
1343 
1344 /* Attempt to locate one of the given set of files.  Messages are logged
1345    appropriate to what has been found.  The return value will be 0 or
1346    greater on success (it will be the index of the file name found) and
1347    fw_entry will be filled in.  Otherwise a negative error is returned on
1348    failure.  If the return value is -ENOENT then no viable firmware file
1349    could be located. */
pvr2_locate_firmware(struct pvr2_hdw * hdw,const struct firmware ** fw_entry,const char * fwtypename,unsigned int fwcount,const char * fwnames[])1350 static int pvr2_locate_firmware(struct pvr2_hdw *hdw,
1351 				const struct firmware **fw_entry,
1352 				const char *fwtypename,
1353 				unsigned int fwcount,
1354 				const char *fwnames[])
1355 {
1356 	unsigned int idx;
1357 	int ret = -EINVAL;
1358 	for (idx = 0; idx < fwcount; idx++) {
1359 		ret = request_firmware(fw_entry,
1360 				       fwnames[idx],
1361 				       &hdw->usb_dev->dev);
1362 		if (!ret) {
1363 			trace_firmware("Located %s firmware: %s; uploading...",
1364 				       fwtypename,
1365 				       fwnames[idx]);
1366 			return idx;
1367 		}
1368 		if (ret == -ENOENT) continue;
1369 		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1370 			   "request_firmware fatal error with code=%d",ret);
1371 		return ret;
1372 	}
1373 	pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1374 		   "***WARNING*** Device %s firmware seems to be missing.",
1375 		   fwtypename);
1376 	pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1377 		   "Did you install the pvrusb2 firmware files in their proper location?");
1378 	if (fwcount == 1) {
1379 		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1380 			   "request_firmware unable to locate %s file %s",
1381 			   fwtypename,fwnames[0]);
1382 	} else {
1383 		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1384 			   "request_firmware unable to locate one of the following %s files:",
1385 			   fwtypename);
1386 		for (idx = 0; idx < fwcount; idx++) {
1387 			pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1388 				   "request_firmware: Failed to find %s",
1389 				   fwnames[idx]);
1390 		}
1391 	}
1392 	return ret;
1393 }
1394 
1395 
1396 /*
1397  * pvr2_upload_firmware1().
1398  *
1399  * Send the 8051 firmware to the device.  After the upload, arrange for
1400  * device to re-enumerate.
1401  *
1402  * NOTE : the pointer to the firmware data given by request_firmware()
1403  * is not suitable for an usb transaction.
1404  *
1405  */
pvr2_upload_firmware1(struct pvr2_hdw * hdw)1406 static int pvr2_upload_firmware1(struct pvr2_hdw *hdw)
1407 {
1408 	const struct firmware *fw_entry = NULL;
1409 	void  *fw_ptr;
1410 	unsigned int pipe;
1411 	unsigned int fwsize;
1412 	int ret;
1413 	u16 address;
1414 
1415 	if (!hdw->hdw_desc->fx2_firmware.cnt) {
1416 		hdw->fw1_state = FW1_STATE_OK;
1417 		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1418 			   "Connected device type defines no firmware to upload; ignoring firmware");
1419 		return -ENOTTY;
1420 	}
1421 
1422 	hdw->fw1_state = FW1_STATE_FAILED; // default result
1423 
1424 	trace_firmware("pvr2_upload_firmware1");
1425 
1426 	ret = pvr2_locate_firmware(hdw,&fw_entry,"fx2 controller",
1427 				   hdw->hdw_desc->fx2_firmware.cnt,
1428 				   hdw->hdw_desc->fx2_firmware.lst);
1429 	if (ret < 0) {
1430 		if (ret == -ENOENT) hdw->fw1_state = FW1_STATE_MISSING;
1431 		return ret;
1432 	}
1433 
1434 	usb_clear_halt(hdw->usb_dev, usb_sndbulkpipe(hdw->usb_dev, 0 & 0x7f));
1435 
1436 	pipe = usb_sndctrlpipe(hdw->usb_dev, 0);
1437 	fwsize = fw_entry->size;
1438 
1439 	if ((fwsize != 0x2000) &&
1440 	    (!(hdw->hdw_desc->flag_fx2_16kb && (fwsize == 0x4000)))) {
1441 		if (hdw->hdw_desc->flag_fx2_16kb) {
1442 			pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1443 				   "Wrong fx2 firmware size (expected 8192 or 16384, got %u)",
1444 				   fwsize);
1445 		} else {
1446 			pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1447 				   "Wrong fx2 firmware size (expected 8192, got %u)",
1448 				   fwsize);
1449 		}
1450 		release_firmware(fw_entry);
1451 		return -ENOMEM;
1452 	}
1453 
1454 	fw_ptr = kmalloc(0x800, GFP_KERNEL);
1455 	if (fw_ptr == NULL){
1456 		release_firmware(fw_entry);
1457 		return -ENOMEM;
1458 	}
1459 
1460 	/* We have to hold the CPU during firmware upload. */
1461 	pvr2_hdw_cpureset_assert(hdw,1);
1462 
1463 	/* upload the firmware to address 0000-1fff in 2048 (=0x800) bytes
1464 	   chunk. */
1465 
1466 	ret = 0;
1467 	for (address = 0; address < fwsize; address += 0x800) {
1468 		memcpy(fw_ptr, fw_entry->data + address, 0x800);
1469 		ret += usb_control_msg(hdw->usb_dev, pipe, 0xa0, 0x40, address,
1470 				       0, fw_ptr, 0x800, 1000);
1471 	}
1472 
1473 	trace_firmware("Upload done, releasing device's CPU");
1474 
1475 	/* Now release the CPU.  It will disconnect and reconnect later. */
1476 	pvr2_hdw_cpureset_assert(hdw,0);
1477 
1478 	kfree(fw_ptr);
1479 	release_firmware(fw_entry);
1480 
1481 	trace_firmware("Upload done (%d bytes sent)",ret);
1482 
1483 	/* We should have written fwsize bytes */
1484 	if (ret == fwsize) {
1485 		hdw->fw1_state = FW1_STATE_RELOAD;
1486 		return 0;
1487 	}
1488 
1489 	return -EIO;
1490 }
1491 
1492 
1493 /*
1494  * pvr2_upload_firmware2()
1495  *
1496  * This uploads encoder firmware on endpoint 2.
1497  *
1498  */
1499 
pvr2_upload_firmware2(struct pvr2_hdw * hdw)1500 int pvr2_upload_firmware2(struct pvr2_hdw *hdw)
1501 {
1502 	const struct firmware *fw_entry = NULL;
1503 	void  *fw_ptr;
1504 	unsigned int pipe, fw_len, fw_done, bcnt, icnt;
1505 	int actual_length;
1506 	int ret = 0;
1507 	int fwidx;
1508 	static const char *fw_files[] = {
1509 		CX2341X_FIRM_ENC_FILENAME,
1510 	};
1511 
1512 	if (hdw->hdw_desc->flag_skip_cx23416_firmware) {
1513 		return 0;
1514 	}
1515 
1516 	trace_firmware("pvr2_upload_firmware2");
1517 
1518 	ret = pvr2_locate_firmware(hdw,&fw_entry,"encoder",
1519 				   ARRAY_SIZE(fw_files), fw_files);
1520 	if (ret < 0) return ret;
1521 	fwidx = ret;
1522 	ret = 0;
1523 	/* Since we're about to completely reinitialize the encoder,
1524 	   invalidate our cached copy of its configuration state.  Next
1525 	   time we configure the encoder, then we'll fully configure it. */
1526 	hdw->enc_cur_valid = 0;
1527 
1528 	/* Encoder is about to be reset so note that as far as we're
1529 	   concerned now, the encoder has never been run. */
1530 	timer_delete_sync(&hdw->encoder_run_timer);
1531 	if (hdw->state_encoder_runok) {
1532 		hdw->state_encoder_runok = 0;
1533 		trace_stbit("state_encoder_runok",hdw->state_encoder_runok);
1534 	}
1535 
1536 	/* First prepare firmware loading */
1537 	ret |= pvr2_write_register(hdw, 0x0048, 0xffffffff); /*interrupt mask*/
1538 	ret |= pvr2_hdw_gpio_chg_dir(hdw,0xffffffff,0x00000088); /*gpio dir*/
1539 	ret |= pvr2_hdw_gpio_chg_out(hdw,0xffffffff,0x00000008); /*gpio output state*/
1540 	ret |= pvr2_hdw_cmd_deep_reset(hdw);
1541 	ret |= pvr2_write_register(hdw, 0xa064, 0x00000000); /*APU command*/
1542 	ret |= pvr2_hdw_gpio_chg_dir(hdw,0xffffffff,0x00000408); /*gpio dir*/
1543 	ret |= pvr2_hdw_gpio_chg_out(hdw,0xffffffff,0x00000008); /*gpio output state*/
1544 	ret |= pvr2_write_register(hdw, 0x9058, 0xffffffed); /*VPU ctrl*/
1545 	ret |= pvr2_write_register(hdw, 0x9054, 0xfffffffd); /*reset hw blocks*/
1546 	ret |= pvr2_write_register(hdw, 0x07f8, 0x80000800); /*encoder SDRAM refresh*/
1547 	ret |= pvr2_write_register(hdw, 0x07fc, 0x0000001a); /*encoder SDRAM pre-charge*/
1548 	ret |= pvr2_write_register(hdw, 0x0700, 0x00000000); /*I2C clock*/
1549 	ret |= pvr2_write_register(hdw, 0xaa00, 0x00000000); /*unknown*/
1550 	ret |= pvr2_write_register(hdw, 0xaa04, 0x00057810); /*unknown*/
1551 	ret |= pvr2_write_register(hdw, 0xaa10, 0x00148500); /*unknown*/
1552 	ret |= pvr2_write_register(hdw, 0xaa18, 0x00840000); /*unknown*/
1553 	ret |= pvr2_issue_simple_cmd(hdw,FX2CMD_FWPOST1);
1554 	ret |= pvr2_issue_simple_cmd(hdw,FX2CMD_MEMSEL | (1 << 8) | (0 << 16));
1555 
1556 	if (ret) {
1557 		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1558 			   "firmware2 upload prep failed, ret=%d",ret);
1559 		release_firmware(fw_entry);
1560 		goto done;
1561 	}
1562 
1563 	/* Now send firmware */
1564 
1565 	fw_len = fw_entry->size;
1566 
1567 	if (fw_len % sizeof(u32)) {
1568 		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1569 			   "size of %s firmware must be a multiple of %zu bytes",
1570 			   fw_files[fwidx],sizeof(u32));
1571 		release_firmware(fw_entry);
1572 		ret = -EINVAL;
1573 		goto done;
1574 	}
1575 
1576 	fw_ptr = kmalloc(FIRMWARE_CHUNK_SIZE, GFP_KERNEL);
1577 	if (fw_ptr == NULL){
1578 		release_firmware(fw_entry);
1579 		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1580 			   "failed to allocate memory for firmware2 upload");
1581 		ret = -ENOMEM;
1582 		goto done;
1583 	}
1584 
1585 	pipe = usb_sndbulkpipe(hdw->usb_dev, PVR2_FIRMWARE_ENDPOINT);
1586 
1587 	fw_done = 0;
1588 	for (fw_done = 0; fw_done < fw_len;) {
1589 		bcnt = fw_len - fw_done;
1590 		if (bcnt > FIRMWARE_CHUNK_SIZE) bcnt = FIRMWARE_CHUNK_SIZE;
1591 		memcpy(fw_ptr, fw_entry->data + fw_done, bcnt);
1592 		/* Usbsnoop log shows that we must swap bytes... */
1593 		/* Some background info: The data being swapped here is a
1594 		   firmware image destined for the mpeg encoder chip that
1595 		   lives at the other end of a USB endpoint.  The encoder
1596 		   chip always talks in 32 bit chunks and its storage is
1597 		   organized into 32 bit words.  However from the file
1598 		   system to the encoder chip everything is purely a byte
1599 		   stream.  The firmware file's contents are always 32 bit
1600 		   swapped from what the encoder expects.  Thus the need
1601 		   always exists to swap the bytes regardless of the endian
1602 		   type of the host processor and therefore swab32() makes
1603 		   the most sense. */
1604 		for (icnt = 0; icnt < bcnt/4 ; icnt++)
1605 			((u32 *)fw_ptr)[icnt] = swab32(((u32 *)fw_ptr)[icnt]);
1606 
1607 		ret |= usb_bulk_msg(hdw->usb_dev, pipe, fw_ptr,bcnt,
1608 				    &actual_length, 1000);
1609 		ret |= (actual_length != bcnt);
1610 		if (ret) break;
1611 		fw_done += bcnt;
1612 	}
1613 
1614 	trace_firmware("upload of %s : %i / %i ",
1615 		       fw_files[fwidx],fw_done,fw_len);
1616 
1617 	kfree(fw_ptr);
1618 	release_firmware(fw_entry);
1619 
1620 	if (ret) {
1621 		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1622 			   "firmware2 upload transfer failure");
1623 		goto done;
1624 	}
1625 
1626 	/* Finish upload */
1627 
1628 	ret |= pvr2_write_register(hdw, 0x9054, 0xffffffff); /*reset hw blocks*/
1629 	ret |= pvr2_write_register(hdw, 0x9058, 0xffffffe8); /*VPU ctrl*/
1630 	ret |= pvr2_issue_simple_cmd(hdw,FX2CMD_MEMSEL | (1 << 8) | (0 << 16));
1631 
1632 	if (ret) {
1633 		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1634 			   "firmware2 upload post-proc failure");
1635 	}
1636 
1637  done:
1638 	if (hdw->hdw_desc->signal_routing_scheme ==
1639 	    PVR2_ROUTING_SCHEME_GOTVIEW) {
1640 		/* Ensure that GPIO 11 is set to output for GOTVIEW
1641 		   hardware. */
1642 		pvr2_hdw_gpio_chg_dir(hdw,(1 << 11),~0);
1643 	}
1644 	return ret;
1645 }
1646 
1647 
pvr2_get_state_name(unsigned int st)1648 static const char *pvr2_get_state_name(unsigned int st)
1649 {
1650 	if (st < ARRAY_SIZE(pvr2_state_names)) {
1651 		return pvr2_state_names[st];
1652 	}
1653 	return "???";
1654 }
1655 
pvr2_decoder_enable(struct pvr2_hdw * hdw,int enablefl)1656 static int pvr2_decoder_enable(struct pvr2_hdw *hdw,int enablefl)
1657 {
1658 	/* Even though we really only care about the video decoder chip at
1659 	   this point, we'll broadcast stream on/off to all sub-devices
1660 	   anyway, just in case somebody else wants to hear the
1661 	   command... */
1662 	pvr2_trace(PVR2_TRACE_CHIPS, "subdev v4l2 stream=%s",
1663 		   (enablefl ? "on" : "off"));
1664 	v4l2_device_call_all(&hdw->v4l2_dev, 0, video, s_stream, enablefl);
1665 	v4l2_device_call_all(&hdw->v4l2_dev, 0, audio, s_stream, enablefl);
1666 	if (hdw->decoder_client_id) {
1667 		/* We get here if the encoder has been noticed.  Otherwise
1668 		   we'll issue a warning to the user (which should
1669 		   normally never happen). */
1670 		return 0;
1671 	}
1672 	if (!hdw->flag_decoder_missed) {
1673 		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1674 			   "***WARNING*** No decoder present");
1675 		hdw->flag_decoder_missed = !0;
1676 		trace_stbit("flag_decoder_missed",
1677 			    hdw->flag_decoder_missed);
1678 	}
1679 	return -EIO;
1680 }
1681 
1682 
pvr2_hdw_get_state(struct pvr2_hdw * hdw)1683 int pvr2_hdw_get_state(struct pvr2_hdw *hdw)
1684 {
1685 	return hdw->master_state;
1686 }
1687 
1688 
pvr2_hdw_untrip_unlocked(struct pvr2_hdw * hdw)1689 static int pvr2_hdw_untrip_unlocked(struct pvr2_hdw *hdw)
1690 {
1691 	if (!hdw->flag_tripped) return 0;
1692 	hdw->flag_tripped = 0;
1693 	pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1694 		   "Clearing driver error status");
1695 	return !0;
1696 }
1697 
1698 
pvr2_hdw_untrip(struct pvr2_hdw * hdw)1699 int pvr2_hdw_untrip(struct pvr2_hdw *hdw)
1700 {
1701 	int fl;
1702 	LOCK_TAKE(hdw->big_lock); do {
1703 		fl = pvr2_hdw_untrip_unlocked(hdw);
1704 	} while (0); LOCK_GIVE(hdw->big_lock);
1705 	if (fl) pvr2_hdw_state_sched(hdw);
1706 	return 0;
1707 }
1708 
1709 
1710 
1711 
pvr2_hdw_get_streaming(struct pvr2_hdw * hdw)1712 int pvr2_hdw_get_streaming(struct pvr2_hdw *hdw)
1713 {
1714 	return hdw->state_pipeline_req != 0;
1715 }
1716 
1717 
pvr2_hdw_set_streaming(struct pvr2_hdw * hdw,int enable_flag)1718 int pvr2_hdw_set_streaming(struct pvr2_hdw *hdw,int enable_flag)
1719 {
1720 	int ret,st;
1721 	LOCK_TAKE(hdw->big_lock);
1722 	pvr2_hdw_untrip_unlocked(hdw);
1723 	if (!enable_flag != !hdw->state_pipeline_req) {
1724 		hdw->state_pipeline_req = enable_flag != 0;
1725 		pvr2_trace(PVR2_TRACE_START_STOP,
1726 			   "/*--TRACE_STREAM--*/ %s",
1727 			   enable_flag ? "enable" : "disable");
1728 	}
1729 	pvr2_hdw_state_sched(hdw);
1730 	LOCK_GIVE(hdw->big_lock);
1731 	if ((ret = pvr2_hdw_wait(hdw,0)) < 0) return ret;
1732 	if (enable_flag) {
1733 		while ((st = hdw->master_state) != PVR2_STATE_RUN) {
1734 			if (st != PVR2_STATE_READY) return -EIO;
1735 			if ((ret = pvr2_hdw_wait(hdw,st)) < 0) return ret;
1736 		}
1737 	}
1738 	return 0;
1739 }
1740 
1741 
pvr2_hdw_set_stream_type(struct pvr2_hdw * hdw,enum pvr2_config config)1742 int pvr2_hdw_set_stream_type(struct pvr2_hdw *hdw,enum pvr2_config config)
1743 {
1744 	int fl;
1745 	LOCK_TAKE(hdw->big_lock);
1746 	if ((fl = (hdw->desired_stream_type != config)) != 0) {
1747 		hdw->desired_stream_type = config;
1748 		hdw->state_pipeline_config = 0;
1749 		trace_stbit("state_pipeline_config",
1750 			    hdw->state_pipeline_config);
1751 		pvr2_hdw_state_sched(hdw);
1752 	}
1753 	LOCK_GIVE(hdw->big_lock);
1754 	if (fl) return 0;
1755 	return pvr2_hdw_wait(hdw,0);
1756 }
1757 
1758 
get_default_tuner_type(struct pvr2_hdw * hdw)1759 static int get_default_tuner_type(struct pvr2_hdw *hdw)
1760 {
1761 	int unit_number = hdw->unit_number;
1762 	int tp = -1;
1763 	if ((unit_number >= 0) && (unit_number < PVR_NUM)) {
1764 		tp = tuner[unit_number];
1765 	}
1766 	if (tp < 0) return -EINVAL;
1767 	hdw->tuner_type = tp;
1768 	hdw->tuner_updated = !0;
1769 	return 0;
1770 }
1771 
1772 
get_default_standard(struct pvr2_hdw * hdw)1773 static v4l2_std_id get_default_standard(struct pvr2_hdw *hdw)
1774 {
1775 	int unit_number = hdw->unit_number;
1776 	int tp = 0;
1777 	if ((unit_number >= 0) && (unit_number < PVR_NUM)) {
1778 		tp = video_std[unit_number];
1779 		if (tp) return tp;
1780 	}
1781 	return 0;
1782 }
1783 
1784 
get_default_error_tolerance(struct pvr2_hdw * hdw)1785 static unsigned int get_default_error_tolerance(struct pvr2_hdw *hdw)
1786 {
1787 	int unit_number = hdw->unit_number;
1788 	int tp = 0;
1789 	if ((unit_number >= 0) && (unit_number < PVR_NUM)) {
1790 		tp = tolerance[unit_number];
1791 	}
1792 	return tp;
1793 }
1794 
1795 
pvr2_hdw_check_firmware(struct pvr2_hdw * hdw)1796 static int pvr2_hdw_check_firmware(struct pvr2_hdw *hdw)
1797 {
1798 	/* Try a harmless request to fetch the eeprom's address over
1799 	   endpoint 1.  See what happens.  Only the full FX2 image can
1800 	   respond to this.  If this probe fails then likely the FX2
1801 	   firmware needs be loaded. */
1802 	int result;
1803 	LOCK_TAKE(hdw->ctl_lock); do {
1804 		hdw->cmd_buffer[0] = FX2CMD_GET_EEPROM_ADDR;
1805 		result = pvr2_send_request_ex(hdw,HZ*1,!0,
1806 					   hdw->cmd_buffer,1,
1807 					   hdw->cmd_buffer,1);
1808 		if (result < 0) break;
1809 	} while(0); LOCK_GIVE(hdw->ctl_lock);
1810 	if (result) {
1811 		pvr2_trace(PVR2_TRACE_INIT,
1812 			   "Probe of device endpoint 1 result status %d",
1813 			   result);
1814 	} else {
1815 		pvr2_trace(PVR2_TRACE_INIT,
1816 			   "Probe of device endpoint 1 succeeded");
1817 	}
1818 	return result == 0;
1819 }
1820 
1821 struct pvr2_std_hack {
1822 	v4l2_std_id pat;  /* Pattern to match */
1823 	v4l2_std_id msk;  /* Which bits we care about */
1824 	v4l2_std_id std;  /* What additional standards or default to set */
1825 };
1826 
1827 /* This data structure labels specific combinations of standards from
1828    tveeprom that we'll try to recognize.  If we recognize one, then assume
1829    a specified default standard to use.  This is here because tveeprom only
1830    tells us about available standards not the intended default standard (if
1831    any) for the device in question.  We guess the default based on what has
1832    been reported as available.  Note that this is only for guessing a
1833    default - which can always be overridden explicitly - and if the user
1834    has otherwise named a default then that default will always be used in
1835    place of this table. */
1836 static const struct pvr2_std_hack std_eeprom_maps[] = {
1837 	{	/* PAL(B/G) */
1838 		.pat = V4L2_STD_B|V4L2_STD_GH,
1839 		.std = V4L2_STD_PAL_B|V4L2_STD_PAL_B1|V4L2_STD_PAL_G,
1840 	},
1841 	{	/* NTSC(M) */
1842 		.pat = V4L2_STD_MN,
1843 		.std = V4L2_STD_NTSC_M,
1844 	},
1845 	{	/* PAL(I) */
1846 		.pat = V4L2_STD_PAL_I,
1847 		.std = V4L2_STD_PAL_I,
1848 	},
1849 	{	/* SECAM(L/L') */
1850 		.pat = V4L2_STD_SECAM_L|V4L2_STD_SECAM_LC,
1851 		.std = V4L2_STD_SECAM_L|V4L2_STD_SECAM_LC,
1852 	},
1853 	{	/* PAL(D/D1/K) */
1854 		.pat = V4L2_STD_DK,
1855 		.std = V4L2_STD_PAL_D|V4L2_STD_PAL_D1|V4L2_STD_PAL_K,
1856 	},
1857 };
1858 
pvr2_hdw_setup_std(struct pvr2_hdw * hdw)1859 static void pvr2_hdw_setup_std(struct pvr2_hdw *hdw)
1860 {
1861 	char buf[40];
1862 	unsigned int bcnt;
1863 	v4l2_std_id std1,std2,std3;
1864 
1865 	std1 = get_default_standard(hdw);
1866 	std3 = std1 ? 0 : hdw->hdw_desc->default_std_mask;
1867 
1868 	bcnt = pvr2_std_id_to_str(buf,sizeof(buf),hdw->std_mask_eeprom);
1869 	pvr2_trace(PVR2_TRACE_STD,
1870 		   "Supported video standard(s) reported available in hardware: %.*s",
1871 		   bcnt,buf);
1872 
1873 	hdw->std_mask_avail = hdw->std_mask_eeprom;
1874 
1875 	std2 = (std1|std3) & ~hdw->std_mask_avail;
1876 	if (std2) {
1877 		bcnt = pvr2_std_id_to_str(buf,sizeof(buf),std2);
1878 		pvr2_trace(PVR2_TRACE_STD,
1879 			   "Expanding supported video standards to include: %.*s",
1880 			   bcnt,buf);
1881 		hdw->std_mask_avail |= std2;
1882 	}
1883 
1884 	hdw->std_info_cur.def.type_bitmask.valid_bits = hdw->std_mask_avail;
1885 
1886 	if (std1) {
1887 		bcnt = pvr2_std_id_to_str(buf,sizeof(buf),std1);
1888 		pvr2_trace(PVR2_TRACE_STD,
1889 			   "Initial video standard forced to %.*s",
1890 			   bcnt,buf);
1891 		hdw->std_mask_cur = std1;
1892 		hdw->std_dirty = !0;
1893 		return;
1894 	}
1895 	if (std3) {
1896 		bcnt = pvr2_std_id_to_str(buf,sizeof(buf),std3);
1897 		pvr2_trace(PVR2_TRACE_STD,
1898 			   "Initial video standard (determined by device type): %.*s",
1899 			   bcnt, buf);
1900 		hdw->std_mask_cur = std3;
1901 		hdw->std_dirty = !0;
1902 		return;
1903 	}
1904 
1905 	{
1906 		unsigned int idx;
1907 		for (idx = 0; idx < ARRAY_SIZE(std_eeprom_maps); idx++) {
1908 			if (std_eeprom_maps[idx].msk ?
1909 			    ((std_eeprom_maps[idx].pat ^
1910 			     hdw->std_mask_eeprom) &
1911 			     std_eeprom_maps[idx].msk) :
1912 			    (std_eeprom_maps[idx].pat !=
1913 			     hdw->std_mask_eeprom)) continue;
1914 			bcnt = pvr2_std_id_to_str(buf,sizeof(buf),
1915 						  std_eeprom_maps[idx].std);
1916 			pvr2_trace(PVR2_TRACE_STD,
1917 				   "Initial video standard guessed as %.*s",
1918 				   bcnt,buf);
1919 			hdw->std_mask_cur = std_eeprom_maps[idx].std;
1920 			hdw->std_dirty = !0;
1921 			return;
1922 		}
1923 	}
1924 
1925 }
1926 
1927 
pvr2_copy_i2c_addr_list(unsigned short * dst,const unsigned char * src,unsigned int dst_max)1928 static unsigned int pvr2_copy_i2c_addr_list(
1929 	unsigned short *dst, const unsigned char *src,
1930 	unsigned int dst_max)
1931 {
1932 	unsigned int cnt = 0;
1933 	if (!src) return 0;
1934 	while (src[cnt] && (cnt + 1) < dst_max) {
1935 		dst[cnt] = src[cnt];
1936 		cnt++;
1937 	}
1938 	dst[cnt] = I2C_CLIENT_END;
1939 	return cnt;
1940 }
1941 
1942 
pvr2_hdw_cx25840_vbi_hack(struct pvr2_hdw * hdw)1943 static void pvr2_hdw_cx25840_vbi_hack(struct pvr2_hdw *hdw)
1944 {
1945 	/*
1946 	  Mike Isely <isely@pobox.com> 19-Nov-2006 - This bit of nuttiness
1947 	  for cx25840 causes that module to correctly set up its video
1948 	  scaling.  This is really a problem in the cx25840 module itself,
1949 	  but we work around it here.  The problem has not been seen in
1950 	  ivtv because there VBI is supported and set up.  We don't do VBI
1951 	  here (at least not yet) and thus we never attempted to even set
1952 	  it up.
1953 	*/
1954 	struct v4l2_format fmt;
1955 	if (hdw->decoder_client_id != PVR2_CLIENT_ID_CX25840) {
1956 		/* We're not using a cx25840 so don't enable the hack */
1957 		return;
1958 	}
1959 
1960 	pvr2_trace(PVR2_TRACE_INIT,
1961 		   "Module ID %u: Executing cx25840 VBI hack",
1962 		   hdw->decoder_client_id);
1963 	memset(&fmt, 0, sizeof(fmt));
1964 	fmt.type = V4L2_BUF_TYPE_SLICED_VBI_CAPTURE;
1965 	fmt.fmt.sliced.service_lines[0][21] = V4L2_SLICED_CAPTION_525;
1966 	fmt.fmt.sliced.service_lines[1][21] = V4L2_SLICED_CAPTION_525;
1967 	v4l2_device_call_all(&hdw->v4l2_dev, hdw->decoder_client_id,
1968 			     vbi, s_sliced_fmt, &fmt.fmt.sliced);
1969 }
1970 
1971 
pvr2_hdw_load_subdev(struct pvr2_hdw * hdw,const struct pvr2_device_client_desc * cd)1972 static int pvr2_hdw_load_subdev(struct pvr2_hdw *hdw,
1973 				const struct pvr2_device_client_desc *cd)
1974 {
1975 	const char *fname;
1976 	unsigned char mid;
1977 	struct v4l2_subdev *sd;
1978 	unsigned int i2ccnt;
1979 	const unsigned char *p;
1980 	/* Arbitrary count - max # i2c addresses we will probe */
1981 	unsigned short i2caddr[25];
1982 
1983 	mid = cd->module_id;
1984 	fname = (mid < ARRAY_SIZE(module_names)) ? module_names[mid] : NULL;
1985 	if (!fname) {
1986 		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1987 			   "Module ID %u for device %s has no name?  The driver might have a configuration problem.",
1988 			   mid,
1989 			   hdw->hdw_desc->description);
1990 		return -EINVAL;
1991 	}
1992 	pvr2_trace(PVR2_TRACE_INIT,
1993 		   "Module ID %u (%s) for device %s being loaded...",
1994 		   mid, fname,
1995 		   hdw->hdw_desc->description);
1996 
1997 	i2ccnt = pvr2_copy_i2c_addr_list(i2caddr, cd->i2c_address_list,
1998 					 ARRAY_SIZE(i2caddr));
1999 	if (!i2ccnt && ((p = (mid < ARRAY_SIZE(module_i2c_addresses)) ?
2000 			 module_i2c_addresses[mid] : NULL) != NULL)) {
2001 		/* Second chance: Try default i2c address list */
2002 		i2ccnt = pvr2_copy_i2c_addr_list(i2caddr, p,
2003 						 ARRAY_SIZE(i2caddr));
2004 		if (i2ccnt) {
2005 			pvr2_trace(PVR2_TRACE_INIT,
2006 				   "Module ID %u: Using default i2c address list",
2007 				   mid);
2008 		}
2009 	}
2010 
2011 	if (!i2ccnt) {
2012 		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2013 			   "Module ID %u (%s) for device %s: No i2c addresses.	The driver might have a configuration problem.",
2014 			   mid, fname, hdw->hdw_desc->description);
2015 		return -EINVAL;
2016 	}
2017 
2018 	if (i2ccnt == 1) {
2019 		pvr2_trace(PVR2_TRACE_INIT,
2020 			   "Module ID %u: Setting up with specified i2c address 0x%x",
2021 			   mid, i2caddr[0]);
2022 		sd = v4l2_i2c_new_subdev(&hdw->v4l2_dev, &hdw->i2c_adap,
2023 					 fname, i2caddr[0], NULL);
2024 	} else {
2025 		pvr2_trace(PVR2_TRACE_INIT,
2026 			   "Module ID %u: Setting up with address probe list",
2027 			   mid);
2028 		sd = v4l2_i2c_new_subdev(&hdw->v4l2_dev, &hdw->i2c_adap,
2029 					 fname, 0, i2caddr);
2030 	}
2031 
2032 	if (!sd) {
2033 		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2034 			   "Module ID %u (%s) for device %s failed to load.  Possible missing sub-device kernel module or initialization failure within module.",
2035 			   mid, fname, hdw->hdw_desc->description);
2036 		return -EIO;
2037 	}
2038 
2039 	/* Tag this sub-device instance with the module ID we know about.
2040 	   In other places we'll use that tag to determine if the instance
2041 	   requires special handling. */
2042 	sd->grp_id = mid;
2043 
2044 	pvr2_trace(PVR2_TRACE_INFO, "Attached sub-driver %s", fname);
2045 
2046 
2047 	/* client-specific setup... */
2048 	switch (mid) {
2049 	case PVR2_CLIENT_ID_CX25840:
2050 	case PVR2_CLIENT_ID_SAA7115:
2051 		hdw->decoder_client_id = mid;
2052 		break;
2053 	default: break;
2054 	}
2055 
2056 	return 0;
2057 }
2058 
2059 
pvr2_hdw_load_modules(struct pvr2_hdw * hdw)2060 static void pvr2_hdw_load_modules(struct pvr2_hdw *hdw)
2061 {
2062 	unsigned int idx;
2063 	const struct pvr2_string_table *cm;
2064 	const struct pvr2_device_client_table *ct;
2065 	int okFl = !0;
2066 
2067 	cm = &hdw->hdw_desc->client_modules;
2068 	for (idx = 0; idx < cm->cnt; idx++) {
2069 		request_module(cm->lst[idx]);
2070 	}
2071 
2072 	ct = &hdw->hdw_desc->client_table;
2073 	for (idx = 0; idx < ct->cnt; idx++) {
2074 		if (pvr2_hdw_load_subdev(hdw, &ct->lst[idx]) < 0) okFl = 0;
2075 	}
2076 	if (!okFl) {
2077 		hdw->flag_modulefail = !0;
2078 		pvr2_hdw_render_useless(hdw);
2079 	}
2080 }
2081 
2082 
pvr2_hdw_setup_low(struct pvr2_hdw * hdw)2083 static void pvr2_hdw_setup_low(struct pvr2_hdw *hdw)
2084 {
2085 	int ret;
2086 	unsigned int idx;
2087 	struct pvr2_ctrl *cptr;
2088 	int reloadFl = 0;
2089 	if (hdw->hdw_desc->fx2_firmware.cnt) {
2090 		if (!reloadFl) {
2091 			reloadFl =
2092 				(hdw->usb_intf->cur_altsetting->desc.bNumEndpoints
2093 				 == 0);
2094 			if (reloadFl) {
2095 				pvr2_trace(PVR2_TRACE_INIT,
2096 					   "USB endpoint config looks strange; possibly firmware needs to be loaded");
2097 			}
2098 		}
2099 		if (!reloadFl) {
2100 			reloadFl = !pvr2_hdw_check_firmware(hdw);
2101 			if (reloadFl) {
2102 				pvr2_trace(PVR2_TRACE_INIT,
2103 					   "Check for FX2 firmware failed; possibly firmware needs to be loaded");
2104 			}
2105 		}
2106 		if (reloadFl) {
2107 			if (pvr2_upload_firmware1(hdw) != 0) {
2108 				pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2109 					   "Failure uploading firmware1");
2110 			}
2111 			return;
2112 		}
2113 	}
2114 	hdw->fw1_state = FW1_STATE_OK;
2115 
2116 	if (!pvr2_hdw_dev_ok(hdw)) return;
2117 
2118 	hdw->force_dirty = !0;
2119 
2120 	if (!hdw->hdw_desc->flag_no_powerup) {
2121 		pvr2_hdw_cmd_powerup(hdw);
2122 		if (!pvr2_hdw_dev_ok(hdw)) return;
2123 	}
2124 
2125 	/* Take the IR chip out of reset, if appropriate */
2126 	if (hdw->ir_scheme_active == PVR2_IR_SCHEME_ZILOG) {
2127 		pvr2_issue_simple_cmd(hdw,
2128 				      FX2CMD_HCW_ZILOG_RESET |
2129 				      (1 << 8) |
2130 				      ((0) << 16));
2131 	}
2132 
2133 	/* This step MUST happen after the earlier powerup step */
2134 	pvr2_i2c_core_init(hdw);
2135 	if (!pvr2_hdw_dev_ok(hdw)) return;
2136 
2137 	/* Reset demod only on Hauppauge 160xxx platform */
2138 	if (le16_to_cpu(hdw->usb_dev->descriptor.idVendor) == 0x2040 &&
2139 	    (le16_to_cpu(hdw->usb_dev->descriptor.idProduct) == 0x7502 ||
2140 	     le16_to_cpu(hdw->usb_dev->descriptor.idProduct) == 0x7510)) {
2141 		pr_info("%s(): resetting 160xxx demod\n", __func__);
2142 		/* TODO: not sure this is proper place to reset once only */
2143 		pvr2_issue_simple_cmd(hdw,
2144 				      FX2CMD_HCW_DEMOD_RESET_PIN |
2145 				      (1 << 8) |
2146 				      ((0) << 16));
2147 		usleep_range(10000, 10500);
2148 		pvr2_issue_simple_cmd(hdw,
2149 				      FX2CMD_HCW_DEMOD_RESET_PIN |
2150 				      (1 << 8) |
2151 				      ((1) << 16));
2152 		usleep_range(10000, 10500);
2153 	}
2154 
2155 	pvr2_hdw_load_modules(hdw);
2156 	if (!pvr2_hdw_dev_ok(hdw)) return;
2157 
2158 	v4l2_device_call_all(&hdw->v4l2_dev, 0, core, load_fw);
2159 
2160 	for (idx = 0; idx < CTRLDEF_COUNT; idx++) {
2161 		cptr = hdw->controls + idx;
2162 		if (cptr->info->skip_init) continue;
2163 		if (!cptr->info->set_value) continue;
2164 		cptr->info->set_value(cptr,~0,cptr->info->default_value);
2165 	}
2166 
2167 	pvr2_hdw_cx25840_vbi_hack(hdw);
2168 
2169 	/* Set up special default values for the television and radio
2170 	   frequencies here.  It's not really important what these defaults
2171 	   are, but I set them to something usable in the Chicago area just
2172 	   to make driver testing a little easier. */
2173 
2174 	hdw->freqValTelevision = default_tv_freq;
2175 	hdw->freqValRadio = default_radio_freq;
2176 
2177 	// Do not use pvr2_reset_ctl_endpoints() here.  It is not
2178 	// thread-safe against the normal pvr2_send_request() mechanism.
2179 	// (We should make it thread safe).
2180 
2181 	if (hdw->hdw_desc->flag_has_hauppauge_rom) {
2182 		ret = pvr2_hdw_get_eeprom_addr(hdw);
2183 		if (!pvr2_hdw_dev_ok(hdw)) return;
2184 		if (ret < 0) {
2185 			pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2186 				   "Unable to determine location of eeprom, skipping");
2187 		} else {
2188 			hdw->eeprom_addr = ret;
2189 			pvr2_eeprom_analyze(hdw);
2190 			if (!pvr2_hdw_dev_ok(hdw)) return;
2191 		}
2192 	} else {
2193 		hdw->tuner_type = hdw->hdw_desc->default_tuner_type;
2194 		hdw->tuner_updated = !0;
2195 		hdw->std_mask_eeprom = V4L2_STD_ALL;
2196 	}
2197 
2198 	if (hdw->serial_number) {
2199 		idx = scnprintf(hdw->identifier, sizeof(hdw->identifier) - 1,
2200 				"sn-%lu", hdw->serial_number);
2201 	} else if (hdw->unit_number >= 0) {
2202 		idx = scnprintf(hdw->identifier, sizeof(hdw->identifier) - 1,
2203 				"unit-%c",
2204 				hdw->unit_number + 'a');
2205 	} else {
2206 		idx = scnprintf(hdw->identifier, sizeof(hdw->identifier) - 1,
2207 				"unit-??");
2208 	}
2209 	hdw->identifier[idx] = 0;
2210 
2211 	pvr2_hdw_setup_std(hdw);
2212 
2213 	if (!get_default_tuner_type(hdw)) {
2214 		pvr2_trace(PVR2_TRACE_INIT,
2215 			   "pvr2_hdw_setup: Tuner type overridden to %d",
2216 			   hdw->tuner_type);
2217 	}
2218 
2219 
2220 	if (!pvr2_hdw_dev_ok(hdw)) return;
2221 
2222 	if (hdw->hdw_desc->signal_routing_scheme ==
2223 	    PVR2_ROUTING_SCHEME_GOTVIEW) {
2224 		/* Ensure that GPIO 11 is set to output for GOTVIEW
2225 		   hardware. */
2226 		pvr2_hdw_gpio_chg_dir(hdw,(1 << 11),~0);
2227 	}
2228 
2229 	pvr2_hdw_commit_setup(hdw);
2230 
2231 	hdw->vid_stream = pvr2_stream_create();
2232 	if (!pvr2_hdw_dev_ok(hdw)) return;
2233 	pvr2_trace(PVR2_TRACE_INIT,
2234 		   "pvr2_hdw_setup: video stream is %p",hdw->vid_stream);
2235 	if (hdw->vid_stream) {
2236 		idx = get_default_error_tolerance(hdw);
2237 		if (idx) {
2238 			pvr2_trace(PVR2_TRACE_INIT,
2239 				   "pvr2_hdw_setup: video stream %p setting tolerance %u",
2240 				   hdw->vid_stream,idx);
2241 		}
2242 		pvr2_stream_setup(hdw->vid_stream,hdw->usb_dev,
2243 				  PVR2_VID_ENDPOINT,idx);
2244 	}
2245 
2246 	if (!pvr2_hdw_dev_ok(hdw)) return;
2247 
2248 	hdw->flag_init_ok = !0;
2249 
2250 	pvr2_hdw_state_sched(hdw);
2251 }
2252 
2253 
2254 /* Set up the structure and attempt to put the device into a usable state.
2255    This can be a time-consuming operation, which is why it is not done
2256    internally as part of the create() step. */
pvr2_hdw_setup(struct pvr2_hdw * hdw)2257 static void pvr2_hdw_setup(struct pvr2_hdw *hdw)
2258 {
2259 	pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_setup(hdw=%p) begin",hdw);
2260 	do {
2261 		pvr2_hdw_setup_low(hdw);
2262 		pvr2_trace(PVR2_TRACE_INIT,
2263 			   "pvr2_hdw_setup(hdw=%p) done, ok=%d init_ok=%d",
2264 			   hdw,pvr2_hdw_dev_ok(hdw),hdw->flag_init_ok);
2265 		if (pvr2_hdw_dev_ok(hdw)) {
2266 			if (hdw->flag_init_ok) {
2267 				pvr2_trace(
2268 					PVR2_TRACE_INFO,
2269 					"Device initialization completed successfully.");
2270 				break;
2271 			}
2272 			if (hdw->fw1_state == FW1_STATE_RELOAD) {
2273 				pvr2_trace(
2274 					PVR2_TRACE_INFO,
2275 					"Device microcontroller firmware (re)loaded; it should now reset and reconnect.");
2276 				break;
2277 			}
2278 			pvr2_trace(
2279 				PVR2_TRACE_ERROR_LEGS,
2280 				"Device initialization was not successful.");
2281 			if (hdw->fw1_state == FW1_STATE_MISSING) {
2282 				pvr2_trace(
2283 					PVR2_TRACE_ERROR_LEGS,
2284 					"Giving up since device microcontroller firmware appears to be missing.");
2285 				break;
2286 			}
2287 		}
2288 		if (hdw->flag_modulefail) {
2289 			pvr2_trace(
2290 				PVR2_TRACE_ERROR_LEGS,
2291 				"***WARNING*** pvrusb2 driver initialization failed due to the failure of one or more sub-device kernel modules.");
2292 			pvr2_trace(
2293 				PVR2_TRACE_ERROR_LEGS,
2294 				"You need to resolve the failing condition before this driver can function.  There should be some earlier messages giving more information about the problem.");
2295 			break;
2296 		}
2297 		if (procreload) {
2298 			pvr2_trace(
2299 				PVR2_TRACE_ERROR_LEGS,
2300 				"Attempting pvrusb2 recovery by reloading primary firmware.");
2301 			pvr2_trace(
2302 				PVR2_TRACE_ERROR_LEGS,
2303 				"If this works, device should disconnect and reconnect in a sane state.");
2304 			hdw->fw1_state = FW1_STATE_UNKNOWN;
2305 			pvr2_upload_firmware1(hdw);
2306 		} else {
2307 			pvr2_trace(
2308 				PVR2_TRACE_ERROR_LEGS,
2309 				"***WARNING*** pvrusb2 device hardware appears to be jammed and I can't clear it.");
2310 			pvr2_trace(
2311 				PVR2_TRACE_ERROR_LEGS,
2312 				"You might need to power cycle the pvrusb2 device in order to recover.");
2313 		}
2314 	} while (0);
2315 	pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_setup(hdw=%p) end",hdw);
2316 }
2317 
2318 
2319 /* Perform second stage initialization.  Set callback pointer first so that
2320    we can avoid a possible initialization race (if the kernel thread runs
2321    before the callback has been set). */
pvr2_hdw_initialize(struct pvr2_hdw * hdw,void (* callback_func)(void *),void * callback_data)2322 int pvr2_hdw_initialize(struct pvr2_hdw *hdw,
2323 			void (*callback_func)(void *),
2324 			void *callback_data)
2325 {
2326 	LOCK_TAKE(hdw->big_lock); do {
2327 		if (hdw->flag_disconnected) {
2328 			/* Handle a race here: If we're already
2329 			   disconnected by this point, then give up.  If we
2330 			   get past this then we'll remain connected for
2331 			   the duration of initialization since the entire
2332 			   initialization sequence is now protected by the
2333 			   big_lock. */
2334 			break;
2335 		}
2336 		hdw->state_data = callback_data;
2337 		hdw->state_func = callback_func;
2338 		pvr2_hdw_setup(hdw);
2339 	} while (0); LOCK_GIVE(hdw->big_lock);
2340 	return hdw->flag_init_ok;
2341 }
2342 
2343 
2344 /* Create, set up, and return a structure for interacting with the
2345    underlying hardware.  */
pvr2_hdw_create(struct usb_interface * intf,const struct usb_device_id * devid)2346 struct pvr2_hdw *pvr2_hdw_create(struct usb_interface *intf,
2347 				 const struct usb_device_id *devid)
2348 {
2349 	unsigned int idx,cnt1,cnt2,m;
2350 	struct pvr2_hdw *hdw = NULL;
2351 	int valid_std_mask;
2352 	struct pvr2_ctrl *cptr;
2353 	struct usb_device *usb_dev;
2354 	const struct pvr2_device_desc *hdw_desc;
2355 	__u8 ifnum;
2356 	struct v4l2_queryctrl qctrl;
2357 	struct pvr2_ctl_info *ciptr;
2358 
2359 	usb_dev = interface_to_usbdev(intf);
2360 
2361 	hdw_desc = (const struct pvr2_device_desc *)(devid->driver_info);
2362 
2363 	if (hdw_desc == NULL) {
2364 		pvr2_trace(PVR2_TRACE_INIT, "pvr2_hdw_create: No device description pointer, unable to continue.");
2365 		pvr2_trace(PVR2_TRACE_INIT,
2366 			   "If you have a new device type, please contact Mike Isely <isely@pobox.com> to get it included in the driver");
2367 		goto fail;
2368 	}
2369 
2370 	hdw = kzalloc_obj(*hdw);
2371 	pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_create: hdw=%p, type \"%s\"",
2372 		   hdw,hdw_desc->description);
2373 	pvr2_trace(PVR2_TRACE_INFO, "Hardware description: %s",
2374 		hdw_desc->description);
2375 	if (hdw_desc->flag_is_experimental) {
2376 		pvr2_trace(PVR2_TRACE_INFO, "**********");
2377 		pvr2_trace(PVR2_TRACE_INFO,
2378 			   "***WARNING*** Support for this device (%s) is experimental.",
2379 							      hdw_desc->description);
2380 		pvr2_trace(PVR2_TRACE_INFO,
2381 			   "Important functionality might not be entirely working.");
2382 		pvr2_trace(PVR2_TRACE_INFO,
2383 			   "Please consider contacting the driver author to help with further stabilization of the driver.");
2384 		pvr2_trace(PVR2_TRACE_INFO, "**********");
2385 	}
2386 	if (!hdw) goto fail;
2387 
2388 	timer_setup(&hdw->quiescent_timer, pvr2_hdw_quiescent_timeout, 0);
2389 
2390 	timer_setup(&hdw->decoder_stabilization_timer,
2391 		    pvr2_hdw_decoder_stabilization_timeout, 0);
2392 
2393 	timer_setup(&hdw->encoder_wait_timer, pvr2_hdw_encoder_wait_timeout,
2394 		    0);
2395 
2396 	timer_setup(&hdw->encoder_run_timer, pvr2_hdw_encoder_run_timeout, 0);
2397 
2398 	hdw->master_state = PVR2_STATE_DEAD;
2399 
2400 	init_waitqueue_head(&hdw->state_wait_data);
2401 
2402 	hdw->tuner_signal_stale = !0;
2403 	cx2341x_fill_defaults(&hdw->enc_ctl_state);
2404 
2405 	/* Calculate which inputs are OK */
2406 	m = 0;
2407 	if (hdw_desc->flag_has_analogtuner) m |= 1 << PVR2_CVAL_INPUT_TV;
2408 	if (hdw_desc->digital_control_scheme != PVR2_DIGITAL_SCHEME_NONE) {
2409 		m |= 1 << PVR2_CVAL_INPUT_DTV;
2410 	}
2411 	if (hdw_desc->flag_has_svideo) m |= 1 << PVR2_CVAL_INPUT_SVIDEO;
2412 	if (hdw_desc->flag_has_composite) m |= 1 << PVR2_CVAL_INPUT_COMPOSITE;
2413 	if (hdw_desc->flag_has_fmradio) m |= 1 << PVR2_CVAL_INPUT_RADIO;
2414 	hdw->input_avail_mask = m;
2415 	hdw->input_allowed_mask = hdw->input_avail_mask;
2416 
2417 	/* If not a hybrid device, pathway_state never changes.  So
2418 	   initialize it here to what it should forever be. */
2419 	if (!(hdw->input_avail_mask & (1 << PVR2_CVAL_INPUT_DTV))) {
2420 		hdw->pathway_state = PVR2_PATHWAY_ANALOG;
2421 	} else if (!(hdw->input_avail_mask & (1 << PVR2_CVAL_INPUT_TV))) {
2422 		hdw->pathway_state = PVR2_PATHWAY_DIGITAL;
2423 	}
2424 
2425 	hdw->control_cnt = CTRLDEF_COUNT;
2426 	hdw->control_cnt += MPEGDEF_COUNT;
2427 	hdw->controls = kzalloc_objs(struct pvr2_ctrl, hdw->control_cnt);
2428 	if (!hdw->controls) goto fail;
2429 	hdw->hdw_desc = hdw_desc;
2430 	hdw->ir_scheme_active = hdw->hdw_desc->ir_scheme;
2431 	for (idx = 0; idx < hdw->control_cnt; idx++) {
2432 		cptr = hdw->controls + idx;
2433 		cptr->hdw = hdw;
2434 	}
2435 	for (idx = 0; idx < 32; idx++) {
2436 		hdw->std_mask_ptrs[idx] = hdw->std_mask_names[idx];
2437 	}
2438 	for (idx = 0; idx < CTRLDEF_COUNT; idx++) {
2439 		cptr = hdw->controls + idx;
2440 		cptr->info = control_defs+idx;
2441 	}
2442 
2443 	/* Ensure that default input choice is a valid one. */
2444 	m = hdw->input_avail_mask;
2445 	if (m) for (idx = 0; idx < (sizeof(m) << 3); idx++) {
2446 		if (!((1UL << idx) & m)) continue;
2447 		hdw->input_val = idx;
2448 		break;
2449 	}
2450 
2451 	/* Define and configure additional controls from cx2341x module. */
2452 	hdw->mpeg_ctrl_info = kzalloc_objs(*(hdw->mpeg_ctrl_info),
2453 					   MPEGDEF_COUNT);
2454 	if (!hdw->mpeg_ctrl_info) goto fail;
2455 	for (idx = 0; idx < MPEGDEF_COUNT; idx++) {
2456 		cptr = hdw->controls + idx + CTRLDEF_COUNT;
2457 		ciptr = &(hdw->mpeg_ctrl_info[idx].info);
2458 		ciptr->desc = hdw->mpeg_ctrl_info[idx].desc;
2459 		ciptr->name = mpeg_ids[idx].strid;
2460 		ciptr->v4l_id = mpeg_ids[idx].id;
2461 		ciptr->skip_init = !0;
2462 		ciptr->get_value = ctrl_cx2341x_get;
2463 		ciptr->get_v4lflags = ctrl_cx2341x_getv4lflags;
2464 		ciptr->is_dirty = ctrl_cx2341x_is_dirty;
2465 		if (!idx) ciptr->clear_dirty = ctrl_cx2341x_clear_dirty;
2466 		qctrl.id = ciptr->v4l_id;
2467 		cx2341x_ctrl_query(&hdw->enc_ctl_state,&qctrl);
2468 		if (!(qctrl.flags & V4L2_CTRL_FLAG_READ_ONLY)) {
2469 			ciptr->set_value = ctrl_cx2341x_set;
2470 		}
2471 		strscpy(hdw->mpeg_ctrl_info[idx].desc, qctrl.name,
2472 			sizeof(hdw->mpeg_ctrl_info[idx].desc));
2473 		ciptr->default_value = qctrl.default_value;
2474 		switch (qctrl.type) {
2475 		default:
2476 		case V4L2_CTRL_TYPE_INTEGER:
2477 			ciptr->type = pvr2_ctl_int;
2478 			ciptr->def.type_int.min_value = qctrl.minimum;
2479 			ciptr->def.type_int.max_value = qctrl.maximum;
2480 			break;
2481 		case V4L2_CTRL_TYPE_BOOLEAN:
2482 			ciptr->type = pvr2_ctl_bool;
2483 			break;
2484 		case V4L2_CTRL_TYPE_MENU:
2485 			ciptr->type = pvr2_ctl_enum;
2486 			ciptr->def.type_enum.value_names =
2487 				cx2341x_ctrl_get_menu(&hdw->enc_ctl_state,
2488 								ciptr->v4l_id);
2489 			for (cnt1 = 0;
2490 			     ciptr->def.type_enum.value_names[cnt1] != NULL;
2491 			     cnt1++) { }
2492 			ciptr->def.type_enum.count = cnt1;
2493 			break;
2494 		}
2495 		cptr->info = ciptr;
2496 	}
2497 
2498 	// Initialize control data regarding video standard masks
2499 	valid_std_mask = pvr2_std_get_usable();
2500 	for (idx = 0; idx < 32; idx++) {
2501 		if (!(valid_std_mask & (1UL << idx))) continue;
2502 		cnt1 = pvr2_std_id_to_str(
2503 			hdw->std_mask_names[idx],
2504 			sizeof(hdw->std_mask_names[idx])-1,
2505 			1UL << idx);
2506 		hdw->std_mask_names[idx][cnt1] = 0;
2507 	}
2508 	cptr = pvr2_hdw_get_ctrl_by_id(hdw,PVR2_CID_STDAVAIL);
2509 	if (cptr) {
2510 		memcpy(&hdw->std_info_avail,cptr->info,
2511 		       sizeof(hdw->std_info_avail));
2512 		cptr->info = &hdw->std_info_avail;
2513 		hdw->std_info_avail.def.type_bitmask.bit_names =
2514 			hdw->std_mask_ptrs;
2515 		hdw->std_info_avail.def.type_bitmask.valid_bits =
2516 			valid_std_mask;
2517 	}
2518 	cptr = pvr2_hdw_get_ctrl_by_id(hdw,PVR2_CID_STDCUR);
2519 	if (cptr) {
2520 		memcpy(&hdw->std_info_cur,cptr->info,
2521 		       sizeof(hdw->std_info_cur));
2522 		cptr->info = &hdw->std_info_cur;
2523 		hdw->std_info_cur.def.type_bitmask.bit_names =
2524 			hdw->std_mask_ptrs;
2525 		hdw->std_info_cur.def.type_bitmask.valid_bits =
2526 			valid_std_mask;
2527 	}
2528 	cptr = pvr2_hdw_get_ctrl_by_id(hdw,PVR2_CID_STDDETECT);
2529 	if (cptr) {
2530 		memcpy(&hdw->std_info_detect,cptr->info,
2531 		       sizeof(hdw->std_info_detect));
2532 		cptr->info = &hdw->std_info_detect;
2533 		hdw->std_info_detect.def.type_bitmask.bit_names =
2534 			hdw->std_mask_ptrs;
2535 		hdw->std_info_detect.def.type_bitmask.valid_bits =
2536 			valid_std_mask;
2537 	}
2538 
2539 	hdw->cropcap_stale = !0;
2540 	hdw->eeprom_addr = -1;
2541 	hdw->unit_number = -1;
2542 	hdw->v4l_minor_number_video = -1;
2543 	hdw->v4l_minor_number_vbi = -1;
2544 	hdw->v4l_minor_number_radio = -1;
2545 	hdw->ctl_write_buffer = kmalloc(PVR2_CTL_BUFFSIZE,GFP_KERNEL);
2546 	if (!hdw->ctl_write_buffer) goto fail;
2547 	hdw->ctl_read_buffer = kmalloc(PVR2_CTL_BUFFSIZE,GFP_KERNEL);
2548 	if (!hdw->ctl_read_buffer) goto fail;
2549 	hdw->ctl_write_urb = usb_alloc_urb(0,GFP_KERNEL);
2550 	if (!hdw->ctl_write_urb) goto fail;
2551 	hdw->ctl_read_urb = usb_alloc_urb(0,GFP_KERNEL);
2552 	if (!hdw->ctl_read_urb) goto fail;
2553 
2554 	if (v4l2_device_register(&intf->dev, &hdw->v4l2_dev) != 0) {
2555 		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2556 			   "Error registering with v4l core, giving up");
2557 		goto fail;
2558 	}
2559 	mutex_lock(&pvr2_unit_mtx);
2560 	do {
2561 		for (idx = 0; idx < PVR_NUM; idx++) {
2562 			if (unit_pointers[idx]) continue;
2563 			hdw->unit_number = idx;
2564 			unit_pointers[idx] = hdw;
2565 			break;
2566 		}
2567 	} while (0);
2568 	mutex_unlock(&pvr2_unit_mtx);
2569 
2570 	INIT_WORK(&hdw->workpoll, pvr2_hdw_worker_poll);
2571 
2572 	if (hdw->unit_number == -1)
2573 		goto fail;
2574 
2575 	cnt1 = 0;
2576 	cnt2 = scnprintf(hdw->name+cnt1,sizeof(hdw->name)-cnt1,"pvrusb2");
2577 	cnt1 += cnt2;
2578 	if (hdw->unit_number >= 0) {
2579 		cnt2 = scnprintf(hdw->name+cnt1,sizeof(hdw->name)-cnt1,"_%c",
2580 				 ('a' + hdw->unit_number));
2581 		cnt1 += cnt2;
2582 	}
2583 	if (cnt1 >= sizeof(hdw->name)) cnt1 = sizeof(hdw->name)-1;
2584 	hdw->name[cnt1] = 0;
2585 
2586 	pvr2_trace(PVR2_TRACE_INIT,"Driver unit number is %d, name is %s",
2587 		   hdw->unit_number,hdw->name);
2588 
2589 	hdw->tuner_type = -1;
2590 	hdw->flag_ok = !0;
2591 
2592 	hdw->usb_intf = intf;
2593 	hdw->usb_dev = usb_dev;
2594 
2595 	usb_make_path(hdw->usb_dev, hdw->bus_info, sizeof(hdw->bus_info));
2596 
2597 	ifnum = hdw->usb_intf->cur_altsetting->desc.bInterfaceNumber;
2598 	usb_set_interface(hdw->usb_dev,ifnum,0);
2599 
2600 	mutex_init(&hdw->ctl_lock_mutex);
2601 	mutex_init(&hdw->big_lock_mutex);
2602 
2603 	return hdw;
2604  fail:
2605 	if (hdw) {
2606 		timer_shutdown_sync(&hdw->quiescent_timer);
2607 		timer_shutdown_sync(&hdw->decoder_stabilization_timer);
2608 		timer_shutdown_sync(&hdw->encoder_run_timer);
2609 		timer_shutdown_sync(&hdw->encoder_wait_timer);
2610 		flush_work(&hdw->workpoll);
2611 		v4l2_device_unregister(&hdw->v4l2_dev);
2612 		usb_free_urb(hdw->ctl_read_urb);
2613 		usb_free_urb(hdw->ctl_write_urb);
2614 		kfree(hdw->ctl_read_buffer);
2615 		kfree(hdw->ctl_write_buffer);
2616 		kfree(hdw->controls);
2617 		kfree(hdw->mpeg_ctrl_info);
2618 		kfree(hdw);
2619 	}
2620 	return NULL;
2621 }
2622 
2623 
2624 /* Remove _all_ associations between this driver and the underlying USB
2625    layer. */
pvr2_hdw_remove_usb_stuff(struct pvr2_hdw * hdw)2626 static void pvr2_hdw_remove_usb_stuff(struct pvr2_hdw *hdw)
2627 {
2628 	if (hdw->flag_disconnected) return;
2629 	pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_remove_usb_stuff: hdw=%p",hdw);
2630 	if (hdw->ctl_read_urb) {
2631 		usb_kill_urb(hdw->ctl_read_urb);
2632 		usb_free_urb(hdw->ctl_read_urb);
2633 		hdw->ctl_read_urb = NULL;
2634 	}
2635 	if (hdw->ctl_write_urb) {
2636 		usb_kill_urb(hdw->ctl_write_urb);
2637 		usb_free_urb(hdw->ctl_write_urb);
2638 		hdw->ctl_write_urb = NULL;
2639 	}
2640 	if (hdw->ctl_read_buffer) {
2641 		kfree(hdw->ctl_read_buffer);
2642 		hdw->ctl_read_buffer = NULL;
2643 	}
2644 	if (hdw->ctl_write_buffer) {
2645 		kfree(hdw->ctl_write_buffer);
2646 		hdw->ctl_write_buffer = NULL;
2647 	}
2648 	hdw->flag_disconnected = !0;
2649 	/* If we don't do this, then there will be a dangling struct device
2650 	   reference to our disappearing device persisting inside the V4L
2651 	   core... */
2652 	v4l2_device_disconnect(&hdw->v4l2_dev);
2653 	hdw->usb_dev = NULL;
2654 	hdw->usb_intf = NULL;
2655 	pvr2_hdw_render_useless(hdw);
2656 }
2657 
pvr2_hdw_set_v4l2_dev(struct pvr2_hdw * hdw,struct video_device * vdev)2658 void pvr2_hdw_set_v4l2_dev(struct pvr2_hdw *hdw, struct video_device *vdev)
2659 {
2660 	vdev->v4l2_dev = &hdw->v4l2_dev;
2661 }
2662 
2663 /* Destroy hardware interaction structure */
pvr2_hdw_destroy(struct pvr2_hdw * hdw)2664 void pvr2_hdw_destroy(struct pvr2_hdw *hdw)
2665 {
2666 	if (!hdw) return;
2667 	pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_destroy: hdw=%p",hdw);
2668 	flush_work(&hdw->workpoll);
2669 	timer_shutdown_sync(&hdw->quiescent_timer);
2670 	timer_shutdown_sync(&hdw->decoder_stabilization_timer);
2671 	timer_shutdown_sync(&hdw->encoder_run_timer);
2672 	timer_shutdown_sync(&hdw->encoder_wait_timer);
2673 	if (hdw->fw_buffer) {
2674 		kfree(hdw->fw_buffer);
2675 		hdw->fw_buffer = NULL;
2676 	}
2677 	if (hdw->vid_stream) {
2678 		pvr2_stream_destroy(hdw->vid_stream);
2679 		hdw->vid_stream = NULL;
2680 	}
2681 	v4l2_device_unregister(&hdw->v4l2_dev);
2682 	pvr2_hdw_disconnect(hdw);
2683 	mutex_lock(&pvr2_unit_mtx);
2684 	do {
2685 		if ((hdw->unit_number >= 0) &&
2686 		    (hdw->unit_number < PVR_NUM) &&
2687 		    (unit_pointers[hdw->unit_number] == hdw)) {
2688 			unit_pointers[hdw->unit_number] = NULL;
2689 		}
2690 	} while (0);
2691 	mutex_unlock(&pvr2_unit_mtx);
2692 	kfree(hdw->controls);
2693 	kfree(hdw->mpeg_ctrl_info);
2694 	kfree(hdw);
2695 }
2696 
2697 
pvr2_hdw_dev_ok(struct pvr2_hdw * hdw)2698 int pvr2_hdw_dev_ok(struct pvr2_hdw *hdw)
2699 {
2700 	return (hdw && hdw->flag_ok);
2701 }
2702 
2703 
2704 /* Called when hardware has been unplugged */
pvr2_hdw_disconnect(struct pvr2_hdw * hdw)2705 void pvr2_hdw_disconnect(struct pvr2_hdw *hdw)
2706 {
2707 	pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_disconnect(hdw=%p)",hdw);
2708 	LOCK_TAKE(hdw->big_lock);
2709 	pvr2_i2c_core_done(hdw);
2710 	LOCK_TAKE(hdw->ctl_lock);
2711 	pvr2_hdw_remove_usb_stuff(hdw);
2712 	LOCK_GIVE(hdw->ctl_lock);
2713 	LOCK_GIVE(hdw->big_lock);
2714 }
2715 
2716 
2717 /* Get the number of defined controls */
pvr2_hdw_get_ctrl_count(struct pvr2_hdw * hdw)2718 unsigned int pvr2_hdw_get_ctrl_count(struct pvr2_hdw *hdw)
2719 {
2720 	return hdw->control_cnt;
2721 }
2722 
2723 
2724 /* Retrieve a control handle given its index (0..count-1) */
pvr2_hdw_get_ctrl_by_index(struct pvr2_hdw * hdw,unsigned int idx)2725 struct pvr2_ctrl *pvr2_hdw_get_ctrl_by_index(struct pvr2_hdw *hdw,
2726 					     unsigned int idx)
2727 {
2728 	if (idx >= hdw->control_cnt) return NULL;
2729 	return hdw->controls + idx;
2730 }
2731 
2732 
2733 /* Retrieve a control handle given its index (0..count-1) */
pvr2_hdw_get_ctrl_by_id(struct pvr2_hdw * hdw,unsigned int ctl_id)2734 struct pvr2_ctrl *pvr2_hdw_get_ctrl_by_id(struct pvr2_hdw *hdw,
2735 					  unsigned int ctl_id)
2736 {
2737 	struct pvr2_ctrl *cptr;
2738 	unsigned int idx;
2739 	int i;
2740 
2741 	/* This could be made a lot more efficient, but for now... */
2742 	for (idx = 0; idx < hdw->control_cnt; idx++) {
2743 		cptr = hdw->controls + idx;
2744 		i = cptr->info->internal_id;
2745 		if (i && (i == ctl_id)) return cptr;
2746 	}
2747 	return NULL;
2748 }
2749 
2750 
2751 /* Given a V4L ID, retrieve the control structure associated with it. */
pvr2_hdw_get_ctrl_v4l(struct pvr2_hdw * hdw,unsigned int ctl_id)2752 struct pvr2_ctrl *pvr2_hdw_get_ctrl_v4l(struct pvr2_hdw *hdw,unsigned int ctl_id)
2753 {
2754 	struct pvr2_ctrl *cptr;
2755 	unsigned int idx;
2756 	int i;
2757 
2758 	/* This could be made a lot more efficient, but for now... */
2759 	for (idx = 0; idx < hdw->control_cnt; idx++) {
2760 		cptr = hdw->controls + idx;
2761 		i = cptr->info->v4l_id;
2762 		if (i && (i == ctl_id)) return cptr;
2763 	}
2764 	return NULL;
2765 }
2766 
2767 
2768 /* Given a V4L ID for its immediate predecessor, retrieve the control
2769    structure associated with it. */
pvr2_hdw_get_ctrl_nextv4l(struct pvr2_hdw * hdw,unsigned int ctl_id)2770 struct pvr2_ctrl *pvr2_hdw_get_ctrl_nextv4l(struct pvr2_hdw *hdw,
2771 					    unsigned int ctl_id)
2772 {
2773 	struct pvr2_ctrl *cptr,*cp2;
2774 	unsigned int idx;
2775 	int i;
2776 
2777 	/* This could be made a lot more efficient, but for now... */
2778 	cp2 = NULL;
2779 	for (idx = 0; idx < hdw->control_cnt; idx++) {
2780 		cptr = hdw->controls + idx;
2781 		i = cptr->info->v4l_id;
2782 		if (!i) continue;
2783 		if (i <= ctl_id) continue;
2784 		if (cp2 && (cp2->info->v4l_id < i)) continue;
2785 		cp2 = cptr;
2786 	}
2787 	return cp2;
2788 	return NULL;
2789 }
2790 
2791 
get_ctrl_typename(enum pvr2_ctl_type tp)2792 static const char *get_ctrl_typename(enum pvr2_ctl_type tp)
2793 {
2794 	switch (tp) {
2795 	case pvr2_ctl_int: return "integer";
2796 	case pvr2_ctl_enum: return "enum";
2797 	case pvr2_ctl_bool: return "boolean";
2798 	case pvr2_ctl_bitmask: return "bitmask";
2799 	}
2800 	return "";
2801 }
2802 
2803 
pvr2_subdev_set_control(struct pvr2_hdw * hdw,int id,const char * name,int val)2804 static void pvr2_subdev_set_control(struct pvr2_hdw *hdw, int id,
2805 				    const char *name, int val)
2806 {
2807 	struct v4l2_control ctrl;
2808 	struct v4l2_subdev *sd;
2809 
2810 	pvr2_trace(PVR2_TRACE_CHIPS, "subdev v4l2 %s=%d", name, val);
2811 	memset(&ctrl, 0, sizeof(ctrl));
2812 	ctrl.id = id;
2813 	ctrl.value = val;
2814 
2815 	v4l2_device_for_each_subdev(sd, &hdw->v4l2_dev)
2816 		v4l2_s_ctrl(NULL, sd->ctrl_handler, &ctrl);
2817 }
2818 
2819 #define PVR2_SUBDEV_SET_CONTROL(hdw, id, lab) \
2820 	if ((hdw)->lab##_dirty || (hdw)->force_dirty) {		\
2821 		pvr2_subdev_set_control(hdw, id, #lab, (hdw)->lab##_val); \
2822 	}
2823 
pvr2_hdw_get_detected_std(struct pvr2_hdw * hdw)2824 static v4l2_std_id pvr2_hdw_get_detected_std(struct pvr2_hdw *hdw)
2825 {
2826 	v4l2_std_id std;
2827 	std = (v4l2_std_id)hdw->std_mask_avail;
2828 	v4l2_device_call_all(&hdw->v4l2_dev, 0,
2829 			     video, querystd, &std);
2830 	return std;
2831 }
2832 
2833 /* Execute whatever commands are required to update the state of all the
2834    sub-devices so that they match our current control values. */
pvr2_subdev_update(struct pvr2_hdw * hdw)2835 static void pvr2_subdev_update(struct pvr2_hdw *hdw)
2836 {
2837 	struct v4l2_subdev *sd;
2838 	unsigned int id;
2839 	pvr2_subdev_update_func fp;
2840 
2841 	pvr2_trace(PVR2_TRACE_CHIPS, "subdev update...");
2842 
2843 	if (hdw->tuner_updated || hdw->force_dirty) {
2844 		struct tuner_setup setup;
2845 		pvr2_trace(PVR2_TRACE_CHIPS, "subdev tuner set_type(%d)",
2846 			   hdw->tuner_type);
2847 		if (((int)(hdw->tuner_type)) >= 0) {
2848 			memset(&setup, 0, sizeof(setup));
2849 			setup.addr = ADDR_UNSET;
2850 			setup.type = hdw->tuner_type;
2851 			setup.mode_mask = T_RADIO | T_ANALOG_TV;
2852 			v4l2_device_call_all(&hdw->v4l2_dev, 0,
2853 					     tuner, s_type_addr, &setup);
2854 		}
2855 	}
2856 
2857 	if (hdw->input_dirty || hdw->std_dirty || hdw->force_dirty) {
2858 		pvr2_trace(PVR2_TRACE_CHIPS, "subdev v4l2 set_standard");
2859 		if (hdw->input_val == PVR2_CVAL_INPUT_RADIO) {
2860 			v4l2_device_call_all(&hdw->v4l2_dev, 0,
2861 					     tuner, s_radio);
2862 		} else {
2863 			v4l2_std_id vs;
2864 			vs = hdw->std_mask_cur;
2865 			v4l2_device_call_all(&hdw->v4l2_dev, 0,
2866 					     video, s_std, vs);
2867 			pvr2_hdw_cx25840_vbi_hack(hdw);
2868 		}
2869 		hdw->tuner_signal_stale = !0;
2870 		hdw->cropcap_stale = !0;
2871 	}
2872 
2873 	PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_BRIGHTNESS, brightness);
2874 	PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_CONTRAST, contrast);
2875 	PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_SATURATION, saturation);
2876 	PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_HUE, hue);
2877 	PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_AUDIO_MUTE, mute);
2878 	PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_AUDIO_VOLUME, volume);
2879 	PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_AUDIO_BALANCE, balance);
2880 	PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_AUDIO_BASS, bass);
2881 	PVR2_SUBDEV_SET_CONTROL(hdw, V4L2_CID_AUDIO_TREBLE, treble);
2882 
2883 	if (hdw->input_dirty || hdw->audiomode_dirty || hdw->force_dirty) {
2884 		struct v4l2_tuner vt;
2885 		memset(&vt, 0, sizeof(vt));
2886 		vt.type = (hdw->input_val == PVR2_CVAL_INPUT_RADIO) ?
2887 			V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV;
2888 		vt.audmode = hdw->audiomode_val;
2889 		v4l2_device_call_all(&hdw->v4l2_dev, 0, tuner, s_tuner, &vt);
2890 	}
2891 
2892 	if (hdw->freqDirty || hdw->force_dirty) {
2893 		unsigned long fv;
2894 		struct v4l2_frequency freq;
2895 		fv = pvr2_hdw_get_cur_freq(hdw);
2896 		pvr2_trace(PVR2_TRACE_CHIPS, "subdev v4l2 set_freq(%lu)", fv);
2897 		if (hdw->tuner_signal_stale) pvr2_hdw_status_poll(hdw);
2898 		memset(&freq, 0, sizeof(freq));
2899 		if (hdw->tuner_signal_info.capability & V4L2_TUNER_CAP_LOW) {
2900 			/* ((fv * 1000) / 62500) */
2901 			freq.frequency = (fv * 2) / 125;
2902 		} else {
2903 			freq.frequency = fv / 62500;
2904 		}
2905 		/* tuner-core currently doesn't seem to care about this, but
2906 		   let's set it anyway for completeness. */
2907 		if (hdw->input_val == PVR2_CVAL_INPUT_RADIO) {
2908 			freq.type = V4L2_TUNER_RADIO;
2909 		} else {
2910 			freq.type = V4L2_TUNER_ANALOG_TV;
2911 		}
2912 		freq.tuner = 0;
2913 		v4l2_device_call_all(&hdw->v4l2_dev, 0, tuner,
2914 				     s_frequency, &freq);
2915 	}
2916 
2917 	if (hdw->res_hor_dirty || hdw->res_ver_dirty || hdw->force_dirty) {
2918 		struct v4l2_subdev_format format = {
2919 			.which = V4L2_SUBDEV_FORMAT_ACTIVE,
2920 		};
2921 
2922 		format.format.width = hdw->res_hor_val;
2923 		format.format.height = hdw->res_ver_val;
2924 		format.format.code = MEDIA_BUS_FMT_FIXED;
2925 		pvr2_trace(PVR2_TRACE_CHIPS, "subdev v4l2 set_size(%dx%d)",
2926 			   format.format.width, format.format.height);
2927 		v4l2_device_call_all(&hdw->v4l2_dev, 0, pad, set_fmt,
2928 				     NULL, &format);
2929 	}
2930 
2931 	if (hdw->srate_dirty || hdw->force_dirty) {
2932 		u32 val;
2933 		pvr2_trace(PVR2_TRACE_CHIPS, "subdev v4l2 set_audio %d",
2934 			   hdw->srate_val);
2935 		switch (hdw->srate_val) {
2936 		default:
2937 		case V4L2_MPEG_AUDIO_SAMPLING_FREQ_48000:
2938 			val = 48000;
2939 			break;
2940 		case V4L2_MPEG_AUDIO_SAMPLING_FREQ_44100:
2941 			val = 44100;
2942 			break;
2943 		case V4L2_MPEG_AUDIO_SAMPLING_FREQ_32000:
2944 			val = 32000;
2945 			break;
2946 		}
2947 		v4l2_device_call_all(&hdw->v4l2_dev, 0,
2948 				     audio, s_clock_freq, val);
2949 	}
2950 
2951 	/* Unable to set crop parameters; there is apparently no equivalent
2952 	   for VIDIOC_S_CROP */
2953 
2954 	v4l2_device_for_each_subdev(sd, &hdw->v4l2_dev) {
2955 		id = sd->grp_id;
2956 		if (id >= ARRAY_SIZE(pvr2_module_update_functions)) continue;
2957 		fp = pvr2_module_update_functions[id];
2958 		if (!fp) continue;
2959 		(*fp)(hdw, sd);
2960 	}
2961 
2962 	if (hdw->tuner_signal_stale || hdw->cropcap_stale) {
2963 		pvr2_hdw_status_poll(hdw);
2964 	}
2965 }
2966 
2967 
2968 /* Figure out if we need to commit control changes.  If so, mark internal
2969    state flags to indicate this fact and return true.  Otherwise do nothing
2970    else and return false. */
pvr2_hdw_commit_setup(struct pvr2_hdw * hdw)2971 static int pvr2_hdw_commit_setup(struct pvr2_hdw *hdw)
2972 {
2973 	unsigned int idx;
2974 	struct pvr2_ctrl *cptr;
2975 	int value;
2976 	int commit_flag = hdw->force_dirty;
2977 	char buf[100];
2978 	unsigned int bcnt,ccnt;
2979 
2980 	for (idx = 0; idx < hdw->control_cnt; idx++) {
2981 		cptr = hdw->controls + idx;
2982 		if (!cptr->info->is_dirty) continue;
2983 		if (!cptr->info->is_dirty(cptr)) continue;
2984 		commit_flag = !0;
2985 
2986 		if (!(pvrusb2_debug & PVR2_TRACE_CTL)) continue;
2987 		bcnt = scnprintf(buf,sizeof(buf),"\"%s\" <-- ",
2988 				 cptr->info->name);
2989 		value = 0;
2990 		cptr->info->get_value(cptr,&value);
2991 		pvr2_ctrl_value_to_sym_internal(cptr,~0,value,
2992 						buf+bcnt,
2993 						sizeof(buf)-bcnt,&ccnt);
2994 		bcnt += ccnt;
2995 		bcnt += scnprintf(buf+bcnt,sizeof(buf)-bcnt," <%s>",
2996 				  get_ctrl_typename(cptr->info->type));
2997 		pvr2_trace(PVR2_TRACE_CTL,
2998 			   "/*--TRACE_COMMIT--*/ %.*s",
2999 			   bcnt,buf);
3000 	}
3001 
3002 	if (!commit_flag) {
3003 		/* Nothing has changed */
3004 		return 0;
3005 	}
3006 
3007 	hdw->state_pipeline_config = 0;
3008 	trace_stbit("state_pipeline_config",hdw->state_pipeline_config);
3009 	pvr2_hdw_state_sched(hdw);
3010 
3011 	return !0;
3012 }
3013 
3014 
3015 /* Perform all operations needed to commit all control changes.  This must
3016    be performed in synchronization with the pipeline state and is thus
3017    expected to be called as part of the driver's worker thread.  Return
3018    true if commit successful, otherwise return false to indicate that
3019    commit isn't possible at this time. */
pvr2_hdw_commit_execute(struct pvr2_hdw * hdw)3020 static int pvr2_hdw_commit_execute(struct pvr2_hdw *hdw)
3021 {
3022 	unsigned int idx;
3023 	struct pvr2_ctrl *cptr;
3024 	int disruptive_change;
3025 
3026 	if (hdw->input_dirty && hdw->state_pathway_ok &&
3027 	    (((hdw->input_val == PVR2_CVAL_INPUT_DTV) ?
3028 	      PVR2_PATHWAY_DIGITAL : PVR2_PATHWAY_ANALOG) !=
3029 	     hdw->pathway_state)) {
3030 		/* Change of mode being asked for... */
3031 		hdw->state_pathway_ok = 0;
3032 		trace_stbit("state_pathway_ok", hdw->state_pathway_ok);
3033 	}
3034 	if (!hdw->state_pathway_ok) {
3035 		/* Can't commit anything until pathway is ok. */
3036 		return 0;
3037 	}
3038 
3039 	/* Handle some required side effects when the video standard is
3040 	   changed.... */
3041 	if (hdw->std_dirty) {
3042 		int nvres;
3043 		int gop_size;
3044 		if (hdw->std_mask_cur & V4L2_STD_525_60) {
3045 			nvres = 480;
3046 			gop_size = 15;
3047 		} else {
3048 			nvres = 576;
3049 			gop_size = 12;
3050 		}
3051 		/* Rewrite the vertical resolution to be appropriate to the
3052 		   video standard that has been selected. */
3053 		if (nvres != hdw->res_ver_val) {
3054 			hdw->res_ver_val = nvres;
3055 			hdw->res_ver_dirty = !0;
3056 		}
3057 		/* Rewrite the GOP size to be appropriate to the video
3058 		   standard that has been selected. */
3059 		if (gop_size != hdw->enc_ctl_state.video_gop_size) {
3060 			struct v4l2_ext_controls cs;
3061 			struct v4l2_ext_control c1;
3062 			memset(&cs, 0, sizeof(cs));
3063 			memset(&c1, 0, sizeof(c1));
3064 			cs.controls = &c1;
3065 			cs.count = 1;
3066 			c1.id = V4L2_CID_MPEG_VIDEO_GOP_SIZE;
3067 			c1.value = gop_size;
3068 			cx2341x_ext_ctrls(&hdw->enc_ctl_state, 0, &cs,
3069 					  VIDIOC_S_EXT_CTRLS);
3070 		}
3071 	}
3072 
3073 	/* The broadcast decoder can only scale down, so if
3074 	 * res_*_dirty && crop window < output format ==> enlarge crop.
3075 	 *
3076 	 * The mpeg encoder receives fields of res_hor_val dots and
3077 	 * res_ver_val halflines.  Limits: hor<=720, ver<=576.
3078 	 */
3079 	if (hdw->res_hor_dirty && hdw->cropw_val < hdw->res_hor_val) {
3080 		hdw->cropw_val = hdw->res_hor_val;
3081 		hdw->cropw_dirty = !0;
3082 	} else if (hdw->cropw_dirty) {
3083 		hdw->res_hor_dirty = !0;           /* must rescale */
3084 		hdw->res_hor_val = min(720, hdw->cropw_val);
3085 	}
3086 	if (hdw->res_ver_dirty && hdw->croph_val < hdw->res_ver_val) {
3087 		hdw->croph_val = hdw->res_ver_val;
3088 		hdw->croph_dirty = !0;
3089 	} else if (hdw->croph_dirty) {
3090 		int nvres = hdw->std_mask_cur & V4L2_STD_525_60 ? 480 : 576;
3091 		hdw->res_ver_dirty = !0;
3092 		hdw->res_ver_val = min(nvres, hdw->croph_val);
3093 	}
3094 
3095 	/* If any of the below has changed, then we can't do the update
3096 	   while the pipeline is running.  Pipeline must be paused first
3097 	   and decoder -> encoder connection be made quiescent before we
3098 	   can proceed. */
3099 	disruptive_change =
3100 		(hdw->std_dirty ||
3101 		 hdw->enc_unsafe_stale ||
3102 		 hdw->srate_dirty ||
3103 		 hdw->res_ver_dirty ||
3104 		 hdw->res_hor_dirty ||
3105 		 hdw->cropw_dirty ||
3106 		 hdw->croph_dirty ||
3107 		 hdw->input_dirty ||
3108 		 (hdw->active_stream_type != hdw->desired_stream_type));
3109 	if (disruptive_change && !hdw->state_pipeline_idle) {
3110 		/* Pipeline is not idle; we can't proceed.  Arrange to
3111 		   cause pipeline to stop so that we can try this again
3112 		   later.... */
3113 		hdw->state_pipeline_pause = !0;
3114 		return 0;
3115 	}
3116 
3117 	if (hdw->srate_dirty) {
3118 		/* Write new sample rate into control structure since
3119 		 * the master copy is stale.  We must track srate
3120 		 * separate from the mpeg control structure because
3121 		 * other logic also uses this value. */
3122 		struct v4l2_ext_controls cs;
3123 		struct v4l2_ext_control c1;
3124 		memset(&cs,0,sizeof(cs));
3125 		memset(&c1,0,sizeof(c1));
3126 		cs.controls = &c1;
3127 		cs.count = 1;
3128 		c1.id = V4L2_CID_MPEG_AUDIO_SAMPLING_FREQ;
3129 		c1.value = hdw->srate_val;
3130 		cx2341x_ext_ctrls(&hdw->enc_ctl_state, 0, &cs,VIDIOC_S_EXT_CTRLS);
3131 	}
3132 
3133 	if (hdw->active_stream_type != hdw->desired_stream_type) {
3134 		/* Handle any side effects of stream config here */
3135 		hdw->active_stream_type = hdw->desired_stream_type;
3136 	}
3137 
3138 	if (hdw->hdw_desc->signal_routing_scheme ==
3139 	    PVR2_ROUTING_SCHEME_GOTVIEW) {
3140 		u32 b;
3141 		/* Handle GOTVIEW audio switching */
3142 		pvr2_hdw_gpio_get_out(hdw,&b);
3143 		if (hdw->input_val == PVR2_CVAL_INPUT_RADIO) {
3144 			/* Set GPIO 11 */
3145 			pvr2_hdw_gpio_chg_out(hdw,(1 << 11),~0);
3146 		} else {
3147 			/* Clear GPIO 11 */
3148 			pvr2_hdw_gpio_chg_out(hdw,(1 << 11),0);
3149 		}
3150 	}
3151 
3152 	/* Check and update state for all sub-devices. */
3153 	pvr2_subdev_update(hdw);
3154 
3155 	hdw->tuner_updated = 0;
3156 	hdw->force_dirty = 0;
3157 	for (idx = 0; idx < hdw->control_cnt; idx++) {
3158 		cptr = hdw->controls + idx;
3159 		if (!cptr->info->clear_dirty) continue;
3160 		cptr->info->clear_dirty(cptr);
3161 	}
3162 
3163 	if ((hdw->pathway_state == PVR2_PATHWAY_ANALOG) &&
3164 	    hdw->state_encoder_run) {
3165 		/* If encoder isn't running or it can't be touched, then
3166 		   this will get worked out later when we start the
3167 		   encoder. */
3168 		if (pvr2_encoder_adjust(hdw) < 0) return !0;
3169 	}
3170 
3171 	hdw->state_pipeline_config = !0;
3172 	/* Hardware state may have changed in a way to cause the cropping
3173 	   capabilities to have changed.  So mark it stale, which will
3174 	   cause a later re-fetch. */
3175 	trace_stbit("state_pipeline_config",hdw->state_pipeline_config);
3176 	return !0;
3177 }
3178 
3179 
pvr2_hdw_commit_ctl(struct pvr2_hdw * hdw)3180 int pvr2_hdw_commit_ctl(struct pvr2_hdw *hdw)
3181 {
3182 	int fl;
3183 	LOCK_TAKE(hdw->big_lock);
3184 	fl = pvr2_hdw_commit_setup(hdw);
3185 	LOCK_GIVE(hdw->big_lock);
3186 	if (!fl) return 0;
3187 	return pvr2_hdw_wait(hdw,0);
3188 }
3189 
3190 
pvr2_hdw_worker_poll(struct work_struct * work)3191 static void pvr2_hdw_worker_poll(struct work_struct *work)
3192 {
3193 	int fl = 0;
3194 	struct pvr2_hdw *hdw = container_of(work,struct pvr2_hdw,workpoll);
3195 	LOCK_TAKE(hdw->big_lock); do {
3196 		fl = pvr2_hdw_state_eval(hdw);
3197 	} while (0); LOCK_GIVE(hdw->big_lock);
3198 	if (fl && hdw->state_func) {
3199 		hdw->state_func(hdw->state_data);
3200 	}
3201 }
3202 
3203 
pvr2_hdw_wait(struct pvr2_hdw * hdw,int state)3204 static int pvr2_hdw_wait(struct pvr2_hdw *hdw,int state)
3205 {
3206 	return wait_event_interruptible(
3207 		hdw->state_wait_data,
3208 		(hdw->state_stale == 0) &&
3209 		(!state || (hdw->master_state != state)));
3210 }
3211 
3212 
3213 /* Return name for this driver instance */
pvr2_hdw_get_driver_name(struct pvr2_hdw * hdw)3214 const char *pvr2_hdw_get_driver_name(struct pvr2_hdw *hdw)
3215 {
3216 	return hdw->name;
3217 }
3218 
3219 
pvr2_hdw_get_desc(struct pvr2_hdw * hdw)3220 const char *pvr2_hdw_get_desc(struct pvr2_hdw *hdw)
3221 {
3222 	return hdw->hdw_desc->description;
3223 }
3224 
3225 
pvr2_hdw_get_type(struct pvr2_hdw * hdw)3226 const char *pvr2_hdw_get_type(struct pvr2_hdw *hdw)
3227 {
3228 	return hdw->hdw_desc->shortname;
3229 }
3230 
3231 
pvr2_hdw_is_hsm(struct pvr2_hdw * hdw)3232 int pvr2_hdw_is_hsm(struct pvr2_hdw *hdw)
3233 {
3234 	int result;
3235 	LOCK_TAKE(hdw->ctl_lock); do {
3236 		hdw->cmd_buffer[0] = FX2CMD_GET_USB_SPEED;
3237 		result = pvr2_send_request(hdw,
3238 					   hdw->cmd_buffer,1,
3239 					   hdw->cmd_buffer,1);
3240 		if (result < 0) break;
3241 		result = (hdw->cmd_buffer[0] != 0);
3242 	} while(0); LOCK_GIVE(hdw->ctl_lock);
3243 	return result;
3244 }
3245 
3246 
3247 /* Execute poll of tuner status */
pvr2_hdw_execute_tuner_poll(struct pvr2_hdw * hdw)3248 void pvr2_hdw_execute_tuner_poll(struct pvr2_hdw *hdw)
3249 {
3250 	LOCK_TAKE(hdw->big_lock); do {
3251 		pvr2_hdw_status_poll(hdw);
3252 	} while (0); LOCK_GIVE(hdw->big_lock);
3253 }
3254 
3255 
pvr2_hdw_check_cropcap(struct pvr2_hdw * hdw)3256 static int pvr2_hdw_check_cropcap(struct pvr2_hdw *hdw)
3257 {
3258 	if (!hdw->cropcap_stale) {
3259 		return 0;
3260 	}
3261 	pvr2_hdw_status_poll(hdw);
3262 	if (hdw->cropcap_stale) {
3263 		return -EIO;
3264 	}
3265 	return 0;
3266 }
3267 
3268 
3269 /* Return information about cropping capabilities */
pvr2_hdw_get_cropcap(struct pvr2_hdw * hdw,struct v4l2_cropcap * pp)3270 int pvr2_hdw_get_cropcap(struct pvr2_hdw *hdw, struct v4l2_cropcap *pp)
3271 {
3272 	int stat = 0;
3273 	LOCK_TAKE(hdw->big_lock);
3274 	stat = pvr2_hdw_check_cropcap(hdw);
3275 	if (!stat) {
3276 		memcpy(pp, &hdw->cropcap_info, sizeof(hdw->cropcap_info));
3277 	}
3278 	LOCK_GIVE(hdw->big_lock);
3279 	return stat;
3280 }
3281 
3282 
3283 /* Return information about the tuner */
pvr2_hdw_get_tuner_status(struct pvr2_hdw * hdw,struct v4l2_tuner * vtp)3284 int pvr2_hdw_get_tuner_status(struct pvr2_hdw *hdw,struct v4l2_tuner *vtp)
3285 {
3286 	LOCK_TAKE(hdw->big_lock);
3287 	do {
3288 		if (hdw->tuner_signal_stale) {
3289 			pvr2_hdw_status_poll(hdw);
3290 		}
3291 		memcpy(vtp,&hdw->tuner_signal_info,sizeof(struct v4l2_tuner));
3292 	} while (0);
3293 	LOCK_GIVE(hdw->big_lock);
3294 	return 0;
3295 }
3296 
3297 
3298 /* Get handle to video output stream */
pvr2_hdw_get_video_stream(struct pvr2_hdw * hp)3299 struct pvr2_stream *pvr2_hdw_get_video_stream(struct pvr2_hdw *hp)
3300 {
3301 	return hp->vid_stream;
3302 }
3303 
3304 
pvr2_hdw_trigger_module_log(struct pvr2_hdw * hdw)3305 void pvr2_hdw_trigger_module_log(struct pvr2_hdw *hdw)
3306 {
3307 	int nr = pvr2_hdw_get_unit_number(hdw);
3308 	LOCK_TAKE(hdw->big_lock);
3309 	do {
3310 		pr_info("pvrusb2: =================  START STATUS CARD #%d  =================\n", nr);
3311 		v4l2_device_call_all(&hdw->v4l2_dev, 0, core, log_status);
3312 		pvr2_trace(PVR2_TRACE_INFO,"cx2341x config:");
3313 		cx2341x_log_status(&hdw->enc_ctl_state, "pvrusb2");
3314 		pvr2_hdw_state_log_state(hdw);
3315 		pr_info("pvrusb2: ==================  END STATUS CARD #%d  ==================\n", nr);
3316 	} while (0);
3317 	LOCK_GIVE(hdw->big_lock);
3318 }
3319 
3320 
3321 /* Grab EEPROM contents, needed for direct method. */
3322 #define EEPROM_SIZE 8192
3323 #define trace_eeprom(...) pvr2_trace(PVR2_TRACE_EEPROM,__VA_ARGS__)
pvr2_full_eeprom_fetch(struct pvr2_hdw * hdw)3324 static u8 *pvr2_full_eeprom_fetch(struct pvr2_hdw *hdw)
3325 {
3326 	struct i2c_msg msg[2];
3327 	u8 *eeprom;
3328 	u8 iadd[2];
3329 	u8 addr;
3330 	u16 eepromSize;
3331 	unsigned int offs;
3332 	int ret;
3333 	int mode16 = 0;
3334 	unsigned pcnt,tcnt;
3335 	eeprom = kzalloc(EEPROM_SIZE, GFP_KERNEL);
3336 	if (!eeprom) {
3337 		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3338 			   "Failed to allocate memory required to read eeprom");
3339 		return NULL;
3340 	}
3341 
3342 	trace_eeprom("Value for eeprom addr from controller was 0x%x",
3343 		     hdw->eeprom_addr);
3344 	addr = hdw->eeprom_addr;
3345 	/* Seems that if the high bit is set, then the *real* eeprom
3346 	   address is shifted right now bit position (noticed this in
3347 	   newer PVR USB2 hardware) */
3348 	if (addr & 0x80) addr >>= 1;
3349 
3350 	/* FX2 documentation states that a 16bit-addressed eeprom is
3351 	   expected if the I2C address is an odd number (yeah, this is
3352 	   strange but it's what they do) */
3353 	mode16 = (addr & 1);
3354 	eepromSize = (mode16 ? EEPROM_SIZE : 256);
3355 	trace_eeprom("Examining %d byte eeprom at location 0x%x using %d bit addressing",
3356 		     eepromSize, addr,
3357 		     mode16 ? 16 : 8);
3358 
3359 	msg[0].addr = addr;
3360 	msg[0].flags = 0;
3361 	msg[0].len = mode16 ? 2 : 1;
3362 	msg[0].buf = iadd;
3363 	msg[1].addr = addr;
3364 	msg[1].flags = I2C_M_RD;
3365 
3366 	/* We have to do the actual eeprom data fetch ourselves, because
3367 	   (1) we're only fetching part of the eeprom, and (2) if we were
3368 	   getting the whole thing our I2C driver can't grab it in one
3369 	   pass - which is what tveeprom is otherwise going to attempt */
3370 	for (tcnt = 0; tcnt < EEPROM_SIZE; tcnt += pcnt) {
3371 		pcnt = 16;
3372 		if (pcnt + tcnt > EEPROM_SIZE) pcnt = EEPROM_SIZE-tcnt;
3373 		offs = tcnt + (eepromSize - EEPROM_SIZE);
3374 		if (mode16) {
3375 			iadd[0] = offs >> 8;
3376 			iadd[1] = offs;
3377 		} else {
3378 			iadd[0] = offs;
3379 		}
3380 		msg[1].len = pcnt;
3381 		msg[1].buf = eeprom+tcnt;
3382 		if ((ret = i2c_transfer(&hdw->i2c_adap,
3383 					msg,ARRAY_SIZE(msg))) != 2) {
3384 			pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3385 				   "eeprom fetch set offs err=%d",ret);
3386 			kfree(eeprom);
3387 			return NULL;
3388 		}
3389 	}
3390 	return eeprom;
3391 }
3392 
3393 
pvr2_hdw_cpufw_set_enabled(struct pvr2_hdw * hdw,int mode,int enable_flag)3394 void pvr2_hdw_cpufw_set_enabled(struct pvr2_hdw *hdw,
3395 				int mode,
3396 				int enable_flag)
3397 {
3398 	int ret;
3399 	u16 address;
3400 	unsigned int pipe;
3401 	LOCK_TAKE(hdw->big_lock);
3402 	do {
3403 		if ((hdw->fw_buffer == NULL) == !enable_flag) break;
3404 
3405 		if (!enable_flag) {
3406 			pvr2_trace(PVR2_TRACE_FIRMWARE,
3407 				   "Cleaning up after CPU firmware fetch");
3408 			kfree(hdw->fw_buffer);
3409 			hdw->fw_buffer = NULL;
3410 			hdw->fw_size = 0;
3411 			if (hdw->fw_cpu_flag) {
3412 				/* Now release the CPU.  It will disconnect
3413 				   and reconnect later. */
3414 				pvr2_hdw_cpureset_assert(hdw,0);
3415 			}
3416 			break;
3417 		}
3418 
3419 		hdw->fw_cpu_flag = (mode != 2);
3420 		if (hdw->fw_cpu_flag) {
3421 			hdw->fw_size = (mode == 1) ? 0x4000 : 0x2000;
3422 			pvr2_trace(PVR2_TRACE_FIRMWARE,
3423 				   "Preparing to suck out CPU firmware (size=%u)",
3424 				   hdw->fw_size);
3425 			hdw->fw_buffer = kzalloc(hdw->fw_size,GFP_KERNEL);
3426 			if (!hdw->fw_buffer) {
3427 				hdw->fw_size = 0;
3428 				break;
3429 			}
3430 
3431 			/* We have to hold the CPU during firmware upload. */
3432 			pvr2_hdw_cpureset_assert(hdw,1);
3433 
3434 			/* download the firmware from address 0000-1fff in 2048
3435 			   (=0x800) bytes chunk. */
3436 
3437 			pvr2_trace(PVR2_TRACE_FIRMWARE,
3438 				   "Grabbing CPU firmware");
3439 			pipe = usb_rcvctrlpipe(hdw->usb_dev, 0);
3440 			for(address = 0; address < hdw->fw_size;
3441 			    address += 0x800) {
3442 				ret = usb_control_msg(hdw->usb_dev,pipe,
3443 						      0xa0,0xc0,
3444 						      address,0,
3445 						      hdw->fw_buffer+address,
3446 						      0x800,1000);
3447 				if (ret < 0) break;
3448 			}
3449 
3450 			pvr2_trace(PVR2_TRACE_FIRMWARE,
3451 				   "Done grabbing CPU firmware");
3452 		} else {
3453 			pvr2_trace(PVR2_TRACE_FIRMWARE,
3454 				   "Sucking down EEPROM contents");
3455 			hdw->fw_buffer = pvr2_full_eeprom_fetch(hdw);
3456 			if (!hdw->fw_buffer) {
3457 				pvr2_trace(PVR2_TRACE_FIRMWARE,
3458 					   "EEPROM content suck failed.");
3459 				break;
3460 			}
3461 			hdw->fw_size = EEPROM_SIZE;
3462 			pvr2_trace(PVR2_TRACE_FIRMWARE,
3463 				   "Done sucking down EEPROM contents");
3464 		}
3465 	} while (0);
3466 	LOCK_GIVE(hdw->big_lock);
3467 }
3468 
3469 
3470 /* Return true if we're in a mode for retrieval CPU firmware */
pvr2_hdw_cpufw_get_enabled(struct pvr2_hdw * hdw)3471 int pvr2_hdw_cpufw_get_enabled(struct pvr2_hdw *hdw)
3472 {
3473 	return hdw->fw_buffer != NULL;
3474 }
3475 
3476 
pvr2_hdw_cpufw_get(struct pvr2_hdw * hdw,unsigned int offs,char * buf,unsigned int cnt)3477 int pvr2_hdw_cpufw_get(struct pvr2_hdw *hdw,unsigned int offs,
3478 		       char *buf,unsigned int cnt)
3479 {
3480 	int ret = -EINVAL;
3481 	LOCK_TAKE(hdw->big_lock);
3482 	do {
3483 		if (!buf) break;
3484 		if (!cnt) break;
3485 
3486 		if (!hdw->fw_buffer) {
3487 			ret = -EIO;
3488 			break;
3489 		}
3490 
3491 		if (offs >= hdw->fw_size) {
3492 			pvr2_trace(PVR2_TRACE_FIRMWARE,
3493 				   "Read firmware data offs=%d EOF",
3494 				   offs);
3495 			ret = 0;
3496 			break;
3497 		}
3498 
3499 		if (offs + cnt > hdw->fw_size) cnt = hdw->fw_size - offs;
3500 
3501 		memcpy(buf,hdw->fw_buffer+offs,cnt);
3502 
3503 		pvr2_trace(PVR2_TRACE_FIRMWARE,
3504 			   "Read firmware data offs=%d cnt=%d",
3505 			   offs,cnt);
3506 		ret = cnt;
3507 	} while (0);
3508 	LOCK_GIVE(hdw->big_lock);
3509 
3510 	return ret;
3511 }
3512 
3513 
pvr2_hdw_v4l_get_minor_number(struct pvr2_hdw * hdw,enum pvr2_v4l_type index)3514 int pvr2_hdw_v4l_get_minor_number(struct pvr2_hdw *hdw,
3515 				  enum pvr2_v4l_type index)
3516 {
3517 	switch (index) {
3518 	case pvr2_v4l_type_video: return hdw->v4l_minor_number_video;
3519 	case pvr2_v4l_type_vbi: return hdw->v4l_minor_number_vbi;
3520 	case pvr2_v4l_type_radio: return hdw->v4l_minor_number_radio;
3521 	default: return -1;
3522 	}
3523 }
3524 
3525 
3526 /* Store a v4l minor device number */
pvr2_hdw_v4l_store_minor_number(struct pvr2_hdw * hdw,enum pvr2_v4l_type index,int v)3527 void pvr2_hdw_v4l_store_minor_number(struct pvr2_hdw *hdw,
3528 				     enum pvr2_v4l_type index,int v)
3529 {
3530 	switch (index) {
3531 	case pvr2_v4l_type_video: hdw->v4l_minor_number_video = v;break;
3532 	case pvr2_v4l_type_vbi: hdw->v4l_minor_number_vbi = v;break;
3533 	case pvr2_v4l_type_radio: hdw->v4l_minor_number_radio = v;break;
3534 	default: break;
3535 	}
3536 }
3537 
3538 
pvr2_ctl_write_complete(struct urb * urb)3539 static void pvr2_ctl_write_complete(struct urb *urb)
3540 {
3541 	struct pvr2_hdw *hdw = urb->context;
3542 	hdw->ctl_write_pend_flag = 0;
3543 	if (hdw->ctl_read_pend_flag) return;
3544 	complete(&hdw->ctl_done);
3545 }
3546 
3547 
pvr2_ctl_read_complete(struct urb * urb)3548 static void pvr2_ctl_read_complete(struct urb *urb)
3549 {
3550 	struct pvr2_hdw *hdw = urb->context;
3551 	hdw->ctl_read_pend_flag = 0;
3552 	if (hdw->ctl_write_pend_flag) return;
3553 	complete(&hdw->ctl_done);
3554 }
3555 
3556 struct hdw_timer {
3557 	struct timer_list timer;
3558 	struct pvr2_hdw *hdw;
3559 };
3560 
pvr2_ctl_timeout(struct timer_list * t)3561 static void pvr2_ctl_timeout(struct timer_list *t)
3562 {
3563 	struct hdw_timer *timer = timer_container_of(timer, t, timer);
3564 	struct pvr2_hdw *hdw = timer->hdw;
3565 
3566 	if (hdw->ctl_write_pend_flag || hdw->ctl_read_pend_flag) {
3567 		hdw->ctl_timeout_flag = !0;
3568 		if (hdw->ctl_write_pend_flag)
3569 			usb_unlink_urb(hdw->ctl_write_urb);
3570 		if (hdw->ctl_read_pend_flag)
3571 			usb_unlink_urb(hdw->ctl_read_urb);
3572 	}
3573 }
3574 
3575 
3576 /* Issue a command and get a response from the device.  This extended
3577    version includes a probe flag (which if set means that device errors
3578    should not be logged or treated as fatal) and a timeout in jiffies.
3579    This can be used to non-lethally probe the health of endpoint 1. */
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)3580 static int pvr2_send_request_ex(struct pvr2_hdw *hdw,
3581 				unsigned int timeout,int probe_fl,
3582 				void *write_data,unsigned int write_len,
3583 				void *read_data,unsigned int read_len)
3584 {
3585 	unsigned int idx;
3586 	int status = 0;
3587 	struct hdw_timer timer = {
3588 		.hdw = hdw,
3589 	};
3590 
3591 	if (!hdw->ctl_lock_held) {
3592 		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3593 			   "Attempted to execute control transfer without lock!!");
3594 		return -EDEADLK;
3595 	}
3596 	if (!hdw->flag_ok && !probe_fl) {
3597 		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3598 			   "Attempted to execute control transfer when device not ok");
3599 		return -EIO;
3600 	}
3601 	if (!(hdw->ctl_read_urb && hdw->ctl_write_urb)) {
3602 		if (!probe_fl) {
3603 			pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3604 				   "Attempted to execute control transfer when USB is disconnected");
3605 		}
3606 		return -ENOTTY;
3607 	}
3608 
3609 	/* Ensure that we have sane parameters */
3610 	if (!write_data) write_len = 0;
3611 	if (!read_data) read_len = 0;
3612 	if (write_len > PVR2_CTL_BUFFSIZE) {
3613 		pvr2_trace(
3614 			PVR2_TRACE_ERROR_LEGS,
3615 			"Attempted to execute %d byte control-write transfer (limit=%d)",
3616 			write_len,PVR2_CTL_BUFFSIZE);
3617 		return -EINVAL;
3618 	}
3619 	if (read_len > PVR2_CTL_BUFFSIZE) {
3620 		pvr2_trace(
3621 			PVR2_TRACE_ERROR_LEGS,
3622 			"Attempted to execute %d byte control-read transfer (limit=%d)",
3623 			read_len, PVR2_CTL_BUFFSIZE);
3624 		return -EINVAL;
3625 	}
3626 	if ((!write_len) && (!read_len)) {
3627 		pvr2_trace(
3628 			PVR2_TRACE_ERROR_LEGS,
3629 			"Attempted to execute null control transfer?");
3630 		return -EINVAL;
3631 	}
3632 
3633 
3634 	hdw->cmd_debug_state = 1;
3635 	if (write_len && write_data)
3636 		hdw->cmd_debug_code = ((unsigned char *)write_data)[0];
3637 	else
3638 		hdw->cmd_debug_code = 0;
3639 	hdw->cmd_debug_write_len = write_len;
3640 	hdw->cmd_debug_read_len = read_len;
3641 
3642 	/* Initialize common stuff */
3643 	init_completion(&hdw->ctl_done);
3644 	hdw->ctl_timeout_flag = 0;
3645 	hdw->ctl_write_pend_flag = 0;
3646 	hdw->ctl_read_pend_flag = 0;
3647 	timer_setup_on_stack(&timer.timer, pvr2_ctl_timeout, 0);
3648 	timer.timer.expires = jiffies + timeout;
3649 
3650 	if (write_len && write_data) {
3651 		hdw->cmd_debug_state = 2;
3652 		/* Transfer write data to internal buffer */
3653 		for (idx = 0; idx < write_len; idx++) {
3654 			hdw->ctl_write_buffer[idx] =
3655 				((unsigned char *)write_data)[idx];
3656 		}
3657 		/* Initiate a write request */
3658 		usb_fill_bulk_urb(hdw->ctl_write_urb,
3659 				  hdw->usb_dev,
3660 				  usb_sndbulkpipe(hdw->usb_dev,
3661 						  PVR2_CTL_WRITE_ENDPOINT),
3662 				  hdw->ctl_write_buffer,
3663 				  write_len,
3664 				  pvr2_ctl_write_complete,
3665 				  hdw);
3666 		hdw->ctl_write_urb->actual_length = 0;
3667 		hdw->ctl_write_pend_flag = !0;
3668 		if (usb_urb_ep_type_check(hdw->ctl_write_urb)) {
3669 			pvr2_trace(
3670 				PVR2_TRACE_ERROR_LEGS,
3671 				"Invalid write control endpoint");
3672 			return -EINVAL;
3673 		}
3674 		status = usb_submit_urb(hdw->ctl_write_urb,GFP_KERNEL);
3675 		if (status < 0) {
3676 			pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3677 				   "Failed to submit write-control URB status=%d",
3678 status);
3679 			hdw->ctl_write_pend_flag = 0;
3680 			goto done;
3681 		}
3682 	}
3683 
3684 	if (read_len) {
3685 		hdw->cmd_debug_state = 3;
3686 		memset(hdw->ctl_read_buffer,0x43,read_len);
3687 		/* Initiate a read request */
3688 		usb_fill_bulk_urb(hdw->ctl_read_urb,
3689 				  hdw->usb_dev,
3690 				  usb_rcvbulkpipe(hdw->usb_dev,
3691 						  PVR2_CTL_READ_ENDPOINT),
3692 				  hdw->ctl_read_buffer,
3693 				  read_len,
3694 				  pvr2_ctl_read_complete,
3695 				  hdw);
3696 		hdw->ctl_read_urb->actual_length = 0;
3697 		hdw->ctl_read_pend_flag = !0;
3698 		if (usb_urb_ep_type_check(hdw->ctl_read_urb)) {
3699 			pvr2_trace(
3700 				PVR2_TRACE_ERROR_LEGS,
3701 				"Invalid read control endpoint");
3702 			return -EINVAL;
3703 		}
3704 		status = usb_submit_urb(hdw->ctl_read_urb,GFP_KERNEL);
3705 		if (status < 0) {
3706 			pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3707 				   "Failed to submit read-control URB status=%d",
3708 status);
3709 			hdw->ctl_read_pend_flag = 0;
3710 			if (hdw->ctl_write_pend_flag) {
3711 				usb_unlink_urb(hdw->ctl_write_urb);
3712 				while (hdw->ctl_write_pend_flag)
3713 					wait_for_completion(&hdw->ctl_done);
3714 			}
3715 			goto done;
3716 		}
3717 	}
3718 
3719 	/* Start timer */
3720 	add_timer(&timer.timer);
3721 
3722 	/* Now wait for all I/O to complete */
3723 	hdw->cmd_debug_state = 4;
3724 	while (hdw->ctl_write_pend_flag || hdw->ctl_read_pend_flag) {
3725 		wait_for_completion(&hdw->ctl_done);
3726 	}
3727 	hdw->cmd_debug_state = 5;
3728 
3729 	/* Stop timer */
3730 	timer_delete_sync(&timer.timer);
3731 
3732 	hdw->cmd_debug_state = 6;
3733 	status = 0;
3734 
3735 	if (hdw->ctl_timeout_flag) {
3736 		status = -ETIMEDOUT;
3737 		if (!probe_fl) {
3738 			pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3739 				   "Timed out control-write");
3740 		}
3741 		goto done;
3742 	}
3743 
3744 	if (write_len) {
3745 		/* Validate results of write request */
3746 		if ((hdw->ctl_write_urb->status != 0) &&
3747 		    (hdw->ctl_write_urb->status != -ENOENT) &&
3748 		    (hdw->ctl_write_urb->status != -ESHUTDOWN) &&
3749 		    (hdw->ctl_write_urb->status != -ECONNRESET)) {
3750 			/* USB subsystem is reporting some kind of failure
3751 			   on the write */
3752 			status = hdw->ctl_write_urb->status;
3753 			if (!probe_fl) {
3754 				pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3755 					   "control-write URB failure, status=%d",
3756 					   status);
3757 			}
3758 			goto done;
3759 		}
3760 		if (hdw->ctl_write_urb->actual_length < write_len) {
3761 			/* Failed to write enough data */
3762 			status = -EIO;
3763 			if (!probe_fl) {
3764 				pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3765 					   "control-write URB short, expected=%d got=%d",
3766 					   write_len,
3767 					   hdw->ctl_write_urb->actual_length);
3768 			}
3769 			goto done;
3770 		}
3771 	}
3772 	if (read_len && read_data) {
3773 		/* Validate results of read request */
3774 		if ((hdw->ctl_read_urb->status != 0) &&
3775 		    (hdw->ctl_read_urb->status != -ENOENT) &&
3776 		    (hdw->ctl_read_urb->status != -ESHUTDOWN) &&
3777 		    (hdw->ctl_read_urb->status != -ECONNRESET)) {
3778 			/* USB subsystem is reporting some kind of failure
3779 			   on the read */
3780 			status = hdw->ctl_read_urb->status;
3781 			if (!probe_fl) {
3782 				pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3783 					   "control-read URB failure, status=%d",
3784 					   status);
3785 			}
3786 			goto done;
3787 		}
3788 		if (hdw->ctl_read_urb->actual_length < read_len) {
3789 			/* Failed to read enough data */
3790 			status = -EIO;
3791 			if (!probe_fl) {
3792 				pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3793 					   "control-read URB short, expected=%d got=%d",
3794 					   read_len,
3795 					   hdw->ctl_read_urb->actual_length);
3796 			}
3797 			goto done;
3798 		}
3799 		/* Transfer retrieved data out from internal buffer */
3800 		for (idx = 0; idx < read_len; idx++) {
3801 			((unsigned char *)read_data)[idx] =
3802 				hdw->ctl_read_buffer[idx];
3803 		}
3804 	}
3805 
3806  done:
3807 
3808 	hdw->cmd_debug_state = 0;
3809 	if ((status < 0) && (!probe_fl)) {
3810 		pvr2_hdw_render_useless(hdw);
3811 	}
3812 	timer_destroy_on_stack(&timer.timer);
3813 
3814 	return status;
3815 }
3816 
3817 
pvr2_send_request(struct pvr2_hdw * hdw,void * write_data,unsigned int write_len,void * read_data,unsigned int read_len)3818 int pvr2_send_request(struct pvr2_hdw *hdw,
3819 		      void *write_data,unsigned int write_len,
3820 		      void *read_data,unsigned int read_len)
3821 {
3822 	return pvr2_send_request_ex(hdw,HZ*4,0,
3823 				    write_data,write_len,
3824 				    read_data,read_len);
3825 }
3826 
3827 
pvr2_issue_simple_cmd(struct pvr2_hdw * hdw,u32 cmdcode)3828 static int pvr2_issue_simple_cmd(struct pvr2_hdw *hdw,u32 cmdcode)
3829 {
3830 	int ret;
3831 	unsigned int cnt = 1;
3832 	unsigned int args = 0;
3833 	LOCK_TAKE(hdw->ctl_lock);
3834 	hdw->cmd_buffer[0] = cmdcode & 0xffu;
3835 	args = (cmdcode >> 8) & 0xffu;
3836 	args = (args > 2) ? 2 : args;
3837 	if (args) {
3838 		cnt += args;
3839 		hdw->cmd_buffer[1] = (cmdcode >> 16) & 0xffu;
3840 		if (args > 1) {
3841 			hdw->cmd_buffer[2] = (cmdcode >> 24) & 0xffu;
3842 		}
3843 	}
3844 	if (pvrusb2_debug & PVR2_TRACE_INIT) {
3845 		unsigned int idx;
3846 		unsigned int ccnt,bcnt;
3847 		char tbuf[50];
3848 		cmdcode &= 0xffu;
3849 		bcnt = 0;
3850 		ccnt = scnprintf(tbuf+bcnt,
3851 				 sizeof(tbuf)-bcnt,
3852 				 "Sending FX2 command 0x%x",cmdcode);
3853 		bcnt += ccnt;
3854 		for (idx = 0; idx < ARRAY_SIZE(pvr2_fx2cmd_desc); idx++) {
3855 			if (pvr2_fx2cmd_desc[idx].id == cmdcode) {
3856 				ccnt = scnprintf(tbuf+bcnt,
3857 						 sizeof(tbuf)-bcnt,
3858 						 " \"%s\"",
3859 						 pvr2_fx2cmd_desc[idx].desc);
3860 				bcnt += ccnt;
3861 				break;
3862 			}
3863 		}
3864 		if (args) {
3865 			ccnt = scnprintf(tbuf+bcnt,
3866 					 sizeof(tbuf)-bcnt,
3867 					 " (%u",hdw->cmd_buffer[1]);
3868 			bcnt += ccnt;
3869 			if (args > 1) {
3870 				ccnt = scnprintf(tbuf+bcnt,
3871 						 sizeof(tbuf)-bcnt,
3872 						 ",%u",hdw->cmd_buffer[2]);
3873 				bcnt += ccnt;
3874 			}
3875 			ccnt = scnprintf(tbuf+bcnt,
3876 					 sizeof(tbuf)-bcnt,
3877 					 ")");
3878 			bcnt += ccnt;
3879 		}
3880 		pvr2_trace(PVR2_TRACE_INIT,"%.*s",bcnt,tbuf);
3881 	}
3882 	ret = pvr2_send_request(hdw,hdw->cmd_buffer,cnt,NULL,0);
3883 	LOCK_GIVE(hdw->ctl_lock);
3884 	return ret;
3885 }
3886 
3887 
pvr2_write_register(struct pvr2_hdw * hdw,u16 reg,u32 data)3888 int pvr2_write_register(struct pvr2_hdw *hdw, u16 reg, u32 data)
3889 {
3890 	int ret;
3891 
3892 	LOCK_TAKE(hdw->ctl_lock);
3893 
3894 	hdw->cmd_buffer[0] = FX2CMD_REG_WRITE;  /* write register prefix */
3895 	PVR2_DECOMPOSE_LE(hdw->cmd_buffer,1,data);
3896 	hdw->cmd_buffer[5] = 0;
3897 	hdw->cmd_buffer[6] = (reg >> 8) & 0xff;
3898 	hdw->cmd_buffer[7] = reg & 0xff;
3899 
3900 
3901 	ret = pvr2_send_request(hdw, hdw->cmd_buffer, 8, hdw->cmd_buffer, 0);
3902 
3903 	LOCK_GIVE(hdw->ctl_lock);
3904 
3905 	return ret;
3906 }
3907 
3908 
pvr2_read_register(struct pvr2_hdw * hdw,u16 reg,u32 * data)3909 static int pvr2_read_register(struct pvr2_hdw *hdw, u16 reg, u32 *data)
3910 {
3911 	int ret = 0;
3912 
3913 	LOCK_TAKE(hdw->ctl_lock);
3914 
3915 	hdw->cmd_buffer[0] = FX2CMD_REG_READ;  /* read register prefix */
3916 	hdw->cmd_buffer[1] = 0;
3917 	hdw->cmd_buffer[2] = 0;
3918 	hdw->cmd_buffer[3] = 0;
3919 	hdw->cmd_buffer[4] = 0;
3920 	hdw->cmd_buffer[5] = 0;
3921 	hdw->cmd_buffer[6] = (reg >> 8) & 0xff;
3922 	hdw->cmd_buffer[7] = reg & 0xff;
3923 
3924 	ret |= pvr2_send_request(hdw, hdw->cmd_buffer, 8, hdw->cmd_buffer, 4);
3925 	*data = PVR2_COMPOSE_LE(hdw->cmd_buffer,0);
3926 
3927 	LOCK_GIVE(hdw->ctl_lock);
3928 
3929 	return ret;
3930 }
3931 
3932 
pvr2_hdw_render_useless(struct pvr2_hdw * hdw)3933 void pvr2_hdw_render_useless(struct pvr2_hdw *hdw)
3934 {
3935 	if (!hdw->flag_ok) return;
3936 	pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3937 		   "Device being rendered inoperable");
3938 	if (hdw->vid_stream) {
3939 		pvr2_stream_setup(hdw->vid_stream,NULL,0,0);
3940 	}
3941 	hdw->flag_ok = 0;
3942 	trace_stbit("flag_ok",hdw->flag_ok);
3943 	pvr2_hdw_state_sched(hdw);
3944 }
3945 
3946 
pvr2_hdw_device_reset(struct pvr2_hdw * hdw)3947 void pvr2_hdw_device_reset(struct pvr2_hdw *hdw)
3948 {
3949 	int ret;
3950 	pvr2_trace(PVR2_TRACE_INIT,"Performing a device reset...");
3951 	ret = usb_lock_device_for_reset(hdw->usb_dev,NULL);
3952 	if (ret == 0) {
3953 		ret = usb_reset_device(hdw->usb_dev);
3954 		usb_unlock_device(hdw->usb_dev);
3955 	} else {
3956 		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3957 			   "Failed to lock USB device ret=%d",ret);
3958 	}
3959 	if (init_pause_msec) {
3960 		pvr2_trace(PVR2_TRACE_INFO,
3961 			   "Waiting %u msec for hardware to settle",
3962 			   init_pause_msec);
3963 		msleep(init_pause_msec);
3964 	}
3965 
3966 }
3967 
3968 
pvr2_hdw_cpureset_assert(struct pvr2_hdw * hdw,int val)3969 void pvr2_hdw_cpureset_assert(struct pvr2_hdw *hdw,int val)
3970 {
3971 	char *da;
3972 	unsigned int pipe;
3973 	int ret;
3974 
3975 	if (!hdw->usb_dev) return;
3976 
3977 	da = kmalloc(16, GFP_KERNEL);
3978 
3979 	if (da == NULL) {
3980 		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3981 			   "Unable to allocate memory to control CPU reset");
3982 		return;
3983 	}
3984 
3985 	pvr2_trace(PVR2_TRACE_INIT,"cpureset_assert(%d)",val);
3986 
3987 	da[0] = val ? 0x01 : 0x00;
3988 
3989 	/* Write the CPUCS register on the 8051.  The lsb of the register
3990 	   is the reset bit; a 1 asserts reset while a 0 clears it. */
3991 	pipe = usb_sndctrlpipe(hdw->usb_dev, 0);
3992 	ret = usb_control_msg(hdw->usb_dev,pipe,0xa0,0x40,0xe600,0,da,1,1000);
3993 	if (ret < 0) {
3994 		pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3995 			   "cpureset_assert(%d) error=%d",val,ret);
3996 		pvr2_hdw_render_useless(hdw);
3997 	}
3998 
3999 	kfree(da);
4000 }
4001 
4002 
pvr2_hdw_cmd_deep_reset(struct pvr2_hdw * hdw)4003 int pvr2_hdw_cmd_deep_reset(struct pvr2_hdw *hdw)
4004 {
4005 	return pvr2_issue_simple_cmd(hdw,FX2CMD_DEEP_RESET);
4006 }
4007 
4008 
pvr2_hdw_cmd_powerup(struct pvr2_hdw * hdw)4009 int pvr2_hdw_cmd_powerup(struct pvr2_hdw *hdw)
4010 {
4011 	return pvr2_issue_simple_cmd(hdw,FX2CMD_POWER_ON);
4012 }
4013 
4014 
4015 
pvr2_hdw_cmd_decoder_reset(struct pvr2_hdw * hdw)4016 int pvr2_hdw_cmd_decoder_reset(struct pvr2_hdw *hdw)
4017 {
4018 	pvr2_trace(PVR2_TRACE_INIT,
4019 		   "Requesting decoder reset");
4020 	if (hdw->decoder_client_id) {
4021 		v4l2_device_call_all(&hdw->v4l2_dev, hdw->decoder_client_id,
4022 				     core, reset, 0);
4023 		pvr2_hdw_cx25840_vbi_hack(hdw);
4024 		return 0;
4025 	}
4026 	pvr2_trace(PVR2_TRACE_INIT,
4027 		   "Unable to reset decoder: nothing attached");
4028 	return -ENOTTY;
4029 }
4030 
4031 
pvr2_hdw_cmd_hcw_demod_reset(struct pvr2_hdw * hdw,int onoff)4032 static int pvr2_hdw_cmd_hcw_demod_reset(struct pvr2_hdw *hdw, int onoff)
4033 {
4034 	hdw->flag_ok = !0;
4035 
4036 	/* Use this for Hauppauge 160xxx only */
4037 	if (le16_to_cpu(hdw->usb_dev->descriptor.idVendor) == 0x2040 &&
4038 	    (le16_to_cpu(hdw->usb_dev->descriptor.idProduct) == 0x7502 ||
4039 	     le16_to_cpu(hdw->usb_dev->descriptor.idProduct) == 0x7510)) {
4040 		pr_debug("%s(): resetting demod on Hauppauge 160xxx platform skipped\n",
4041 			 __func__);
4042 		/* Can't reset 160xxx or it will trash Demod tristate */
4043 		return pvr2_issue_simple_cmd(hdw,
4044 					     FX2CMD_HCW_MAKO_SLEEP_PIN |
4045 					     (1 << 8) |
4046 					     ((onoff ? 1 : 0) << 16));
4047 	}
4048 
4049 	return pvr2_issue_simple_cmd(hdw,
4050 				     FX2CMD_HCW_DEMOD_RESETIN |
4051 				     (1 << 8) |
4052 				     ((onoff ? 1 : 0) << 16));
4053 }
4054 
4055 
pvr2_hdw_cmd_onair_fe_power_ctrl(struct pvr2_hdw * hdw,int onoff)4056 static int pvr2_hdw_cmd_onair_fe_power_ctrl(struct pvr2_hdw *hdw, int onoff)
4057 {
4058 	hdw->flag_ok = !0;
4059 	return pvr2_issue_simple_cmd(hdw,(onoff ?
4060 					  FX2CMD_ONAIR_DTV_POWER_ON :
4061 					  FX2CMD_ONAIR_DTV_POWER_OFF));
4062 }
4063 
4064 
pvr2_hdw_cmd_onair_digital_path_ctrl(struct pvr2_hdw * hdw,int onoff)4065 static int pvr2_hdw_cmd_onair_digital_path_ctrl(struct pvr2_hdw *hdw,
4066 						int onoff)
4067 {
4068 	return pvr2_issue_simple_cmd(hdw,(onoff ?
4069 					  FX2CMD_ONAIR_DTV_STREAMING_ON :
4070 					  FX2CMD_ONAIR_DTV_STREAMING_OFF));
4071 }
4072 
4073 
pvr2_hdw_cmd_modeswitch(struct pvr2_hdw * hdw,int digitalFl)4074 static void pvr2_hdw_cmd_modeswitch(struct pvr2_hdw *hdw,int digitalFl)
4075 {
4076 	int cmode;
4077 	/* Compare digital/analog desired setting with current setting.  If
4078 	   they don't match, fix it... */
4079 	cmode = (digitalFl ? PVR2_PATHWAY_DIGITAL : PVR2_PATHWAY_ANALOG);
4080 	if (cmode == hdw->pathway_state) {
4081 		/* They match; nothing to do */
4082 		return;
4083 	}
4084 
4085 	switch (hdw->hdw_desc->digital_control_scheme) {
4086 	case PVR2_DIGITAL_SCHEME_HAUPPAUGE:
4087 		pvr2_hdw_cmd_hcw_demod_reset(hdw,digitalFl);
4088 		if (cmode == PVR2_PATHWAY_ANALOG) {
4089 			/* If moving to analog mode, also force the decoder
4090 			   to reset.  If no decoder is attached, then it's
4091 			   ok to ignore this because if/when the decoder
4092 			   attaches, it will reset itself at that time. */
4093 			pvr2_hdw_cmd_decoder_reset(hdw);
4094 		}
4095 		break;
4096 	case PVR2_DIGITAL_SCHEME_ONAIR:
4097 		/* Supposedly we should always have the power on whether in
4098 		   digital or analog mode.  But for now do what appears to
4099 		   work... */
4100 		pvr2_hdw_cmd_onair_fe_power_ctrl(hdw,digitalFl);
4101 		break;
4102 	default: break;
4103 	}
4104 
4105 	pvr2_hdw_untrip_unlocked(hdw);
4106 	hdw->pathway_state = cmode;
4107 }
4108 
4109 
pvr2_led_ctrl_hauppauge(struct pvr2_hdw * hdw,int onoff)4110 static void pvr2_led_ctrl_hauppauge(struct pvr2_hdw *hdw, int onoff)
4111 {
4112 	/* change some GPIO data
4113 	 *
4114 	 * note: bit d7 of dir appears to control the LED,
4115 	 * so we shut it off here.
4116 	 *
4117 	 */
4118 	if (onoff) {
4119 		pvr2_hdw_gpio_chg_dir(hdw, 0xffffffff, 0x00000481);
4120 	} else {
4121 		pvr2_hdw_gpio_chg_dir(hdw, 0xffffffff, 0x00000401);
4122 	}
4123 	pvr2_hdw_gpio_chg_out(hdw, 0xffffffff, 0x00000000);
4124 }
4125 
4126 
4127 typedef void (*led_method_func)(struct pvr2_hdw *,int);
4128 
4129 static led_method_func led_methods[] = {
4130 	[PVR2_LED_SCHEME_HAUPPAUGE] = pvr2_led_ctrl_hauppauge,
4131 };
4132 
4133 
4134 /* Toggle LED */
pvr2_led_ctrl(struct pvr2_hdw * hdw,int onoff)4135 static void pvr2_led_ctrl(struct pvr2_hdw *hdw,int onoff)
4136 {
4137 	unsigned int scheme_id;
4138 	led_method_func fp;
4139 
4140 	if ((!onoff) == (!hdw->led_on)) return;
4141 
4142 	hdw->led_on = onoff != 0;
4143 
4144 	scheme_id = hdw->hdw_desc->led_scheme;
4145 	if (scheme_id < ARRAY_SIZE(led_methods)) {
4146 		fp = led_methods[scheme_id];
4147 	} else {
4148 		fp = NULL;
4149 	}
4150 
4151 	if (fp) (*fp)(hdw,onoff);
4152 }
4153 
4154 
4155 /* Stop / start video stream transport */
pvr2_hdw_cmd_usbstream(struct pvr2_hdw * hdw,int runFl)4156 static int pvr2_hdw_cmd_usbstream(struct pvr2_hdw *hdw,int runFl)
4157 {
4158 	int ret;
4159 
4160 	/* If we're in analog mode, then just issue the usual analog
4161 	   command. */
4162 	if (hdw->pathway_state == PVR2_PATHWAY_ANALOG) {
4163 		return pvr2_issue_simple_cmd(hdw,
4164 					     (runFl ?
4165 					      FX2CMD_STREAMING_ON :
4166 					      FX2CMD_STREAMING_OFF));
4167 		/*Note: Not reached */
4168 	}
4169 
4170 	if (hdw->pathway_state != PVR2_PATHWAY_DIGITAL) {
4171 		/* Whoops, we don't know what mode we're in... */
4172 		return -EINVAL;
4173 	}
4174 
4175 	/* To get here we have to be in digital mode.  The mechanism here
4176 	   is unfortunately different for different vendors.  So we switch
4177 	   on the device's digital scheme attribute in order to figure out
4178 	   what to do. */
4179 	switch (hdw->hdw_desc->digital_control_scheme) {
4180 	case PVR2_DIGITAL_SCHEME_HAUPPAUGE:
4181 		return pvr2_issue_simple_cmd(hdw,
4182 					     (runFl ?
4183 					      FX2CMD_HCW_DTV_STREAMING_ON :
4184 					      FX2CMD_HCW_DTV_STREAMING_OFF));
4185 	case PVR2_DIGITAL_SCHEME_ONAIR:
4186 		ret = pvr2_issue_simple_cmd(hdw,
4187 					    (runFl ?
4188 					     FX2CMD_STREAMING_ON :
4189 					     FX2CMD_STREAMING_OFF));
4190 		if (ret) return ret;
4191 		return pvr2_hdw_cmd_onair_digital_path_ctrl(hdw,runFl);
4192 	default:
4193 		return -EINVAL;
4194 	}
4195 }
4196 
4197 
4198 /* Evaluate whether or not state_pathway_ok can change */
state_eval_pathway_ok(struct pvr2_hdw * hdw)4199 static int state_eval_pathway_ok(struct pvr2_hdw *hdw)
4200 {
4201 	if (hdw->state_pathway_ok) {
4202 		/* Nothing to do if pathway is already ok */
4203 		return 0;
4204 	}
4205 	if (!hdw->state_pipeline_idle) {
4206 		/* Not allowed to change anything if pipeline is not idle */
4207 		return 0;
4208 	}
4209 	pvr2_hdw_cmd_modeswitch(hdw,hdw->input_val == PVR2_CVAL_INPUT_DTV);
4210 	hdw->state_pathway_ok = !0;
4211 	trace_stbit("state_pathway_ok",hdw->state_pathway_ok);
4212 	return !0;
4213 }
4214 
4215 
4216 /* Evaluate whether or not state_encoder_ok can change */
state_eval_encoder_ok(struct pvr2_hdw * hdw)4217 static int state_eval_encoder_ok(struct pvr2_hdw *hdw)
4218 {
4219 	if (hdw->state_encoder_ok) return 0;
4220 	if (hdw->flag_tripped) return 0;
4221 	if (hdw->state_encoder_run) return 0;
4222 	if (hdw->state_encoder_config) return 0;
4223 	if (hdw->state_decoder_run) return 0;
4224 	if (hdw->state_usbstream_run) return 0;
4225 	if (hdw->pathway_state == PVR2_PATHWAY_DIGITAL) {
4226 		if (!hdw->hdw_desc->flag_digital_requires_cx23416) return 0;
4227 	} else if (hdw->pathway_state != PVR2_PATHWAY_ANALOG) {
4228 		return 0;
4229 	}
4230 
4231 	if (pvr2_upload_firmware2(hdw) < 0) {
4232 		hdw->flag_tripped = !0;
4233 		trace_stbit("flag_tripped",hdw->flag_tripped);
4234 		return !0;
4235 	}
4236 	hdw->state_encoder_ok = !0;
4237 	trace_stbit("state_encoder_ok",hdw->state_encoder_ok);
4238 	return !0;
4239 }
4240 
4241 
4242 /* Evaluate whether or not state_encoder_config can change */
state_eval_encoder_config(struct pvr2_hdw * hdw)4243 static int state_eval_encoder_config(struct pvr2_hdw *hdw)
4244 {
4245 	if (hdw->state_encoder_config) {
4246 		if (hdw->state_encoder_ok) {
4247 			if (hdw->state_pipeline_req &&
4248 			    !hdw->state_pipeline_pause) return 0;
4249 		}
4250 		hdw->state_encoder_config = 0;
4251 		hdw->state_encoder_waitok = 0;
4252 		trace_stbit("state_encoder_waitok",hdw->state_encoder_waitok);
4253 		/* paranoia - solve race if timer just completed */
4254 		timer_delete_sync(&hdw->encoder_wait_timer);
4255 	} else {
4256 		if (!hdw->state_pathway_ok ||
4257 		    (hdw->pathway_state != PVR2_PATHWAY_ANALOG) ||
4258 		    !hdw->state_encoder_ok ||
4259 		    !hdw->state_pipeline_idle ||
4260 		    hdw->state_pipeline_pause ||
4261 		    !hdw->state_pipeline_req ||
4262 		    !hdw->state_pipeline_config) {
4263 			/* We must reset the enforced wait interval if
4264 			   anything has happened that might have disturbed
4265 			   the encoder.  This should be a rare case. */
4266 			if (timer_pending(&hdw->encoder_wait_timer)) {
4267 				timer_delete_sync(&hdw->encoder_wait_timer);
4268 			}
4269 			if (hdw->state_encoder_waitok) {
4270 				/* Must clear the state - therefore we did
4271 				   something to a state bit and must also
4272 				   return true. */
4273 				hdw->state_encoder_waitok = 0;
4274 				trace_stbit("state_encoder_waitok",
4275 					    hdw->state_encoder_waitok);
4276 				return !0;
4277 			}
4278 			return 0;
4279 		}
4280 		if (!hdw->state_encoder_waitok) {
4281 			if (!timer_pending(&hdw->encoder_wait_timer)) {
4282 				/* waitok flag wasn't set and timer isn't
4283 				   running.  Check flag once more to avoid
4284 				   a race then start the timer.  This is
4285 				   the point when we measure out a minimal
4286 				   quiet interval before doing something to
4287 				   the encoder. */
4288 				if (!hdw->state_encoder_waitok) {
4289 					hdw->encoder_wait_timer.expires =
4290 						jiffies + msecs_to_jiffies(
4291 						TIME_MSEC_ENCODER_WAIT);
4292 					add_timer(&hdw->encoder_wait_timer);
4293 				}
4294 			}
4295 			/* We can't continue until we know we have been
4296 			   quiet for the interval measured by this
4297 			   timer. */
4298 			return 0;
4299 		}
4300 		pvr2_encoder_configure(hdw);
4301 		if (hdw->state_encoder_ok) hdw->state_encoder_config = !0;
4302 	}
4303 	trace_stbit("state_encoder_config",hdw->state_encoder_config);
4304 	return !0;
4305 }
4306 
4307 
4308 /* Return true if the encoder should not be running. */
state_check_disable_encoder_run(struct pvr2_hdw * hdw)4309 static int state_check_disable_encoder_run(struct pvr2_hdw *hdw)
4310 {
4311 	if (!hdw->state_encoder_ok) {
4312 		/* Encoder isn't healthy at the moment, so stop it. */
4313 		return !0;
4314 	}
4315 	if (!hdw->state_pathway_ok) {
4316 		/* Mode is not understood at the moment (i.e. it wants to
4317 		   change), so encoder must be stopped. */
4318 		return !0;
4319 	}
4320 
4321 	switch (hdw->pathway_state) {
4322 	case PVR2_PATHWAY_ANALOG:
4323 		if (!hdw->state_decoder_run) {
4324 			/* We're in analog mode and the decoder is not
4325 			   running; thus the encoder should be stopped as
4326 			   well. */
4327 			return !0;
4328 		}
4329 		break;
4330 	case PVR2_PATHWAY_DIGITAL:
4331 		if (hdw->state_encoder_runok) {
4332 			/* This is a funny case.  We're in digital mode so
4333 			   really the encoder should be stopped.  However
4334 			   if it really is running, only kill it after
4335 			   runok has been set.  This gives a chance for the
4336 			   onair quirk to function (encoder must run
4337 			   briefly first, at least once, before onair
4338 			   digital streaming can work). */
4339 			return !0;
4340 		}
4341 		break;
4342 	default:
4343 		/* Unknown mode; so encoder should be stopped. */
4344 		return !0;
4345 	}
4346 
4347 	/* If we get here, we haven't found a reason to stop the
4348 	   encoder. */
4349 	return 0;
4350 }
4351 
4352 
4353 /* Return true if the encoder should be running. */
state_check_enable_encoder_run(struct pvr2_hdw * hdw)4354 static int state_check_enable_encoder_run(struct pvr2_hdw *hdw)
4355 {
4356 	if (!hdw->state_encoder_ok) {
4357 		/* Don't run the encoder if it isn't healthy... */
4358 		return 0;
4359 	}
4360 	if (!hdw->state_pathway_ok) {
4361 		/* Don't run the encoder if we don't (yet) know what mode
4362 		   we need to be in... */
4363 		return 0;
4364 	}
4365 
4366 	switch (hdw->pathway_state) {
4367 	case PVR2_PATHWAY_ANALOG:
4368 		if (hdw->state_decoder_run && hdw->state_decoder_ready) {
4369 			/* In analog mode, if the decoder is running, then
4370 			   run the encoder. */
4371 			return !0;
4372 		}
4373 		break;
4374 	case PVR2_PATHWAY_DIGITAL:
4375 		if ((hdw->hdw_desc->digital_control_scheme ==
4376 		     PVR2_DIGITAL_SCHEME_ONAIR) &&
4377 		    !hdw->state_encoder_runok) {
4378 			/* This is a quirk.  OnAir hardware won't stream
4379 			   digital until the encoder has been run at least
4380 			   once, for a minimal period of time (empiricially
4381 			   measured to be 1/4 second).  So if we're on
4382 			   OnAir hardware and the encoder has never been
4383 			   run at all, then start the encoder.  Normal
4384 			   state machine logic in the driver will
4385 			   automatically handle the remaining bits. */
4386 			return !0;
4387 		}
4388 		break;
4389 	default:
4390 		/* For completeness (unknown mode; encoder won't run ever) */
4391 		break;
4392 	}
4393 	/* If we get here, then we haven't found any reason to run the
4394 	   encoder, so don't run it. */
4395 	return 0;
4396 }
4397 
4398 
4399 /* Evaluate whether or not state_encoder_run can change */
state_eval_encoder_run(struct pvr2_hdw * hdw)4400 static int state_eval_encoder_run(struct pvr2_hdw *hdw)
4401 {
4402 	if (hdw->state_encoder_run) {
4403 		if (!state_check_disable_encoder_run(hdw)) return 0;
4404 		if (hdw->state_encoder_ok) {
4405 			timer_delete_sync(&hdw->encoder_run_timer);
4406 			if (pvr2_encoder_stop(hdw) < 0) return !0;
4407 		}
4408 		hdw->state_encoder_run = 0;
4409 	} else {
4410 		if (!state_check_enable_encoder_run(hdw)) return 0;
4411 		if (pvr2_encoder_start(hdw) < 0) return !0;
4412 		hdw->state_encoder_run = !0;
4413 		if (!hdw->state_encoder_runok) {
4414 			hdw->encoder_run_timer.expires = jiffies +
4415 				 msecs_to_jiffies(TIME_MSEC_ENCODER_OK);
4416 			add_timer(&hdw->encoder_run_timer);
4417 		}
4418 	}
4419 	trace_stbit("state_encoder_run",hdw->state_encoder_run);
4420 	return !0;
4421 }
4422 
4423 
4424 /* Timeout function for quiescent timer. */
pvr2_hdw_quiescent_timeout(struct timer_list * t)4425 static void pvr2_hdw_quiescent_timeout(struct timer_list *t)
4426 {
4427 	struct pvr2_hdw *hdw = timer_container_of(hdw, t, quiescent_timer);
4428 	hdw->state_decoder_quiescent = !0;
4429 	trace_stbit("state_decoder_quiescent",hdw->state_decoder_quiescent);
4430 	hdw->state_stale = !0;
4431 	schedule_work(&hdw->workpoll);
4432 }
4433 
4434 
4435 /* Timeout function for decoder stabilization timer. */
pvr2_hdw_decoder_stabilization_timeout(struct timer_list * t)4436 static void pvr2_hdw_decoder_stabilization_timeout(struct timer_list *t)
4437 {
4438 	struct pvr2_hdw *hdw = timer_container_of(hdw, t,
4439 						  decoder_stabilization_timer);
4440 	hdw->state_decoder_ready = !0;
4441 	trace_stbit("state_decoder_ready", hdw->state_decoder_ready);
4442 	hdw->state_stale = !0;
4443 	schedule_work(&hdw->workpoll);
4444 }
4445 
4446 
4447 /* Timeout function for encoder wait timer. */
pvr2_hdw_encoder_wait_timeout(struct timer_list * t)4448 static void pvr2_hdw_encoder_wait_timeout(struct timer_list *t)
4449 {
4450 	struct pvr2_hdw *hdw = timer_container_of(hdw, t, encoder_wait_timer);
4451 	hdw->state_encoder_waitok = !0;
4452 	trace_stbit("state_encoder_waitok",hdw->state_encoder_waitok);
4453 	hdw->state_stale = !0;
4454 	schedule_work(&hdw->workpoll);
4455 }
4456 
4457 
4458 /* Timeout function for encoder run timer. */
pvr2_hdw_encoder_run_timeout(struct timer_list * t)4459 static void pvr2_hdw_encoder_run_timeout(struct timer_list *t)
4460 {
4461 	struct pvr2_hdw *hdw = timer_container_of(hdw, t, encoder_run_timer);
4462 	if (!hdw->state_encoder_runok) {
4463 		hdw->state_encoder_runok = !0;
4464 		trace_stbit("state_encoder_runok",hdw->state_encoder_runok);
4465 		hdw->state_stale = !0;
4466 		schedule_work(&hdw->workpoll);
4467 	}
4468 }
4469 
4470 
4471 /* Evaluate whether or not state_decoder_run can change */
state_eval_decoder_run(struct pvr2_hdw * hdw)4472 static int state_eval_decoder_run(struct pvr2_hdw *hdw)
4473 {
4474 	if (hdw->state_decoder_run) {
4475 		if (hdw->state_encoder_ok) {
4476 			if (hdw->state_pipeline_req &&
4477 			    !hdw->state_pipeline_pause &&
4478 			    hdw->state_pathway_ok) return 0;
4479 		}
4480 		if (!hdw->flag_decoder_missed) {
4481 			pvr2_decoder_enable(hdw,0);
4482 		}
4483 		hdw->state_decoder_quiescent = 0;
4484 		hdw->state_decoder_run = 0;
4485 		/* paranoia - solve race if timer(s) just completed */
4486 		timer_delete_sync(&hdw->quiescent_timer);
4487 		/* Kill the stabilization timer, in case we're killing the
4488 		   encoder before the previous stabilization interval has
4489 		   been properly timed. */
4490 		timer_delete_sync(&hdw->decoder_stabilization_timer);
4491 		hdw->state_decoder_ready = 0;
4492 	} else {
4493 		if (!hdw->state_decoder_quiescent) {
4494 			if (!timer_pending(&hdw->quiescent_timer)) {
4495 				/* We don't do something about the
4496 				   quiescent timer until right here because
4497 				   we also want to catch cases where the
4498 				   decoder was already not running (like
4499 				   after initialization) as opposed to
4500 				   knowing that we had just stopped it.
4501 				   The second flag check is here to cover a
4502 				   race - the timer could have run and set
4503 				   this flag just after the previous check
4504 				   but before we did the pending check. */
4505 				if (!hdw->state_decoder_quiescent) {
4506 					hdw->quiescent_timer.expires =
4507 						jiffies + msecs_to_jiffies(
4508 						TIME_MSEC_DECODER_WAIT);
4509 					add_timer(&hdw->quiescent_timer);
4510 				}
4511 			}
4512 			/* Don't allow decoder to start again until it has
4513 			   been quiesced first.  This little detail should
4514 			   hopefully further stabilize the encoder. */
4515 			return 0;
4516 		}
4517 		if (!hdw->state_pathway_ok ||
4518 		    (hdw->pathway_state != PVR2_PATHWAY_ANALOG) ||
4519 		    !hdw->state_pipeline_req ||
4520 		    hdw->state_pipeline_pause ||
4521 		    !hdw->state_pipeline_config ||
4522 		    !hdw->state_encoder_config ||
4523 		    !hdw->state_encoder_ok) return 0;
4524 		timer_delete_sync(&hdw->quiescent_timer);
4525 		if (hdw->flag_decoder_missed) return 0;
4526 		if (pvr2_decoder_enable(hdw,!0) < 0) return 0;
4527 		hdw->state_decoder_quiescent = 0;
4528 		hdw->state_decoder_ready = 0;
4529 		hdw->state_decoder_run = !0;
4530 		if (hdw->decoder_client_id == PVR2_CLIENT_ID_SAA7115) {
4531 			hdw->decoder_stabilization_timer.expires =
4532 				jiffies + msecs_to_jiffies(
4533 				TIME_MSEC_DECODER_STABILIZATION_WAIT);
4534 			add_timer(&hdw->decoder_stabilization_timer);
4535 		} else {
4536 			hdw->state_decoder_ready = !0;
4537 		}
4538 	}
4539 	trace_stbit("state_decoder_quiescent",hdw->state_decoder_quiescent);
4540 	trace_stbit("state_decoder_run",hdw->state_decoder_run);
4541 	trace_stbit("state_decoder_ready", hdw->state_decoder_ready);
4542 	return !0;
4543 }
4544 
4545 
4546 /* Evaluate whether or not state_usbstream_run can change */
state_eval_usbstream_run(struct pvr2_hdw * hdw)4547 static int state_eval_usbstream_run(struct pvr2_hdw *hdw)
4548 {
4549 	if (hdw->state_usbstream_run) {
4550 		int fl = !0;
4551 		if (hdw->pathway_state == PVR2_PATHWAY_ANALOG) {
4552 			fl = (hdw->state_encoder_ok &&
4553 			      hdw->state_encoder_run);
4554 		} else if ((hdw->pathway_state == PVR2_PATHWAY_DIGITAL) &&
4555 			   (hdw->hdw_desc->flag_digital_requires_cx23416)) {
4556 			fl = hdw->state_encoder_ok;
4557 		}
4558 		if (fl &&
4559 		    hdw->state_pipeline_req &&
4560 		    !hdw->state_pipeline_pause &&
4561 		    hdw->state_pathway_ok) {
4562 			return 0;
4563 		}
4564 		pvr2_hdw_cmd_usbstream(hdw,0);
4565 		hdw->state_usbstream_run = 0;
4566 	} else {
4567 		if (!hdw->state_pipeline_req ||
4568 		    hdw->state_pipeline_pause ||
4569 		    !hdw->state_pathway_ok) return 0;
4570 		if (hdw->pathway_state == PVR2_PATHWAY_ANALOG) {
4571 			if (!hdw->state_encoder_ok ||
4572 			    !hdw->state_encoder_run) return 0;
4573 		} else if ((hdw->pathway_state == PVR2_PATHWAY_DIGITAL) &&
4574 			   (hdw->hdw_desc->flag_digital_requires_cx23416)) {
4575 			if (!hdw->state_encoder_ok) return 0;
4576 			if (hdw->state_encoder_run) return 0;
4577 			if (hdw->hdw_desc->digital_control_scheme ==
4578 			    PVR2_DIGITAL_SCHEME_ONAIR) {
4579 				/* OnAir digital receivers won't stream
4580 				   unless the analog encoder has run first.
4581 				   Why?  I have no idea.  But don't even
4582 				   try until we know the analog side is
4583 				   known to have run. */
4584 				if (!hdw->state_encoder_runok) return 0;
4585 			}
4586 		}
4587 		if (pvr2_hdw_cmd_usbstream(hdw,!0) < 0) return 0;
4588 		hdw->state_usbstream_run = !0;
4589 	}
4590 	trace_stbit("state_usbstream_run",hdw->state_usbstream_run);
4591 	return !0;
4592 }
4593 
4594 
4595 /* Attempt to configure pipeline, if needed */
state_eval_pipeline_config(struct pvr2_hdw * hdw)4596 static int state_eval_pipeline_config(struct pvr2_hdw *hdw)
4597 {
4598 	if (hdw->state_pipeline_config ||
4599 	    hdw->state_pipeline_pause) return 0;
4600 	pvr2_hdw_commit_execute(hdw);
4601 	return !0;
4602 }
4603 
4604 
4605 /* Update pipeline idle and pipeline pause tracking states based on other
4606    inputs.  This must be called whenever the other relevant inputs have
4607    changed. */
state_update_pipeline_state(struct pvr2_hdw * hdw)4608 static int state_update_pipeline_state(struct pvr2_hdw *hdw)
4609 {
4610 	unsigned int st;
4611 	int updatedFl = 0;
4612 	/* Update pipeline state */
4613 	st = !(hdw->state_encoder_run ||
4614 	       hdw->state_decoder_run ||
4615 	       hdw->state_usbstream_run ||
4616 	       (!hdw->state_decoder_quiescent));
4617 	if (!st != !hdw->state_pipeline_idle) {
4618 		hdw->state_pipeline_idle = st;
4619 		updatedFl = !0;
4620 	}
4621 	if (hdw->state_pipeline_idle && hdw->state_pipeline_pause) {
4622 		hdw->state_pipeline_pause = 0;
4623 		updatedFl = !0;
4624 	}
4625 	return updatedFl;
4626 }
4627 
4628 
4629 typedef int (*state_eval_func)(struct pvr2_hdw *);
4630 
4631 /* Set of functions to be run to evaluate various states in the driver. */
4632 static const state_eval_func eval_funcs[] = {
4633 	state_eval_pathway_ok,
4634 	state_eval_pipeline_config,
4635 	state_eval_encoder_ok,
4636 	state_eval_encoder_config,
4637 	state_eval_decoder_run,
4638 	state_eval_encoder_run,
4639 	state_eval_usbstream_run,
4640 };
4641 
4642 
4643 /* Process various states and return true if we did anything interesting. */
pvr2_hdw_state_update(struct pvr2_hdw * hdw)4644 static int pvr2_hdw_state_update(struct pvr2_hdw *hdw)
4645 {
4646 	unsigned int i;
4647 	int state_updated = 0;
4648 	int check_flag;
4649 
4650 	if (!hdw->state_stale) return 0;
4651 	if ((hdw->fw1_state != FW1_STATE_OK) ||
4652 	    !hdw->flag_ok) {
4653 		hdw->state_stale = 0;
4654 		return !0;
4655 	}
4656 	/* This loop is the heart of the entire driver.  It keeps trying to
4657 	   evaluate various bits of driver state until nothing changes for
4658 	   one full iteration.  Each "bit of state" tracks some global
4659 	   aspect of the driver, e.g. whether decoder should run, if
4660 	   pipeline is configured, usb streaming is on, etc.  We separately
4661 	   evaluate each of those questions based on other driver state to
4662 	   arrive at the correct running configuration. */
4663 	do {
4664 		check_flag = 0;
4665 		state_update_pipeline_state(hdw);
4666 		/* Iterate over each bit of state */
4667 		for (i = 0; (i<ARRAY_SIZE(eval_funcs)) && hdw->flag_ok; i++) {
4668 			if ((*eval_funcs[i])(hdw)) {
4669 				check_flag = !0;
4670 				state_updated = !0;
4671 				state_update_pipeline_state(hdw);
4672 			}
4673 		}
4674 	} while (check_flag && hdw->flag_ok);
4675 	hdw->state_stale = 0;
4676 	trace_stbit("state_stale",hdw->state_stale);
4677 	return state_updated;
4678 }
4679 
4680 
print_input_mask(unsigned int msk,char * buf,unsigned int acnt)4681 static unsigned int print_input_mask(unsigned int msk,
4682 				     char *buf,unsigned int acnt)
4683 {
4684 	unsigned int idx,ccnt;
4685 	unsigned int tcnt = 0;
4686 	for (idx = 0; idx < ARRAY_SIZE(control_values_input); idx++) {
4687 		if (!((1UL << idx) & msk)) continue;
4688 		ccnt = scnprintf(buf+tcnt,
4689 				 acnt-tcnt,
4690 				 "%s%s",
4691 				 (tcnt ? ", " : ""),
4692 				 control_values_input[idx]);
4693 		tcnt += ccnt;
4694 	}
4695 	return tcnt;
4696 }
4697 
4698 
pvr2_pathway_state_name(int id)4699 static const char *pvr2_pathway_state_name(int id)
4700 {
4701 	switch (id) {
4702 	case PVR2_PATHWAY_ANALOG: return "analog";
4703 	case PVR2_PATHWAY_DIGITAL: return "digital";
4704 	default: return "unknown";
4705 	}
4706 }
4707 
4708 
pvr2_hdw_report_unlocked(struct pvr2_hdw * hdw,int which,char * buf,unsigned int acnt)4709 static unsigned int pvr2_hdw_report_unlocked(struct pvr2_hdw *hdw,int which,
4710 					     char *buf,unsigned int acnt)
4711 {
4712 	switch (which) {
4713 	case 0:
4714 		return scnprintf(
4715 			buf,acnt,
4716 			"driver:%s%s%s%s%s <mode=%s>",
4717 			(hdw->flag_ok ? " <ok>" : " <fail>"),
4718 			(hdw->flag_init_ok ? " <init>" : " <uninitialized>"),
4719 			(hdw->flag_disconnected ? " <disconnected>" :
4720 			 " <connected>"),
4721 			(hdw->flag_tripped ? " <tripped>" : ""),
4722 			(hdw->flag_decoder_missed ? " <no decoder>" : ""),
4723 			pvr2_pathway_state_name(hdw->pathway_state));
4724 
4725 	case 1:
4726 		return scnprintf(
4727 			buf,acnt,
4728 			"pipeline:%s%s%s%s",
4729 			(hdw->state_pipeline_idle ? " <idle>" : ""),
4730 			(hdw->state_pipeline_config ?
4731 			 " <configok>" : " <stale>"),
4732 			(hdw->state_pipeline_req ? " <req>" : ""),
4733 			(hdw->state_pipeline_pause ? " <pause>" : ""));
4734 	case 2:
4735 		return scnprintf(
4736 			buf,acnt,
4737 			"worker:%s%s%s%s%s%s%s",
4738 			(hdw->state_decoder_run ?
4739 			 (hdw->state_decoder_ready ?
4740 			  "<decode:run>" : " <decode:start>") :
4741 			 (hdw->state_decoder_quiescent ?
4742 			  "" : " <decode:stop>")),
4743 			(hdw->state_decoder_quiescent ?
4744 			 " <decode:quiescent>" : ""),
4745 			(hdw->state_encoder_ok ?
4746 			 "" : " <encode:init>"),
4747 			(hdw->state_encoder_run ?
4748 			 (hdw->state_encoder_runok ?
4749 			  " <encode:run>" :
4750 			  " <encode:firstrun>") :
4751 			 (hdw->state_encoder_runok ?
4752 			  " <encode:stop>" :
4753 			  " <encode:virgin>")),
4754 			(hdw->state_encoder_config ?
4755 			 " <encode:configok>" :
4756 			 (hdw->state_encoder_waitok ?
4757 			  "" : " <encode:waitok>")),
4758 			(hdw->state_usbstream_run ?
4759 			 " <usb:run>" : " <usb:stop>"),
4760 			(hdw->state_pathway_ok ?
4761 			 " <pathway:ok>" : ""));
4762 	case 3:
4763 		return scnprintf(
4764 			buf,acnt,
4765 			"state: %s",
4766 			pvr2_get_state_name(hdw->master_state));
4767 	case 4: {
4768 		unsigned int tcnt = 0;
4769 		unsigned int ccnt;
4770 
4771 		ccnt = scnprintf(buf,
4772 				 acnt,
4773 				 "Hardware supported inputs: ");
4774 		tcnt += ccnt;
4775 		tcnt += print_input_mask(hdw->input_avail_mask,
4776 					 buf+tcnt,
4777 					 acnt-tcnt);
4778 		if (hdw->input_avail_mask != hdw->input_allowed_mask) {
4779 			ccnt = scnprintf(buf+tcnt,
4780 					 acnt-tcnt,
4781 					 "; allowed inputs: ");
4782 			tcnt += ccnt;
4783 			tcnt += print_input_mask(hdw->input_allowed_mask,
4784 						 buf+tcnt,
4785 						 acnt-tcnt);
4786 		}
4787 		return tcnt;
4788 	}
4789 	case 5: {
4790 		struct pvr2_stream_stats stats;
4791 		if (!hdw->vid_stream) break;
4792 		pvr2_stream_get_stats(hdw->vid_stream,
4793 				      &stats,
4794 				      0);
4795 		return scnprintf(
4796 			buf,acnt,
4797 			"Bytes streamed=%u URBs: queued=%u idle=%u ready=%u processed=%u failed=%u",
4798 			stats.bytes_processed,
4799 			stats.buffers_in_queue,
4800 			stats.buffers_in_idle,
4801 			stats.buffers_in_ready,
4802 			stats.buffers_processed,
4803 			stats.buffers_failed);
4804 	}
4805 	case 6: {
4806 		unsigned int id = hdw->ir_scheme_active;
4807 		return scnprintf(buf, acnt, "ir scheme: id=%d %s", id,
4808 				 (id >= ARRAY_SIZE(ir_scheme_names) ?
4809 				  "?" : ir_scheme_names[id]));
4810 	}
4811 	default: break;
4812 	}
4813 	return 0;
4814 }
4815 
4816 
4817 /* Generate report containing info about attached sub-devices and attached
4818    i2c clients, including an indication of which attached i2c clients are
4819    actually sub-devices. */
pvr2_hdw_report_clients(struct pvr2_hdw * hdw,char * buf,unsigned int acnt)4820 static unsigned int pvr2_hdw_report_clients(struct pvr2_hdw *hdw,
4821 					    char *buf, unsigned int acnt)
4822 {
4823 	struct v4l2_subdev *sd;
4824 	unsigned int tcnt = 0;
4825 	unsigned int ccnt;
4826 	struct i2c_client *client;
4827 	const char *p;
4828 	unsigned int id;
4829 
4830 	ccnt = scnprintf(buf, acnt, "Associated v4l2-subdev drivers and I2C clients:\n");
4831 	tcnt += ccnt;
4832 	v4l2_device_for_each_subdev(sd, &hdw->v4l2_dev) {
4833 		id = sd->grp_id;
4834 		p = NULL;
4835 		if (id < ARRAY_SIZE(module_names)) p = module_names[id];
4836 		if (p) {
4837 			ccnt = scnprintf(buf + tcnt, acnt - tcnt, "  %s:", p);
4838 			tcnt += ccnt;
4839 		} else {
4840 			ccnt = scnprintf(buf + tcnt, acnt - tcnt,
4841 					 "  (unknown id=%u):", id);
4842 			tcnt += ccnt;
4843 		}
4844 		client = v4l2_get_subdevdata(sd);
4845 		if (client) {
4846 			ccnt = scnprintf(buf + tcnt, acnt - tcnt,
4847 					 " %s @ %02x\n", client->name,
4848 					 client->addr);
4849 			tcnt += ccnt;
4850 		} else {
4851 			ccnt = scnprintf(buf + tcnt, acnt - tcnt,
4852 					 " no i2c client\n");
4853 			tcnt += ccnt;
4854 		}
4855 	}
4856 	return tcnt;
4857 }
4858 
4859 
pvr2_hdw_state_report(struct pvr2_hdw * hdw,char * buf,unsigned int acnt)4860 unsigned int pvr2_hdw_state_report(struct pvr2_hdw *hdw,
4861 				   char *buf,unsigned int acnt)
4862 {
4863 	unsigned int bcnt,ccnt,idx;
4864 	bcnt = 0;
4865 	LOCK_TAKE(hdw->big_lock);
4866 	for (idx = 0; ; idx++) {
4867 		ccnt = pvr2_hdw_report_unlocked(hdw,idx,buf,acnt);
4868 		if (!ccnt) break;
4869 		bcnt += ccnt; acnt -= ccnt; buf += ccnt;
4870 		if (!acnt) break;
4871 		buf[0] = '\n'; ccnt = 1;
4872 		bcnt += ccnt; acnt -= ccnt; buf += ccnt;
4873 	}
4874 	ccnt = pvr2_hdw_report_clients(hdw, buf, acnt);
4875 	bcnt += ccnt; acnt -= ccnt; buf += ccnt;
4876 	LOCK_GIVE(hdw->big_lock);
4877 	return bcnt;
4878 }
4879 
4880 
pvr2_hdw_state_log_state(struct pvr2_hdw * hdw)4881 static void pvr2_hdw_state_log_state(struct pvr2_hdw *hdw)
4882 {
4883 	char buf[256];
4884 	unsigned int idx, ccnt;
4885 	unsigned int lcnt, ucnt;
4886 
4887 	for (idx = 0; ; idx++) {
4888 		ccnt = pvr2_hdw_report_unlocked(hdw,idx,buf,sizeof(buf));
4889 		if (!ccnt) break;
4890 		pr_info("%s %.*s\n", hdw->name, ccnt, buf);
4891 	}
4892 	ccnt = pvr2_hdw_report_clients(hdw, buf, sizeof(buf));
4893 	if (ccnt >= sizeof(buf))
4894 		ccnt = sizeof(buf);
4895 
4896 	ucnt = 0;
4897 	while (ucnt < ccnt) {
4898 		lcnt = 0;
4899 		while ((lcnt + ucnt < ccnt) && (buf[lcnt + ucnt] != '\n')) {
4900 			lcnt++;
4901 		}
4902 		pr_info("%s %.*s\n", hdw->name, lcnt, buf + ucnt);
4903 		ucnt += lcnt + 1;
4904 	}
4905 }
4906 
4907 
4908 /* Evaluate and update the driver's current state, taking various actions
4909    as appropriate for the update. */
pvr2_hdw_state_eval(struct pvr2_hdw * hdw)4910 static int pvr2_hdw_state_eval(struct pvr2_hdw *hdw)
4911 {
4912 	unsigned int st;
4913 	int state_updated = 0;
4914 	int callback_flag = 0;
4915 	int analog_mode;
4916 
4917 	pvr2_trace(PVR2_TRACE_STBITS,
4918 		   "Drive state check START");
4919 	if (pvrusb2_debug & PVR2_TRACE_STBITS) {
4920 		pvr2_hdw_state_log_state(hdw);
4921 	}
4922 
4923 	/* Process all state and get back over disposition */
4924 	state_updated = pvr2_hdw_state_update(hdw);
4925 
4926 	analog_mode = (hdw->pathway_state != PVR2_PATHWAY_DIGITAL);
4927 
4928 	/* Update master state based upon all other states. */
4929 	if (!hdw->flag_ok) {
4930 		st = PVR2_STATE_DEAD;
4931 	} else if (hdw->fw1_state != FW1_STATE_OK) {
4932 		st = PVR2_STATE_COLD;
4933 	} else if ((analog_mode ||
4934 		    hdw->hdw_desc->flag_digital_requires_cx23416) &&
4935 		   !hdw->state_encoder_ok) {
4936 		st = PVR2_STATE_WARM;
4937 	} else if (hdw->flag_tripped ||
4938 		   (analog_mode && hdw->flag_decoder_missed)) {
4939 		st = PVR2_STATE_ERROR;
4940 	} else if (hdw->state_usbstream_run &&
4941 		   (!analog_mode ||
4942 		    (hdw->state_encoder_run && hdw->state_decoder_run))) {
4943 		st = PVR2_STATE_RUN;
4944 	} else {
4945 		st = PVR2_STATE_READY;
4946 	}
4947 	if (hdw->master_state != st) {
4948 		pvr2_trace(PVR2_TRACE_STATE,
4949 			   "Device state change from %s to %s",
4950 			   pvr2_get_state_name(hdw->master_state),
4951 			   pvr2_get_state_name(st));
4952 		pvr2_led_ctrl(hdw,st == PVR2_STATE_RUN);
4953 		hdw->master_state = st;
4954 		state_updated = !0;
4955 		callback_flag = !0;
4956 	}
4957 	if (state_updated) {
4958 		/* Trigger anyone waiting on any state changes here. */
4959 		wake_up(&hdw->state_wait_data);
4960 	}
4961 
4962 	if (pvrusb2_debug & PVR2_TRACE_STBITS) {
4963 		pvr2_hdw_state_log_state(hdw);
4964 	}
4965 	pvr2_trace(PVR2_TRACE_STBITS,
4966 		   "Drive state check DONE callback=%d",callback_flag);
4967 
4968 	return callback_flag;
4969 }
4970 
4971 
4972 /* Cause kernel thread to check / update driver state */
pvr2_hdw_state_sched(struct pvr2_hdw * hdw)4973 static void pvr2_hdw_state_sched(struct pvr2_hdw *hdw)
4974 {
4975 	if (hdw->state_stale) return;
4976 	hdw->state_stale = !0;
4977 	trace_stbit("state_stale",hdw->state_stale);
4978 	schedule_work(&hdw->workpoll);
4979 }
4980 
4981 
pvr2_hdw_gpio_get_dir(struct pvr2_hdw * hdw,u32 * dp)4982 int pvr2_hdw_gpio_get_dir(struct pvr2_hdw *hdw,u32 *dp)
4983 {
4984 	return pvr2_read_register(hdw,PVR2_GPIO_DIR,dp);
4985 }
4986 
4987 
pvr2_hdw_gpio_get_out(struct pvr2_hdw * hdw,u32 * dp)4988 int pvr2_hdw_gpio_get_out(struct pvr2_hdw *hdw,u32 *dp)
4989 {
4990 	return pvr2_read_register(hdw,PVR2_GPIO_OUT,dp);
4991 }
4992 
4993 
pvr2_hdw_gpio_get_in(struct pvr2_hdw * hdw,u32 * dp)4994 int pvr2_hdw_gpio_get_in(struct pvr2_hdw *hdw,u32 *dp)
4995 {
4996 	return pvr2_read_register(hdw,PVR2_GPIO_IN,dp);
4997 }
4998 
4999 
pvr2_hdw_gpio_chg_dir(struct pvr2_hdw * hdw,u32 msk,u32 val)5000 int pvr2_hdw_gpio_chg_dir(struct pvr2_hdw *hdw,u32 msk,u32 val)
5001 {
5002 	u32 cval,nval;
5003 	int ret;
5004 	if (~msk) {
5005 		ret = pvr2_read_register(hdw,PVR2_GPIO_DIR,&cval);
5006 		if (ret) return ret;
5007 		nval = (cval & ~msk) | (val & msk);
5008 		pvr2_trace(PVR2_TRACE_GPIO,
5009 			   "GPIO direction changing 0x%x:0x%x from 0x%x to 0x%x",
5010 			   msk,val,cval,nval);
5011 	} else {
5012 		nval = val;
5013 		pvr2_trace(PVR2_TRACE_GPIO,
5014 			   "GPIO direction changing to 0x%x",nval);
5015 	}
5016 	return pvr2_write_register(hdw,PVR2_GPIO_DIR,nval);
5017 }
5018 
5019 
pvr2_hdw_gpio_chg_out(struct pvr2_hdw * hdw,u32 msk,u32 val)5020 int pvr2_hdw_gpio_chg_out(struct pvr2_hdw *hdw,u32 msk,u32 val)
5021 {
5022 	u32 cval,nval;
5023 	int ret;
5024 	if (~msk) {
5025 		ret = pvr2_read_register(hdw,PVR2_GPIO_OUT,&cval);
5026 		if (ret) return ret;
5027 		nval = (cval & ~msk) | (val & msk);
5028 		pvr2_trace(PVR2_TRACE_GPIO,
5029 			   "GPIO output changing 0x%x:0x%x from 0x%x to 0x%x",
5030 			   msk,val,cval,nval);
5031 	} else {
5032 		nval = val;
5033 		pvr2_trace(PVR2_TRACE_GPIO,
5034 			   "GPIO output changing to 0x%x",nval);
5035 	}
5036 	return pvr2_write_register(hdw,PVR2_GPIO_OUT,nval);
5037 }
5038 
5039 
pvr2_hdw_status_poll(struct pvr2_hdw * hdw)5040 void pvr2_hdw_status_poll(struct pvr2_hdw *hdw)
5041 {
5042 	struct v4l2_tuner *vtp = &hdw->tuner_signal_info;
5043 	memset(vtp, 0, sizeof(*vtp));
5044 	vtp->type = (hdw->input_val == PVR2_CVAL_INPUT_RADIO) ?
5045 		V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV;
5046 	hdw->tuner_signal_stale = 0;
5047 	/* Note: There apparently is no replacement for VIDIOC_CROPCAP
5048 	   using v4l2-subdev - therefore we can't support that AT ALL right
5049 	   now.  (Of course, no sub-drivers seem to implement it either.
5050 	   But now it's a chicken and egg problem...) */
5051 	v4l2_device_call_all(&hdw->v4l2_dev, 0, tuner, g_tuner, vtp);
5052 	pvr2_trace(PVR2_TRACE_CHIPS, "subdev status poll type=%u strength=%u audio=0x%x cap=0x%x low=%u hi=%u",
5053 		   vtp->type,
5054 		   vtp->signal, vtp->rxsubchans, vtp->capability,
5055 		   vtp->rangelow, vtp->rangehigh);
5056 
5057 	/* We have to do this to avoid getting into constant polling if
5058 	   there's nobody to answer a poll of cropcap info. */
5059 	hdw->cropcap_stale = 0;
5060 }
5061 
5062 
pvr2_hdw_get_input_available(struct pvr2_hdw * hdw)5063 unsigned int pvr2_hdw_get_input_available(struct pvr2_hdw *hdw)
5064 {
5065 	return hdw->input_avail_mask;
5066 }
5067 
5068 
pvr2_hdw_get_input_allowed(struct pvr2_hdw * hdw)5069 unsigned int pvr2_hdw_get_input_allowed(struct pvr2_hdw *hdw)
5070 {
5071 	return hdw->input_allowed_mask;
5072 }
5073 
5074 
pvr2_hdw_set_input(struct pvr2_hdw * hdw,int v)5075 static int pvr2_hdw_set_input(struct pvr2_hdw *hdw,int v)
5076 {
5077 	if (hdw->input_val != v) {
5078 		hdw->input_val = v;
5079 		hdw->input_dirty = !0;
5080 	}
5081 
5082 	/* Handle side effects - if we switch to a mode that needs the RF
5083 	   tuner, then select the right frequency choice as well and mark
5084 	   it dirty. */
5085 	if (hdw->input_val == PVR2_CVAL_INPUT_RADIO) {
5086 		hdw->freqSelector = 0;
5087 		hdw->freqDirty = !0;
5088 	} else if ((hdw->input_val == PVR2_CVAL_INPUT_TV) ||
5089 		   (hdw->input_val == PVR2_CVAL_INPUT_DTV)) {
5090 		hdw->freqSelector = 1;
5091 		hdw->freqDirty = !0;
5092 	}
5093 	return 0;
5094 }
5095 
5096 
pvr2_hdw_set_input_allowed(struct pvr2_hdw * hdw,unsigned int change_mask,unsigned int change_val)5097 int pvr2_hdw_set_input_allowed(struct pvr2_hdw *hdw,
5098 			       unsigned int change_mask,
5099 			       unsigned int change_val)
5100 {
5101 	int ret = 0;
5102 	unsigned int nv,m,idx;
5103 	LOCK_TAKE(hdw->big_lock);
5104 	do {
5105 		nv = hdw->input_allowed_mask & ~change_mask;
5106 		nv |= (change_val & change_mask);
5107 		nv &= hdw->input_avail_mask;
5108 		if (!nv) {
5109 			/* No legal modes left; return error instead. */
5110 			ret = -EPERM;
5111 			break;
5112 		}
5113 		hdw->input_allowed_mask = nv;
5114 		if ((1UL << hdw->input_val) & hdw->input_allowed_mask) {
5115 			/* Current mode is still in the allowed mask, so
5116 			   we're done. */
5117 			break;
5118 		}
5119 		/* Select and switch to a mode that is still in the allowed
5120 		   mask */
5121 		if (!hdw->input_allowed_mask) {
5122 			/* Nothing legal; give up */
5123 			break;
5124 		}
5125 		m = hdw->input_allowed_mask;
5126 		for (idx = 0; idx < (sizeof(m) << 3); idx++) {
5127 			if (!((1UL << idx) & m)) continue;
5128 			pvr2_hdw_set_input(hdw,idx);
5129 			break;
5130 		}
5131 	} while (0);
5132 	LOCK_GIVE(hdw->big_lock);
5133 	return ret;
5134 }
5135 
5136 
5137 /* Find I2C address of eeprom */
pvr2_hdw_get_eeprom_addr(struct pvr2_hdw * hdw)5138 static int pvr2_hdw_get_eeprom_addr(struct pvr2_hdw *hdw)
5139 {
5140 	int result;
5141 	LOCK_TAKE(hdw->ctl_lock); do {
5142 		hdw->cmd_buffer[0] = FX2CMD_GET_EEPROM_ADDR;
5143 		result = pvr2_send_request(hdw,
5144 					   hdw->cmd_buffer,1,
5145 					   hdw->cmd_buffer,1);
5146 		if (result < 0) break;
5147 		result = hdw->cmd_buffer[0];
5148 	} while(0); LOCK_GIVE(hdw->ctl_lock);
5149 	return result;
5150 }
5151