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