]> Pileus Git - ~andy/linux/blob - drivers/media/video/pvrusb2/pvrusb2-hdw.c
V4L/DVB (5050): Pvrusb2: Newer frequency range checking
[~andy/linux] / drivers / media / video / pvrusb2 / pvrusb2-hdw.c
1 /*
2  *
3  *  $Id$
4  *
5  *  Copyright (C) 2005 Mike Isely <isely@pobox.com>
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  */
21
22 #include <linux/errno.h>
23 #include <linux/string.h>
24 #include <linux/slab.h>
25 #include <linux/firmware.h>
26 #include <linux/videodev2.h>
27 #include <media/v4l2-common.h>
28 #include <asm/semaphore.h>
29 #include "pvrusb2.h"
30 #include "pvrusb2-std.h"
31 #include "pvrusb2-util.h"
32 #include "pvrusb2-hdw.h"
33 #include "pvrusb2-i2c-core.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
40 #define TV_MIN_FREQ 55250000L
41 #define TV_MAX_FREQ 850000000L
42
43 #define RADIO_MIN_FREQ 87000000L
44 #define RADIO_MAX_FREQ 108000000L
45
46 struct usb_device_id pvr2_device_table[] = {
47         [PVR2_HDW_TYPE_29XXX] = { USB_DEVICE(0x2040, 0x2900) },
48         [PVR2_HDW_TYPE_24XXX] = { USB_DEVICE(0x2040, 0x2400) },
49         { }
50 };
51
52 MODULE_DEVICE_TABLE(usb, pvr2_device_table);
53
54 static const char *pvr2_device_names[] = {
55         [PVR2_HDW_TYPE_29XXX] = "WinTV PVR USB2 Model Category 29xxxx",
56         [PVR2_HDW_TYPE_24XXX] = "WinTV PVR USB2 Model Category 24xxxx",
57 };
58
59 struct pvr2_string_table {
60         const char **lst;
61         unsigned int cnt;
62 };
63
64 // Names of other client modules to request for 24xxx model hardware
65 static const char *pvr2_client_24xxx[] = {
66         "cx25840",
67         "tuner",
68         "wm8775",
69 };
70
71 // Names of other client modules to request for 29xxx model hardware
72 static const char *pvr2_client_29xxx[] = {
73         "msp3400",
74         "saa7115",
75         "tuner",
76 };
77
78 static struct pvr2_string_table pvr2_client_lists[] = {
79         [PVR2_HDW_TYPE_29XXX] = {
80                 pvr2_client_29xxx,
81                 sizeof(pvr2_client_29xxx)/sizeof(pvr2_client_29xxx[0]),
82         },
83         [PVR2_HDW_TYPE_24XXX] = {
84                 pvr2_client_24xxx,
85                 sizeof(pvr2_client_24xxx)/sizeof(pvr2_client_24xxx[0]),
86         },
87 };
88
89 static struct pvr2_hdw *unit_pointers[PVR_NUM] = {[ 0 ... PVR_NUM-1 ] = NULL};
90 static DECLARE_MUTEX(pvr2_unit_sem);
91
92 static int ctlchg = 0;
93 static int initusbreset = 1;
94 static int procreload = 0;
95 static int tuner[PVR_NUM] = { [0 ... PVR_NUM-1] = -1 };
96 static int tolerance[PVR_NUM] = { [0 ... PVR_NUM-1] = 0 };
97 static int video_std[PVR_NUM] = { [0 ... PVR_NUM-1] = 0 };
98 static int init_pause_msec = 0;
99
100 module_param(ctlchg, int, S_IRUGO|S_IWUSR);
101 MODULE_PARM_DESC(ctlchg, "0=optimize ctl change 1=always accept new ctl value");
102 module_param(init_pause_msec, int, S_IRUGO|S_IWUSR);
103 MODULE_PARM_DESC(init_pause_msec, "hardware initialization settling delay");
104 module_param(initusbreset, int, S_IRUGO|S_IWUSR);
105 MODULE_PARM_DESC(initusbreset, "Do USB reset device on probe");
106 module_param(procreload, int, S_IRUGO|S_IWUSR);
107 MODULE_PARM_DESC(procreload,
108                  "Attempt init failure recovery with firmware reload");
109 module_param_array(tuner,    int, NULL, 0444);
110 MODULE_PARM_DESC(tuner,"specify installed tuner type");
111 module_param_array(video_std,    int, NULL, 0444);
112 MODULE_PARM_DESC(video_std,"specify initial video standard");
113 module_param_array(tolerance,    int, NULL, 0444);
114 MODULE_PARM_DESC(tolerance,"specify stream error tolerance");
115
116 #define PVR2_CTL_WRITE_ENDPOINT  0x01
117 #define PVR2_CTL_READ_ENDPOINT   0x81
118
119 #define PVR2_GPIO_IN 0x9008
120 #define PVR2_GPIO_OUT 0x900c
121 #define PVR2_GPIO_DIR 0x9020
122
123 #define trace_firmware(...) pvr2_trace(PVR2_TRACE_FIRMWARE,__VA_ARGS__)
124
125 #define PVR2_FIRMWARE_ENDPOINT   0x02
126
127 /* size of a firmware chunk */
128 #define FIRMWARE_CHUNK_SIZE 0x2000
129
130 /* Define the list of additional controls we'll dynamically construct based
131    on query of the cx2341x module. */
132 struct pvr2_mpeg_ids {
133         const char *strid;
134         int id;
135 };
136 static const struct pvr2_mpeg_ids mpeg_ids[] = {
137         {
138                 .strid = "audio_layer",
139                 .id = V4L2_CID_MPEG_AUDIO_ENCODING,
140         },{
141                 .strid = "audio_bitrate",
142                 .id = V4L2_CID_MPEG_AUDIO_L2_BITRATE,
143         },{
144                 /* Already using audio_mode elsewhere :-( */
145                 .strid = "mpeg_audio_mode",
146                 .id = V4L2_CID_MPEG_AUDIO_MODE,
147         },{
148                 .strid = "mpeg_audio_mode_extension",
149                 .id = V4L2_CID_MPEG_AUDIO_MODE_EXTENSION,
150         },{
151                 .strid = "audio_emphasis",
152                 .id = V4L2_CID_MPEG_AUDIO_EMPHASIS,
153         },{
154                 .strid = "audio_crc",
155                 .id = V4L2_CID_MPEG_AUDIO_CRC,
156         },{
157                 .strid = "video_aspect",
158                 .id = V4L2_CID_MPEG_VIDEO_ASPECT,
159         },{
160                 .strid = "video_b_frames",
161                 .id = V4L2_CID_MPEG_VIDEO_B_FRAMES,
162         },{
163                 .strid = "video_gop_size",
164                 .id = V4L2_CID_MPEG_VIDEO_GOP_SIZE,
165         },{
166                 .strid = "video_gop_closure",
167                 .id = V4L2_CID_MPEG_VIDEO_GOP_CLOSURE,
168         },{
169                 .strid = "video_bitrate_mode",
170                 .id = V4L2_CID_MPEG_VIDEO_BITRATE_MODE,
171         },{
172                 .strid = "video_bitrate",
173                 .id = V4L2_CID_MPEG_VIDEO_BITRATE,
174         },{
175                 .strid = "video_bitrate_peak",
176                 .id = V4L2_CID_MPEG_VIDEO_BITRATE_PEAK,
177         },{
178                 .strid = "video_temporal_decimation",
179                 .id = V4L2_CID_MPEG_VIDEO_TEMPORAL_DECIMATION,
180         },{
181                 .strid = "stream_type",
182                 .id = V4L2_CID_MPEG_STREAM_TYPE,
183         },{
184                 .strid = "video_spatial_filter_mode",
185                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE,
186         },{
187                 .strid = "video_spatial_filter",
188                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER,
189         },{
190                 .strid = "video_luma_spatial_filter_type",
191                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE,
192         },{
193                 .strid = "video_chroma_spatial_filter_type",
194                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE,
195         },{
196                 .strid = "video_temporal_filter_mode",
197                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE,
198         },{
199                 .strid = "video_temporal_filter",
200                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER,
201         },{
202                 .strid = "video_median_filter_type",
203                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE,
204         },{
205                 .strid = "video_luma_median_filter_top",
206                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_TOP,
207         },{
208                 .strid = "video_luma_median_filter_bottom",
209                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_BOTTOM,
210         },{
211                 .strid = "video_chroma_median_filter_top",
212                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_TOP,
213         },{
214                 .strid = "video_chroma_median_filter_bottom",
215                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_BOTTOM,
216         }
217 };
218 #define MPEGDEF_COUNT (sizeof(mpeg_ids)/sizeof(mpeg_ids[0]))
219
220
221 static const char *control_values_srate[] = {
222         [V4L2_MPEG_AUDIO_SAMPLING_FREQ_44100]   = "44.1 kHz",
223         [V4L2_MPEG_AUDIO_SAMPLING_FREQ_48000]   = "48 kHz",
224         [V4L2_MPEG_AUDIO_SAMPLING_FREQ_32000]   = "32 kHz",
225 };
226
227
228
229 static const char *control_values_input[] = {
230         [PVR2_CVAL_INPUT_TV]        = "television",  /*xawtv needs this name*/
231         [PVR2_CVAL_INPUT_RADIO]     = "radio",
232         [PVR2_CVAL_INPUT_SVIDEO]    = "s-video",
233         [PVR2_CVAL_INPUT_COMPOSITE] = "composite",
234 };
235
236
237 static const char *control_values_audiomode[] = {
238         [V4L2_TUNER_MODE_MONO]   = "Mono",
239         [V4L2_TUNER_MODE_STEREO] = "Stereo",
240         [V4L2_TUNER_MODE_LANG1]  = "Lang1",
241         [V4L2_TUNER_MODE_LANG2]  = "Lang2",
242         [V4L2_TUNER_MODE_LANG1_LANG2] = "Lang1+Lang2",
243 };
244
245
246 static const char *control_values_hsm[] = {
247         [PVR2_CVAL_HSM_FAIL] = "Fail",
248         [PVR2_CVAL_HSM_HIGH] = "High",
249         [PVR2_CVAL_HSM_FULL] = "Full",
250 };
251
252
253 static const char *control_values_subsystem[] = {
254         [PVR2_SUBSYS_B_ENC_FIRMWARE]  = "enc_firmware",
255         [PVR2_SUBSYS_B_ENC_CFG] = "enc_config",
256         [PVR2_SUBSYS_B_DIGITIZER_RUN] = "digitizer_run",
257         [PVR2_SUBSYS_B_USBSTREAM_RUN] = "usbstream_run",
258         [PVR2_SUBSYS_B_ENC_RUN] = "enc_run",
259 };
260
261 static int pvr2_hdw_cmd_usbstream(struct pvr2_hdw *hdw,int runFl);
262 static int pvr2_hdw_commit_ctl_internal(struct pvr2_hdw *hdw);
263 static int pvr2_hdw_get_eeprom_addr(struct pvr2_hdw *hdw);
264 static unsigned int pvr2_hdw_get_signal_status_internal(struct pvr2_hdw *hdw);
265 static void pvr2_hdw_internal_find_stdenum(struct pvr2_hdw *hdw);
266 static void pvr2_hdw_internal_set_std_avail(struct pvr2_hdw *hdw);
267 static void pvr2_hdw_render_useless_unlocked(struct pvr2_hdw *hdw);
268 static void pvr2_hdw_subsys_bit_chg_no_lock(struct pvr2_hdw *hdw,
269                                             unsigned long msk,
270                                             unsigned long val);
271 static void pvr2_hdw_subsys_stream_bit_chg_no_lock(struct pvr2_hdw *hdw,
272                                                    unsigned long msk,
273                                                    unsigned long val);
274 static int pvr2_send_request_ex(struct pvr2_hdw *hdw,
275                                 unsigned int timeout,int probe_fl,
276                                 void *write_data,unsigned int write_len,
277                                 void *read_data,unsigned int read_len);
278 static int pvr2_write_u16(struct pvr2_hdw *hdw, u16 data, int res);
279 static int pvr2_write_u8(struct pvr2_hdw *hdw, u8 data, int res);
280
281 static int ctrl_channelfreq_get(struct pvr2_ctrl *cptr,int *vp)
282 {
283         struct pvr2_hdw *hdw = cptr->hdw;
284         if ((hdw->freqProgSlot > 0) && (hdw->freqProgSlot <= FREQTABLE_SIZE)) {
285                 *vp = hdw->freqTable[hdw->freqProgSlot-1];
286         } else {
287                 *vp = 0;
288         }
289         return 0;
290 }
291
292 static int ctrl_channelfreq_set(struct pvr2_ctrl *cptr,int m,int v)
293 {
294         struct pvr2_hdw *hdw = cptr->hdw;
295         if ((hdw->freqProgSlot > 0) && (hdw->freqProgSlot <= FREQTABLE_SIZE)) {
296                 hdw->freqTable[hdw->freqProgSlot-1] = v;
297         }
298         return 0;
299 }
300
301 static int ctrl_channelprog_get(struct pvr2_ctrl *cptr,int *vp)
302 {
303         *vp = cptr->hdw->freqProgSlot;
304         return 0;
305 }
306
307 static int ctrl_channelprog_set(struct pvr2_ctrl *cptr,int m,int v)
308 {
309         struct pvr2_hdw *hdw = cptr->hdw;
310         if ((v >= 0) && (v <= FREQTABLE_SIZE)) {
311                 hdw->freqProgSlot = v;
312         }
313         return 0;
314 }
315
316 static int ctrl_channel_get(struct pvr2_ctrl *cptr,int *vp)
317 {
318         *vp = cptr->hdw->freqSlot;
319         return 0;
320 }
321
322 static int ctrl_channel_set(struct pvr2_ctrl *cptr,int m,int v)
323 {
324         unsigned freq = 0;
325         struct pvr2_hdw *hdw = cptr->hdw;
326         hdw->freqSlot = v;
327         if ((hdw->freqSlot > 0) && (hdw->freqSlot <= FREQTABLE_SIZE)) {
328                 freq = hdw->freqTable[hdw->freqSlot-1];
329         }
330         if (freq && (freq != hdw->freqVal)) {
331                 hdw->freqVal = freq;
332                 hdw->freqDirty = !0;
333         }
334         return 0;
335 }
336
337 static int ctrl_freq_get(struct pvr2_ctrl *cptr,int *vp)
338 {
339         *vp = cptr->hdw->freqVal;
340         return 0;
341 }
342
343 static int ctrl_freq_is_dirty(struct pvr2_ctrl *cptr)
344 {
345         return cptr->hdw->freqDirty != 0;
346 }
347
348 static void ctrl_freq_clear_dirty(struct pvr2_ctrl *cptr)
349 {
350         cptr->hdw->freqDirty = 0;
351 }
352
353 static int ctrl_freq_set(struct pvr2_ctrl *cptr,int m,int v)
354 {
355         struct pvr2_hdw *hdw = cptr->hdw;
356         hdw->freqVal = v;
357         hdw->freqDirty = !0;
358         hdw->freqSlot = 0;
359         return 0;
360 }
361
362 static int ctrl_vres_max_get(struct pvr2_ctrl *cptr,int *vp)
363 {
364         /* Actual maximum depends on the video standard in effect. */
365         if (cptr->hdw->std_mask_cur & V4L2_STD_525_60) {
366                 *vp = 480;
367         } else {
368                 *vp = 576;
369         }
370         return 0;
371 }
372
373 static int ctrl_vres_min_get(struct pvr2_ctrl *cptr,int *vp)
374 {
375         /* Actual minimum depends on device type. */
376         if (cptr->hdw->hdw_type == PVR2_HDW_TYPE_24XXX) {
377                 *vp = 75;
378         } else {
379                 *vp = 17;
380         }
381         return 0;
382 }
383
384 static int ctrl_freq_check(struct pvr2_ctrl *cptr,int v)
385 {
386         if (cptr->hdw->input_val == PVR2_CVAL_INPUT_RADIO) {
387                 return ((v >= RADIO_MIN_FREQ) && (v <= RADIO_MAX_FREQ));
388         } else {
389                 return ((v >= TV_MIN_FREQ) && (v <= TV_MAX_FREQ));
390         }
391 }
392
393 static int ctrl_freq_max_get(struct pvr2_ctrl *cptr, int *vp)
394 {
395         /* Actual maximum depends on radio/tv mode */
396         if (cptr->hdw->input_val == PVR2_CVAL_INPUT_RADIO) {
397                 *vp = RADIO_MAX_FREQ;
398         } else {
399                 *vp = TV_MAX_FREQ;
400         }
401         return 0;
402 }
403
404 static int ctrl_freq_min_get(struct pvr2_ctrl *cptr, int *vp)
405 {
406         /* Actual minimum depends on radio/tv mode */
407         if (cptr->hdw->input_val == PVR2_CVAL_INPUT_RADIO) {
408                 *vp = RADIO_MIN_FREQ;
409         } else {
410                 *vp = TV_MIN_FREQ;
411         }
412         return 0;
413 }
414
415 static int ctrl_cx2341x_is_dirty(struct pvr2_ctrl *cptr)
416 {
417         return cptr->hdw->enc_stale != 0;
418 }
419
420 static void ctrl_cx2341x_clear_dirty(struct pvr2_ctrl *cptr)
421 {
422         cptr->hdw->enc_stale = 0;
423 }
424
425 static int ctrl_cx2341x_get(struct pvr2_ctrl *cptr,int *vp)
426 {
427         int ret;
428         struct v4l2_ext_controls cs;
429         struct v4l2_ext_control c1;
430         memset(&cs,0,sizeof(cs));
431         memset(&c1,0,sizeof(c1));
432         cs.controls = &c1;
433         cs.count = 1;
434         c1.id = cptr->info->v4l_id;
435         ret = cx2341x_ext_ctrls(&cptr->hdw->enc_ctl_state,&cs,
436                                 VIDIOC_G_EXT_CTRLS);
437         if (ret) return ret;
438         *vp = c1.value;
439         return 0;
440 }
441
442 static int ctrl_cx2341x_set(struct pvr2_ctrl *cptr,int m,int v)
443 {
444         int ret;
445         struct v4l2_ext_controls cs;
446         struct v4l2_ext_control c1;
447         memset(&cs,0,sizeof(cs));
448         memset(&c1,0,sizeof(c1));
449         cs.controls = &c1;
450         cs.count = 1;
451         c1.id = cptr->info->v4l_id;
452         c1.value = v;
453         ret = cx2341x_ext_ctrls(&cptr->hdw->enc_ctl_state,&cs,
454                                 VIDIOC_S_EXT_CTRLS);
455         if (ret) return ret;
456         cptr->hdw->enc_stale = !0;
457         return 0;
458 }
459
460 static unsigned int ctrl_cx2341x_getv4lflags(struct pvr2_ctrl *cptr)
461 {
462         struct v4l2_queryctrl qctrl;
463         struct pvr2_ctl_info *info;
464         qctrl.id = cptr->info->v4l_id;
465         cx2341x_ctrl_query(&cptr->hdw->enc_ctl_state,&qctrl);
466         /* Strip out the const so we can adjust a function pointer.  It's
467            OK to do this here because we know this is a dynamically created
468            control, so the underlying storage for the info pointer is (a)
469            private to us, and (b) not in read-only storage.  Either we do
470            this or we significantly complicate the underlying control
471            implementation. */
472         info = (struct pvr2_ctl_info *)(cptr->info);
473         if (qctrl.flags & V4L2_CTRL_FLAG_READ_ONLY) {
474                 if (info->set_value) {
475                         info->set_value = NULL;
476                 }
477         } else {
478                 if (!(info->set_value)) {
479                         info->set_value = ctrl_cx2341x_set;
480                 }
481         }
482         return qctrl.flags;
483 }
484
485 static int ctrl_streamingenabled_get(struct pvr2_ctrl *cptr,int *vp)
486 {
487         *vp = cptr->hdw->flag_streaming_enabled;
488         return 0;
489 }
490
491 static int ctrl_hsm_get(struct pvr2_ctrl *cptr,int *vp)
492 {
493         int result = pvr2_hdw_is_hsm(cptr->hdw);
494         *vp = PVR2_CVAL_HSM_FULL;
495         if (result < 0) *vp = PVR2_CVAL_HSM_FAIL;
496         if (result) *vp = PVR2_CVAL_HSM_HIGH;
497         return 0;
498 }
499
500 static int ctrl_stdavail_get(struct pvr2_ctrl *cptr,int *vp)
501 {
502         *vp = cptr->hdw->std_mask_avail;
503         return 0;
504 }
505
506 static int ctrl_stdavail_set(struct pvr2_ctrl *cptr,int m,int v)
507 {
508         struct pvr2_hdw *hdw = cptr->hdw;
509         v4l2_std_id ns;
510         ns = hdw->std_mask_avail;
511         ns = (ns & ~m) | (v & m);
512         if (ns == hdw->std_mask_avail) return 0;
513         hdw->std_mask_avail = ns;
514         pvr2_hdw_internal_set_std_avail(hdw);
515         pvr2_hdw_internal_find_stdenum(hdw);
516         return 0;
517 }
518
519 static int ctrl_std_val_to_sym(struct pvr2_ctrl *cptr,int msk,int val,
520                                char *bufPtr,unsigned int bufSize,
521                                unsigned int *len)
522 {
523         *len = pvr2_std_id_to_str(bufPtr,bufSize,msk & val);
524         return 0;
525 }
526
527 static int ctrl_std_sym_to_val(struct pvr2_ctrl *cptr,
528                                const char *bufPtr,unsigned int bufSize,
529                                int *mskp,int *valp)
530 {
531         int ret;
532         v4l2_std_id id;
533         ret = pvr2_std_str_to_id(&id,bufPtr,bufSize);
534         if (ret < 0) return ret;
535         if (mskp) *mskp = id;
536         if (valp) *valp = id;
537         return 0;
538 }
539
540 static int ctrl_stdcur_get(struct pvr2_ctrl *cptr,int *vp)
541 {
542         *vp = cptr->hdw->std_mask_cur;
543         return 0;
544 }
545
546 static int ctrl_stdcur_set(struct pvr2_ctrl *cptr,int m,int v)
547 {
548         struct pvr2_hdw *hdw = cptr->hdw;
549         v4l2_std_id ns;
550         ns = hdw->std_mask_cur;
551         ns = (ns & ~m) | (v & m);
552         if (ns == hdw->std_mask_cur) return 0;
553         hdw->std_mask_cur = ns;
554         hdw->std_dirty = !0;
555         pvr2_hdw_internal_find_stdenum(hdw);
556         return 0;
557 }
558
559 static int ctrl_stdcur_is_dirty(struct pvr2_ctrl *cptr)
560 {
561         return cptr->hdw->std_dirty != 0;
562 }
563
564 static void ctrl_stdcur_clear_dirty(struct pvr2_ctrl *cptr)
565 {
566         cptr->hdw->std_dirty = 0;
567 }
568
569 static int ctrl_signal_get(struct pvr2_ctrl *cptr,int *vp)
570 {
571         *vp = ((pvr2_hdw_get_signal_status_internal(cptr->hdw) &
572                 PVR2_SIGNAL_OK) ? 1 : 0);
573         return 0;
574 }
575
576 static int ctrl_subsys_get(struct pvr2_ctrl *cptr,int *vp)
577 {
578         *vp = cptr->hdw->subsys_enabled_mask;
579         return 0;
580 }
581
582 static int ctrl_subsys_set(struct pvr2_ctrl *cptr,int m,int v)
583 {
584         pvr2_hdw_subsys_bit_chg_no_lock(cptr->hdw,m,v);
585         return 0;
586 }
587
588 static int ctrl_subsys_stream_get(struct pvr2_ctrl *cptr,int *vp)
589 {
590         *vp = cptr->hdw->subsys_stream_mask;
591         return 0;
592 }
593
594 static int ctrl_subsys_stream_set(struct pvr2_ctrl *cptr,int m,int v)
595 {
596         pvr2_hdw_subsys_stream_bit_chg_no_lock(cptr->hdw,m,v);
597         return 0;
598 }
599
600 static int ctrl_stdenumcur_set(struct pvr2_ctrl *cptr,int m,int v)
601 {
602         struct pvr2_hdw *hdw = cptr->hdw;
603         if (v < 0) return -EINVAL;
604         if (v > hdw->std_enum_cnt) return -EINVAL;
605         hdw->std_enum_cur = v;
606         if (!v) return 0;
607         v--;
608         if (hdw->std_mask_cur == hdw->std_defs[v].id) return 0;
609         hdw->std_mask_cur = hdw->std_defs[v].id;
610         hdw->std_dirty = !0;
611         return 0;
612 }
613
614
615 static int ctrl_stdenumcur_get(struct pvr2_ctrl *cptr,int *vp)
616 {
617         *vp = cptr->hdw->std_enum_cur;
618         return 0;
619 }
620
621
622 static int ctrl_stdenumcur_is_dirty(struct pvr2_ctrl *cptr)
623 {
624         return cptr->hdw->std_dirty != 0;
625 }
626
627
628 static void ctrl_stdenumcur_clear_dirty(struct pvr2_ctrl *cptr)
629 {
630         cptr->hdw->std_dirty = 0;
631 }
632
633
634 #define DEFINT(vmin,vmax) \
635         .type = pvr2_ctl_int, \
636         .def.type_int.min_value = vmin, \
637         .def.type_int.max_value = vmax
638
639 #define DEFENUM(tab) \
640         .type = pvr2_ctl_enum, \
641         .def.type_enum.count = (sizeof(tab)/sizeof((tab)[0])), \
642         .def.type_enum.value_names = tab
643
644 #define DEFBOOL \
645         .type = pvr2_ctl_bool
646
647 #define DEFMASK(msk,tab) \
648         .type = pvr2_ctl_bitmask, \
649         .def.type_bitmask.valid_bits = msk, \
650         .def.type_bitmask.bit_names = tab
651
652 #define DEFREF(vname) \
653         .set_value = ctrl_set_##vname, \
654         .get_value = ctrl_get_##vname, \
655         .is_dirty = ctrl_isdirty_##vname, \
656         .clear_dirty = ctrl_cleardirty_##vname
657
658
659 #define VCREATE_FUNCS(vname) \
660 static int ctrl_get_##vname(struct pvr2_ctrl *cptr,int *vp) \
661 {*vp = cptr->hdw->vname##_val; return 0;} \
662 static int ctrl_set_##vname(struct pvr2_ctrl *cptr,int m,int v) \
663 {cptr->hdw->vname##_val = v; cptr->hdw->vname##_dirty = !0; return 0;} \
664 static int ctrl_isdirty_##vname(struct pvr2_ctrl *cptr) \
665 {return cptr->hdw->vname##_dirty != 0;} \
666 static void ctrl_cleardirty_##vname(struct pvr2_ctrl *cptr) \
667 {cptr->hdw->vname##_dirty = 0;}
668
669 VCREATE_FUNCS(brightness)
670 VCREATE_FUNCS(contrast)
671 VCREATE_FUNCS(saturation)
672 VCREATE_FUNCS(hue)
673 VCREATE_FUNCS(volume)
674 VCREATE_FUNCS(balance)
675 VCREATE_FUNCS(bass)
676 VCREATE_FUNCS(treble)
677 VCREATE_FUNCS(mute)
678 VCREATE_FUNCS(input)
679 VCREATE_FUNCS(audiomode)
680 VCREATE_FUNCS(res_hor)
681 VCREATE_FUNCS(res_ver)
682 VCREATE_FUNCS(srate)
683
684 /* Table definition of all controls which can be manipulated */
685 static const struct pvr2_ctl_info control_defs[] = {
686         {
687                 .v4l_id = V4L2_CID_BRIGHTNESS,
688                 .desc = "Brightness",
689                 .name = "brightness",
690                 .default_value = 128,
691                 DEFREF(brightness),
692                 DEFINT(0,255),
693         },{
694                 .v4l_id = V4L2_CID_CONTRAST,
695                 .desc = "Contrast",
696                 .name = "contrast",
697                 .default_value = 68,
698                 DEFREF(contrast),
699                 DEFINT(0,127),
700         },{
701                 .v4l_id = V4L2_CID_SATURATION,
702                 .desc = "Saturation",
703                 .name = "saturation",
704                 .default_value = 64,
705                 DEFREF(saturation),
706                 DEFINT(0,127),
707         },{
708                 .v4l_id = V4L2_CID_HUE,
709                 .desc = "Hue",
710                 .name = "hue",
711                 .default_value = 0,
712                 DEFREF(hue),
713                 DEFINT(-128,127),
714         },{
715                 .v4l_id = V4L2_CID_AUDIO_VOLUME,
716                 .desc = "Volume",
717                 .name = "volume",
718                 .default_value = 65535,
719                 DEFREF(volume),
720                 DEFINT(0,65535),
721         },{
722                 .v4l_id = V4L2_CID_AUDIO_BALANCE,
723                 .desc = "Balance",
724                 .name = "balance",
725                 .default_value = 0,
726                 DEFREF(balance),
727                 DEFINT(-32768,32767),
728         },{
729                 .v4l_id = V4L2_CID_AUDIO_BASS,
730                 .desc = "Bass",
731                 .name = "bass",
732                 .default_value = 0,
733                 DEFREF(bass),
734                 DEFINT(-32768,32767),
735         },{
736                 .v4l_id = V4L2_CID_AUDIO_TREBLE,
737                 .desc = "Treble",
738                 .name = "treble",
739                 .default_value = 0,
740                 DEFREF(treble),
741                 DEFINT(-32768,32767),
742         },{
743                 .v4l_id = V4L2_CID_AUDIO_MUTE,
744                 .desc = "Mute",
745                 .name = "mute",
746                 .default_value = 0,
747                 DEFREF(mute),
748                 DEFBOOL,
749         },{
750                 .desc = "Video Source",
751                 .name = "input",
752                 .internal_id = PVR2_CID_INPUT,
753                 .default_value = PVR2_CVAL_INPUT_TV,
754                 DEFREF(input),
755                 DEFENUM(control_values_input),
756         },{
757                 .desc = "Audio Mode",
758                 .name = "audio_mode",
759                 .internal_id = PVR2_CID_AUDIOMODE,
760                 .default_value = V4L2_TUNER_MODE_STEREO,
761                 DEFREF(audiomode),
762                 DEFENUM(control_values_audiomode),
763         },{
764                 .desc = "Horizontal capture resolution",
765                 .name = "resolution_hor",
766                 .internal_id = PVR2_CID_HRES,
767                 .default_value = 720,
768                 DEFREF(res_hor),
769                 DEFINT(19,720),
770         },{
771                 .desc = "Vertical capture resolution",
772                 .name = "resolution_ver",
773                 .internal_id = PVR2_CID_VRES,
774                 .default_value = 480,
775                 DEFREF(res_ver),
776                 DEFINT(17,576),
777                 /* Hook in check for video standard and adjust maximum
778                    depending on the standard. */
779                 .get_max_value = ctrl_vres_max_get,
780                 .get_min_value = ctrl_vres_min_get,
781         },{
782                 .v4l_id = V4L2_CID_MPEG_AUDIO_SAMPLING_FREQ,
783                 .default_value = V4L2_MPEG_AUDIO_SAMPLING_FREQ_48000,
784                 .desc = "Audio Sampling Frequency",
785                 .name = "srate",
786                 DEFREF(srate),
787                 DEFENUM(control_values_srate),
788         },{
789                 .desc = "Tuner Frequency (Hz)",
790                 .name = "frequency",
791                 .internal_id = PVR2_CID_FREQUENCY,
792                 .default_value = 175250000L,
793                 .set_value = ctrl_freq_set,
794                 .get_value = ctrl_freq_get,
795                 .is_dirty = ctrl_freq_is_dirty,
796                 .clear_dirty = ctrl_freq_clear_dirty,
797                 DEFINT(TV_MIN_FREQ,TV_MAX_FREQ),
798                 /* Hook in check for input value (tv/radio) and adjust
799                    max/min values accordingly */
800                 .check_value = ctrl_freq_check,
801                 .get_max_value = ctrl_freq_max_get,
802                 .get_min_value = ctrl_freq_min_get,
803         },{
804                 .desc = "Channel",
805                 .name = "channel",
806                 .set_value = ctrl_channel_set,
807                 .get_value = ctrl_channel_get,
808                 DEFINT(0,FREQTABLE_SIZE),
809         },{
810                 .desc = "Channel Program Frequency",
811                 .name = "freq_table_value",
812                 .set_value = ctrl_channelfreq_set,
813                 .get_value = ctrl_channelfreq_get,
814                 DEFINT(TV_MIN_FREQ,TV_MAX_FREQ),
815         },{
816                 .desc = "Channel Program ID",
817                 .name = "freq_table_channel",
818                 .set_value = ctrl_channelprog_set,
819                 .get_value = ctrl_channelprog_get,
820                 DEFINT(0,FREQTABLE_SIZE),
821         },{
822                 .desc = "Streaming Enabled",
823                 .name = "streaming_enabled",
824                 .get_value = ctrl_streamingenabled_get,
825                 DEFBOOL,
826         },{
827                 .desc = "USB Speed",
828                 .name = "usb_speed",
829                 .get_value = ctrl_hsm_get,
830                 DEFENUM(control_values_hsm),
831         },{
832                 .desc = "Signal Present",
833                 .name = "signal_present",
834                 .get_value = ctrl_signal_get,
835                 DEFBOOL,
836         },{
837                 .desc = "Video Standards Available Mask",
838                 .name = "video_standard_mask_available",
839                 .internal_id = PVR2_CID_STDAVAIL,
840                 .skip_init = !0,
841                 .get_value = ctrl_stdavail_get,
842                 .set_value = ctrl_stdavail_set,
843                 .val_to_sym = ctrl_std_val_to_sym,
844                 .sym_to_val = ctrl_std_sym_to_val,
845                 .type = pvr2_ctl_bitmask,
846         },{
847                 .desc = "Video Standards In Use Mask",
848                 .name = "video_standard_mask_active",
849                 .internal_id = PVR2_CID_STDCUR,
850                 .skip_init = !0,
851                 .get_value = ctrl_stdcur_get,
852                 .set_value = ctrl_stdcur_set,
853                 .is_dirty = ctrl_stdcur_is_dirty,
854                 .clear_dirty = ctrl_stdcur_clear_dirty,
855                 .val_to_sym = ctrl_std_val_to_sym,
856                 .sym_to_val = ctrl_std_sym_to_val,
857                 .type = pvr2_ctl_bitmask,
858         },{
859                 .desc = "Subsystem enabled mask",
860                 .name = "debug_subsys_mask",
861                 .skip_init = !0,
862                 .get_value = ctrl_subsys_get,
863                 .set_value = ctrl_subsys_set,
864                 DEFMASK(PVR2_SUBSYS_ALL,control_values_subsystem),
865         },{
866                 .desc = "Subsystem stream mask",
867                 .name = "debug_subsys_stream_mask",
868                 .skip_init = !0,
869                 .get_value = ctrl_subsys_stream_get,
870                 .set_value = ctrl_subsys_stream_set,
871                 DEFMASK(PVR2_SUBSYS_ALL,control_values_subsystem),
872         },{
873                 .desc = "Video Standard Name",
874                 .name = "video_standard",
875                 .internal_id = PVR2_CID_STDENUM,
876                 .skip_init = !0,
877                 .get_value = ctrl_stdenumcur_get,
878                 .set_value = ctrl_stdenumcur_set,
879                 .is_dirty = ctrl_stdenumcur_is_dirty,
880                 .clear_dirty = ctrl_stdenumcur_clear_dirty,
881                 .type = pvr2_ctl_enum,
882         }
883 };
884
885 #define CTRLDEF_COUNT (sizeof(control_defs)/sizeof(control_defs[0]))
886
887
888 const char *pvr2_config_get_name(enum pvr2_config cfg)
889 {
890         switch (cfg) {
891         case pvr2_config_empty: return "empty";
892         case pvr2_config_mpeg: return "mpeg";
893         case pvr2_config_vbi: return "vbi";
894         case pvr2_config_radio: return "radio";
895         }
896         return "<unknown>";
897 }
898
899
900 struct usb_device *pvr2_hdw_get_dev(struct pvr2_hdw *hdw)
901 {
902         return hdw->usb_dev;
903 }
904
905
906 unsigned long pvr2_hdw_get_sn(struct pvr2_hdw *hdw)
907 {
908         return hdw->serial_number;
909 }
910
911 int pvr2_hdw_get_unit_number(struct pvr2_hdw *hdw)
912 {
913         return hdw->unit_number;
914 }
915
916
917 /* Attempt to locate one of the given set of files.  Messages are logged
918    appropriate to what has been found.  The return value will be 0 or
919    greater on success (it will be the index of the file name found) and
920    fw_entry will be filled in.  Otherwise a negative error is returned on
921    failure.  If the return value is -ENOENT then no viable firmware file
922    could be located. */
923 static int pvr2_locate_firmware(struct pvr2_hdw *hdw,
924                                 const struct firmware **fw_entry,
925                                 const char *fwtypename,
926                                 unsigned int fwcount,
927                                 const char *fwnames[])
928 {
929         unsigned int idx;
930         int ret = -EINVAL;
931         for (idx = 0; idx < fwcount; idx++) {
932                 ret = request_firmware(fw_entry,
933                                        fwnames[idx],
934                                        &hdw->usb_dev->dev);
935                 if (!ret) {
936                         trace_firmware("Located %s firmware: %s;"
937                                        " uploading...",
938                                        fwtypename,
939                                        fwnames[idx]);
940                         return idx;
941                 }
942                 if (ret == -ENOENT) continue;
943                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
944                            "request_firmware fatal error with code=%d",ret);
945                 return ret;
946         }
947         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
948                    "***WARNING***"
949                    " Device %s firmware"
950                    " seems to be missing.",
951                    fwtypename);
952         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
953                    "Did you install the pvrusb2 firmware files"
954                    " in their proper location?");
955         if (fwcount == 1) {
956                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
957                            "request_firmware unable to locate %s file %s",
958                            fwtypename,fwnames[0]);
959         } else {
960                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
961                            "request_firmware unable to locate"
962                            " one of the following %s files:",
963                            fwtypename);
964                 for (idx = 0; idx < fwcount; idx++) {
965                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
966                                    "request_firmware: Failed to find %s",
967                                    fwnames[idx]);
968                 }
969         }
970         return ret;
971 }
972
973
974 /*
975  * pvr2_upload_firmware1().
976  *
977  * Send the 8051 firmware to the device.  After the upload, arrange for
978  * device to re-enumerate.
979  *
980  * NOTE : the pointer to the firmware data given by request_firmware()
981  * is not suitable for an usb transaction.
982  *
983  */
984 static int pvr2_upload_firmware1(struct pvr2_hdw *hdw)
985 {
986         const struct firmware *fw_entry = NULL;
987         void  *fw_ptr;
988         unsigned int pipe;
989         int ret;
990         u16 address;
991         static const char *fw_files_29xxx[] = {
992                 "v4l-pvrusb2-29xxx-01.fw",
993         };
994         static const char *fw_files_24xxx[] = {
995                 "v4l-pvrusb2-24xxx-01.fw",
996         };
997         static const struct pvr2_string_table fw_file_defs[] = {
998                 [PVR2_HDW_TYPE_29XXX] = {
999                         fw_files_29xxx,
1000                         sizeof(fw_files_29xxx)/sizeof(fw_files_29xxx[0]),
1001                 },
1002                 [PVR2_HDW_TYPE_24XXX] = {
1003                         fw_files_24xxx,
1004                         sizeof(fw_files_24xxx)/sizeof(fw_files_24xxx[0]),
1005                 },
1006         };
1007         hdw->fw1_state = FW1_STATE_FAILED; // default result
1008
1009         trace_firmware("pvr2_upload_firmware1");
1010
1011         ret = pvr2_locate_firmware(hdw,&fw_entry,"fx2 controller",
1012                                    fw_file_defs[hdw->hdw_type].cnt,
1013                                    fw_file_defs[hdw->hdw_type].lst);
1014         if (ret < 0) {
1015                 if (ret == -ENOENT) hdw->fw1_state = FW1_STATE_MISSING;
1016                 return ret;
1017         }
1018
1019         usb_settoggle(hdw->usb_dev, 0 & 0xf, !(0 & USB_DIR_IN), 0);
1020         usb_clear_halt(hdw->usb_dev, usb_sndbulkpipe(hdw->usb_dev, 0 & 0x7f));
1021
1022         pipe = usb_sndctrlpipe(hdw->usb_dev, 0);
1023
1024         if (fw_entry->size != 0x2000){
1025                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,"wrong fx2 firmware size");
1026                 release_firmware(fw_entry);
1027                 return -ENOMEM;
1028         }
1029
1030         fw_ptr = kmalloc(0x800, GFP_KERNEL);
1031         if (fw_ptr == NULL){
1032                 release_firmware(fw_entry);
1033                 return -ENOMEM;
1034         }
1035
1036         /* We have to hold the CPU during firmware upload. */
1037         pvr2_hdw_cpureset_assert(hdw,1);
1038
1039         /* upload the firmware to address 0000-1fff in 2048 (=0x800) bytes
1040            chunk. */
1041
1042         ret = 0;
1043         for(address = 0; address < fw_entry->size; address += 0x800) {
1044                 memcpy(fw_ptr, fw_entry->data + address, 0x800);
1045                 ret += usb_control_msg(hdw->usb_dev, pipe, 0xa0, 0x40, address,
1046                                        0, fw_ptr, 0x800, HZ);
1047         }
1048
1049         trace_firmware("Upload done, releasing device's CPU");
1050
1051         /* Now release the CPU.  It will disconnect and reconnect later. */
1052         pvr2_hdw_cpureset_assert(hdw,0);
1053
1054         kfree(fw_ptr);
1055         release_firmware(fw_entry);
1056
1057         trace_firmware("Upload done (%d bytes sent)",ret);
1058
1059         /* We should have written 8192 bytes */
1060         if (ret == 8192) {
1061                 hdw->fw1_state = FW1_STATE_RELOAD;
1062                 return 0;
1063         }
1064
1065         return -EIO;
1066 }
1067
1068
1069 /*
1070  * pvr2_upload_firmware2()
1071  *
1072  * This uploads encoder firmware on endpoint 2.
1073  *
1074  */
1075
1076 int pvr2_upload_firmware2(struct pvr2_hdw *hdw)
1077 {
1078         const struct firmware *fw_entry = NULL;
1079         void  *fw_ptr;
1080         unsigned int pipe, fw_len, fw_done;
1081         int actual_length;
1082         int ret = 0;
1083         int fwidx;
1084         static const char *fw_files[] = {
1085                 CX2341X_FIRM_ENC_FILENAME,
1086         };
1087
1088         trace_firmware("pvr2_upload_firmware2");
1089
1090         ret = pvr2_locate_firmware(hdw,&fw_entry,"encoder",
1091                                    sizeof(fw_files)/sizeof(fw_files[0]),
1092                                    fw_files);
1093         if (ret < 0) return ret;
1094         fwidx = ret;
1095         ret = 0;
1096         /* Since we're about to completely reinitialize the encoder,
1097            invalidate our cached copy of its configuration state.  Next
1098            time we configure the encoder, then we'll fully configure it. */
1099         hdw->enc_cur_valid = 0;
1100
1101         /* First prepare firmware loading */
1102         ret |= pvr2_write_register(hdw, 0x0048, 0xffffffff); /*interrupt mask*/
1103         ret |= pvr2_hdw_gpio_chg_dir(hdw,0xffffffff,0x00000088); /*gpio dir*/
1104         ret |= pvr2_hdw_gpio_chg_out(hdw,0xffffffff,0x00000008); /*gpio output state*/
1105         ret |= pvr2_hdw_cmd_deep_reset(hdw);
1106         ret |= pvr2_write_register(hdw, 0xa064, 0x00000000); /*APU command*/
1107         ret |= pvr2_hdw_gpio_chg_dir(hdw,0xffffffff,0x00000408); /*gpio dir*/
1108         ret |= pvr2_hdw_gpio_chg_out(hdw,0xffffffff,0x00000008); /*gpio output state*/
1109         ret |= pvr2_write_register(hdw, 0x9058, 0xffffffed); /*VPU ctrl*/
1110         ret |= pvr2_write_register(hdw, 0x9054, 0xfffffffd); /*reset hw blocks*/
1111         ret |= pvr2_write_register(hdw, 0x07f8, 0x80000800); /*encoder SDRAM refresh*/
1112         ret |= pvr2_write_register(hdw, 0x07fc, 0x0000001a); /*encoder SDRAM pre-charge*/
1113         ret |= pvr2_write_register(hdw, 0x0700, 0x00000000); /*I2C clock*/
1114         ret |= pvr2_write_register(hdw, 0xaa00, 0x00000000); /*unknown*/
1115         ret |= pvr2_write_register(hdw, 0xaa04, 0x00057810); /*unknown*/
1116         ret |= pvr2_write_register(hdw, 0xaa10, 0x00148500); /*unknown*/
1117         ret |= pvr2_write_register(hdw, 0xaa18, 0x00840000); /*unknown*/
1118         ret |= pvr2_write_u8(hdw, 0x52, 0);
1119         ret |= pvr2_write_u16(hdw, 0x0600, 0);
1120
1121         if (ret) {
1122                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1123                            "firmware2 upload prep failed, ret=%d",ret);
1124                 release_firmware(fw_entry);
1125                 return ret;
1126         }
1127
1128         /* Now send firmware */
1129
1130         fw_len = fw_entry->size;
1131
1132         if (fw_len % FIRMWARE_CHUNK_SIZE) {
1133                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1134                            "size of %s firmware"
1135                            " must be a multiple of 8192B",
1136                            fw_files[fwidx]);
1137                 release_firmware(fw_entry);
1138                 return -1;
1139         }
1140
1141         fw_ptr = kmalloc(FIRMWARE_CHUNK_SIZE, GFP_KERNEL);
1142         if (fw_ptr == NULL){
1143                 release_firmware(fw_entry);
1144                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1145                            "failed to allocate memory for firmware2 upload");
1146                 return -ENOMEM;
1147         }
1148
1149         pipe = usb_sndbulkpipe(hdw->usb_dev, PVR2_FIRMWARE_ENDPOINT);
1150
1151         for (fw_done = 0 ; (fw_done < fw_len) && !ret ;
1152              fw_done += FIRMWARE_CHUNK_SIZE ) {
1153                 int i;
1154                 memcpy(fw_ptr, fw_entry->data + fw_done, FIRMWARE_CHUNK_SIZE);
1155                 /* Usbsnoop log  shows that we must swap bytes... */
1156                 for (i = 0; i < FIRMWARE_CHUNK_SIZE/4 ; i++)
1157                         ((u32 *)fw_ptr)[i] = ___swab32(((u32 *)fw_ptr)[i]);
1158
1159                 ret |= usb_bulk_msg(hdw->usb_dev, pipe, fw_ptr,
1160                                     FIRMWARE_CHUNK_SIZE,
1161                                     &actual_length, HZ);
1162                 ret |= (actual_length != FIRMWARE_CHUNK_SIZE);
1163         }
1164
1165         trace_firmware("upload of %s : %i / %i ",
1166                        fw_files[fwidx],fw_done,fw_len);
1167
1168         kfree(fw_ptr);
1169         release_firmware(fw_entry);
1170
1171         if (ret) {
1172                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1173                            "firmware2 upload transfer failure");
1174                 return ret;
1175         }
1176
1177         /* Finish upload */
1178
1179         ret |= pvr2_write_register(hdw, 0x9054, 0xffffffff); /*reset hw blocks*/
1180         ret |= pvr2_write_register(hdw, 0x9058, 0xffffffe8); /*VPU ctrl*/
1181         ret |= pvr2_write_u16(hdw, 0x0600, 0);
1182
1183         if (ret) {
1184                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1185                            "firmware2 upload post-proc failure");
1186         } else {
1187                 hdw->subsys_enabled_mask |= (1<<PVR2_SUBSYS_B_ENC_FIRMWARE);
1188         }
1189         return ret;
1190 }
1191
1192
1193 #define FIRMWARE_RECOVERY_BITS \
1194         ((1<<PVR2_SUBSYS_B_ENC_CFG) | \
1195          (1<<PVR2_SUBSYS_B_ENC_RUN) | \
1196          (1<<PVR2_SUBSYS_B_ENC_FIRMWARE) | \
1197          (1<<PVR2_SUBSYS_B_USBSTREAM_RUN))
1198
1199 /*
1200
1201   This single function is key to pretty much everything.  The pvrusb2
1202   device can logically be viewed as a series of subsystems which can be
1203   stopped / started or unconfigured / configured.  To get things streaming,
1204   one must configure everything and start everything, but there may be
1205   various reasons over time to deconfigure something or stop something.
1206   This function handles all of this activity.  Everything EVERYWHERE that
1207   must affect a subsystem eventually comes here to do the work.
1208
1209   The current state of all subsystems is represented by a single bit mask,
1210   known as subsys_enabled_mask.  The bit positions are defined by the
1211   PVR2_SUBSYS_xxxx macros, with one subsystem per bit position.  At any
1212   time the set of configured or active subsystems can be queried just by
1213   looking at that mask.  To change bits in that mask, this function here
1214   must be called.  The "msk" argument indicates which bit positions to
1215   change, and the "val" argument defines the new values for the positions
1216   defined by "msk".
1217
1218   There is a priority ordering of starting / stopping things, and for
1219   multiple requested changes, this function implements that ordering.
1220   (Thus we will act on a request to load encoder firmware before we
1221   configure the encoder.)  In addition to priority ordering, there is a
1222   recovery strategy implemented here.  If a particular step fails and we
1223   detect that failure, this function will clear the affected subsystem bits
1224   and restart.  Thus we have a means for recovering from a dead encoder:
1225   Clear all bits that correspond to subsystems that we need to restart /
1226   reconfigure and start over.
1227
1228 */
1229 static void pvr2_hdw_subsys_bit_chg_no_lock(struct pvr2_hdw *hdw,
1230                                             unsigned long msk,
1231                                             unsigned long val)
1232 {
1233         unsigned long nmsk;
1234         unsigned long vmsk;
1235         int ret;
1236         unsigned int tryCount = 0;
1237
1238         if (!hdw->flag_ok) return;
1239
1240         msk &= PVR2_SUBSYS_ALL;
1241         nmsk = (hdw->subsys_enabled_mask & ~msk) | (val & msk);
1242         nmsk &= PVR2_SUBSYS_ALL;
1243
1244         for (;;) {
1245                 tryCount++;
1246                 if (!((nmsk ^ hdw->subsys_enabled_mask) &
1247                       PVR2_SUBSYS_ALL)) break;
1248                 if (tryCount > 4) {
1249                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1250                                    "Too many retries when configuring device;"
1251                                    " giving up");
1252                         pvr2_hdw_render_useless(hdw);
1253                         break;
1254                 }
1255                 if (tryCount > 1) {
1256                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1257                                    "Retrying device reconfiguration");
1258                 }
1259                 pvr2_trace(PVR2_TRACE_INIT,
1260                            "subsys mask changing 0x%lx:0x%lx"
1261                            " from 0x%lx to 0x%lx",
1262                            msk,val,hdw->subsys_enabled_mask,nmsk);
1263
1264                 vmsk = (nmsk ^ hdw->subsys_enabled_mask) &
1265                         hdw->subsys_enabled_mask;
1266                 if (vmsk) {
1267                         if (vmsk & (1<<PVR2_SUBSYS_B_ENC_RUN)) {
1268                                 pvr2_trace(PVR2_TRACE_CTL,
1269                                            "/*---TRACE_CTL----*/"
1270                                            " pvr2_encoder_stop");
1271                                 ret = pvr2_encoder_stop(hdw);
1272                                 if (ret) {
1273                                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1274                                                    "Error recovery initiated");
1275                                         hdw->subsys_enabled_mask &=
1276                                                 ~FIRMWARE_RECOVERY_BITS;
1277                                         continue;
1278                                 }
1279                         }
1280                         if (vmsk & (1<<PVR2_SUBSYS_B_USBSTREAM_RUN)) {
1281                                 pvr2_trace(PVR2_TRACE_CTL,
1282                                            "/*---TRACE_CTL----*/"
1283                                            " pvr2_hdw_cmd_usbstream(0)");
1284                                 pvr2_hdw_cmd_usbstream(hdw,0);
1285                         }
1286                         if (vmsk & (1<<PVR2_SUBSYS_B_DIGITIZER_RUN)) {
1287                                 pvr2_trace(PVR2_TRACE_CTL,
1288                                            "/*---TRACE_CTL----*/"
1289                                            " decoder disable");
1290                                 if (hdw->decoder_ctrl) {
1291                                         hdw->decoder_ctrl->enable(
1292                                                 hdw->decoder_ctrl->ctxt,0);
1293                                 } else {
1294                                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1295                                                    "WARNING:"
1296                                                    " No decoder present");
1297                                 }
1298                                 hdw->subsys_enabled_mask &=
1299                                         ~(1<<PVR2_SUBSYS_B_DIGITIZER_RUN);
1300                         }
1301                         if (vmsk & PVR2_SUBSYS_CFG_ALL) {
1302                                 hdw->subsys_enabled_mask &=
1303                                         ~(vmsk & PVR2_SUBSYS_CFG_ALL);
1304                         }
1305                 }
1306                 vmsk = (nmsk ^ hdw->subsys_enabled_mask) & nmsk;
1307                 if (vmsk) {
1308                         if (vmsk & (1<<PVR2_SUBSYS_B_ENC_FIRMWARE)) {
1309                                 pvr2_trace(PVR2_TRACE_CTL,
1310                                            "/*---TRACE_CTL----*/"
1311                                            " pvr2_upload_firmware2");
1312                                 ret = pvr2_upload_firmware2(hdw);
1313                                 if (ret) {
1314                                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1315                                                    "Failure uploading encoder"
1316                                                    " firmware");
1317                                         pvr2_hdw_render_useless(hdw);
1318                                         break;
1319                                 }
1320                         }
1321                         if (vmsk & (1<<PVR2_SUBSYS_B_ENC_CFG)) {
1322                                 pvr2_trace(PVR2_TRACE_CTL,
1323                                            "/*---TRACE_CTL----*/"
1324                                            " pvr2_encoder_configure");
1325                                 ret = pvr2_encoder_configure(hdw);
1326                                 if (ret) {
1327                                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1328                                                    "Error recovery initiated");
1329                                         hdw->subsys_enabled_mask &=
1330                                                 ~FIRMWARE_RECOVERY_BITS;
1331                                         continue;
1332                                 }
1333                         }
1334                         if (vmsk & (1<<PVR2_SUBSYS_B_DIGITIZER_RUN)) {
1335                                 pvr2_trace(PVR2_TRACE_CTL,
1336                                            "/*---TRACE_CTL----*/"
1337                                            " decoder enable");
1338                                 if (hdw->decoder_ctrl) {
1339                                         hdw->decoder_ctrl->enable(
1340                                                 hdw->decoder_ctrl->ctxt,!0);
1341                                 } else {
1342                                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1343                                                    "WARNING:"
1344                                                    " No decoder present");
1345                                 }
1346                                 hdw->subsys_enabled_mask |=
1347                                         (1<<PVR2_SUBSYS_B_DIGITIZER_RUN);
1348                         }
1349                         if (vmsk & (1<<PVR2_SUBSYS_B_USBSTREAM_RUN)) {
1350                                 pvr2_trace(PVR2_TRACE_CTL,
1351                                            "/*---TRACE_CTL----*/"
1352                                            " pvr2_hdw_cmd_usbstream(1)");
1353                                 pvr2_hdw_cmd_usbstream(hdw,!0);
1354                         }
1355                         if (vmsk & (1<<PVR2_SUBSYS_B_ENC_RUN)) {
1356                                 pvr2_trace(PVR2_TRACE_CTL,
1357                                            "/*---TRACE_CTL----*/"
1358                                            " pvr2_encoder_start");
1359                                 ret = pvr2_encoder_start(hdw);
1360                                 if (ret) {
1361                                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1362                                                    "Error recovery initiated");
1363                                         hdw->subsys_enabled_mask &=
1364                                                 ~FIRMWARE_RECOVERY_BITS;
1365                                         continue;
1366                                 }
1367                         }
1368                 }
1369         }
1370 }
1371
1372
1373 void pvr2_hdw_subsys_bit_chg(struct pvr2_hdw *hdw,
1374                              unsigned long msk,unsigned long val)
1375 {
1376         LOCK_TAKE(hdw->big_lock); do {
1377                 pvr2_hdw_subsys_bit_chg_no_lock(hdw,msk,val);
1378         } while (0); LOCK_GIVE(hdw->big_lock);
1379 }
1380
1381
1382 unsigned long pvr2_hdw_subsys_get(struct pvr2_hdw *hdw)
1383 {
1384         return hdw->subsys_enabled_mask;
1385 }
1386
1387
1388 unsigned long pvr2_hdw_subsys_stream_get(struct pvr2_hdw *hdw)
1389 {
1390         return hdw->subsys_stream_mask;
1391 }
1392
1393
1394 static void pvr2_hdw_subsys_stream_bit_chg_no_lock(struct pvr2_hdw *hdw,
1395                                                    unsigned long msk,
1396                                                    unsigned long val)
1397 {
1398         unsigned long val2;
1399         msk &= PVR2_SUBSYS_ALL;
1400         val2 = ((hdw->subsys_stream_mask & ~msk) | (val & msk));
1401         pvr2_trace(PVR2_TRACE_INIT,
1402                    "stream mask changing 0x%lx:0x%lx from 0x%lx to 0x%lx",
1403                    msk,val,hdw->subsys_stream_mask,val2);
1404         hdw->subsys_stream_mask = val2;
1405 }
1406
1407
1408 void pvr2_hdw_subsys_stream_bit_chg(struct pvr2_hdw *hdw,
1409                                     unsigned long msk,
1410                                     unsigned long val)
1411 {
1412         LOCK_TAKE(hdw->big_lock); do {
1413                 pvr2_hdw_subsys_stream_bit_chg_no_lock(hdw,msk,val);
1414         } while (0); LOCK_GIVE(hdw->big_lock);
1415 }
1416
1417
1418 static int pvr2_hdw_set_streaming_no_lock(struct pvr2_hdw *hdw,int enableFl)
1419 {
1420         if ((!enableFl) == !(hdw->flag_streaming_enabled)) return 0;
1421         if (enableFl) {
1422                 pvr2_trace(PVR2_TRACE_START_STOP,
1423                            "/*--TRACE_STREAM--*/ enable");
1424                 pvr2_hdw_subsys_bit_chg_no_lock(hdw,~0,~0);
1425         } else {
1426                 pvr2_trace(PVR2_TRACE_START_STOP,
1427                            "/*--TRACE_STREAM--*/ disable");
1428                 pvr2_hdw_subsys_bit_chg_no_lock(hdw,hdw->subsys_stream_mask,0);
1429         }
1430         if (!hdw->flag_ok) return -EIO;
1431         hdw->flag_streaming_enabled = enableFl != 0;
1432         return 0;
1433 }
1434
1435
1436 int pvr2_hdw_get_streaming(struct pvr2_hdw *hdw)
1437 {
1438         return hdw->flag_streaming_enabled != 0;
1439 }
1440
1441
1442 int pvr2_hdw_set_streaming(struct pvr2_hdw *hdw,int enable_flag)
1443 {
1444         int ret;
1445         LOCK_TAKE(hdw->big_lock); do {
1446                 ret = pvr2_hdw_set_streaming_no_lock(hdw,enable_flag);
1447         } while (0); LOCK_GIVE(hdw->big_lock);
1448         return ret;
1449 }
1450
1451
1452 static int pvr2_hdw_set_stream_type_no_lock(struct pvr2_hdw *hdw,
1453                                             enum pvr2_config config)
1454 {
1455         unsigned long sm = hdw->subsys_enabled_mask;
1456         if (!hdw->flag_ok) return -EIO;
1457         pvr2_hdw_subsys_bit_chg_no_lock(hdw,hdw->subsys_stream_mask,0);
1458         hdw->config = config;
1459         pvr2_hdw_subsys_bit_chg_no_lock(hdw,~0,sm);
1460         return 0;
1461 }
1462
1463
1464 int pvr2_hdw_set_stream_type(struct pvr2_hdw *hdw,enum pvr2_config config)
1465 {
1466         int ret;
1467         if (!hdw->flag_ok) return -EIO;
1468         LOCK_TAKE(hdw->big_lock);
1469         ret = pvr2_hdw_set_stream_type_no_lock(hdw,config);
1470         LOCK_GIVE(hdw->big_lock);
1471         return ret;
1472 }
1473
1474
1475 static int get_default_tuner_type(struct pvr2_hdw *hdw)
1476 {
1477         int unit_number = hdw->unit_number;
1478         int tp = -1;
1479         if ((unit_number >= 0) && (unit_number < PVR_NUM)) {
1480                 tp = tuner[unit_number];
1481         }
1482         if (tp < 0) return -EINVAL;
1483         hdw->tuner_type = tp;
1484         return 0;
1485 }
1486
1487
1488 static v4l2_std_id get_default_standard(struct pvr2_hdw *hdw)
1489 {
1490         int unit_number = hdw->unit_number;
1491         int tp = 0;
1492         if ((unit_number >= 0) && (unit_number < PVR_NUM)) {
1493                 tp = video_std[unit_number];
1494         }
1495         return tp;
1496 }
1497
1498
1499 static unsigned int get_default_error_tolerance(struct pvr2_hdw *hdw)
1500 {
1501         int unit_number = hdw->unit_number;
1502         int tp = 0;
1503         if ((unit_number >= 0) && (unit_number < PVR_NUM)) {
1504                 tp = tolerance[unit_number];
1505         }
1506         return tp;
1507 }
1508
1509
1510 static int pvr2_hdw_check_firmware(struct pvr2_hdw *hdw)
1511 {
1512         /* Try a harmless request to fetch the eeprom's address over
1513            endpoint 1.  See what happens.  Only the full FX2 image can
1514            respond to this.  If this probe fails then likely the FX2
1515            firmware needs be loaded. */
1516         int result;
1517         LOCK_TAKE(hdw->ctl_lock); do {
1518                 hdw->cmd_buffer[0] = 0xeb;
1519                 result = pvr2_send_request_ex(hdw,HZ*1,!0,
1520                                            hdw->cmd_buffer,1,
1521                                            hdw->cmd_buffer,1);
1522                 if (result < 0) break;
1523         } while(0); LOCK_GIVE(hdw->ctl_lock);
1524         if (result) {
1525                 pvr2_trace(PVR2_TRACE_INIT,
1526                            "Probe of device endpoint 1 result status %d",
1527                            result);
1528         } else {
1529                 pvr2_trace(PVR2_TRACE_INIT,
1530                            "Probe of device endpoint 1 succeeded");
1531         }
1532         return result == 0;
1533 }
1534
1535 static void pvr2_hdw_setup_std(struct pvr2_hdw *hdw)
1536 {
1537         char buf[40];
1538         unsigned int bcnt;
1539         v4l2_std_id std1,std2;
1540
1541         std1 = get_default_standard(hdw);
1542
1543         bcnt = pvr2_std_id_to_str(buf,sizeof(buf),hdw->std_mask_eeprom);
1544         pvr2_trace(PVR2_TRACE_INIT,
1545                    "Supported video standard(s) reported by eeprom: %.*s",
1546                    bcnt,buf);
1547
1548         hdw->std_mask_avail = hdw->std_mask_eeprom;
1549
1550         std2 = std1 & ~hdw->std_mask_avail;
1551         if (std2) {
1552                 bcnt = pvr2_std_id_to_str(buf,sizeof(buf),std2);
1553                 pvr2_trace(PVR2_TRACE_INIT,
1554                            "Expanding supported video standards"
1555                            " to include: %.*s",
1556                            bcnt,buf);
1557                 hdw->std_mask_avail |= std2;
1558         }
1559
1560         pvr2_hdw_internal_set_std_avail(hdw);
1561
1562         if (std1) {
1563                 bcnt = pvr2_std_id_to_str(buf,sizeof(buf),std1);
1564                 pvr2_trace(PVR2_TRACE_INIT,
1565                            "Initial video standard forced to %.*s",
1566                            bcnt,buf);
1567                 hdw->std_mask_cur = std1;
1568                 hdw->std_dirty = !0;
1569                 pvr2_hdw_internal_find_stdenum(hdw);
1570                 return;
1571         }
1572
1573         if (hdw->std_enum_cnt > 1) {
1574                 // Autoselect the first listed standard
1575                 hdw->std_enum_cur = 1;
1576                 hdw->std_mask_cur = hdw->std_defs[hdw->std_enum_cur-1].id;
1577                 hdw->std_dirty = !0;
1578                 pvr2_trace(PVR2_TRACE_INIT,
1579                            "Initial video standard auto-selected to %s",
1580                            hdw->std_defs[hdw->std_enum_cur-1].name);
1581                 return;
1582         }
1583
1584         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1585                    "Unable to select a viable initial video standard");
1586 }
1587
1588
1589 static void pvr2_hdw_setup_low(struct pvr2_hdw *hdw)
1590 {
1591         int ret;
1592         unsigned int idx;
1593         struct pvr2_ctrl *cptr;
1594         int reloadFl = 0;
1595         if (!reloadFl) {
1596                 reloadFl = (hdw->usb_intf->cur_altsetting->desc.bNumEndpoints
1597                             == 0);
1598                 if (reloadFl) {
1599                         pvr2_trace(PVR2_TRACE_INIT,
1600                                    "USB endpoint config looks strange"
1601                                    "; possibly firmware needs to be loaded");
1602                 }
1603         }
1604         if (!reloadFl) {
1605                 reloadFl = !pvr2_hdw_check_firmware(hdw);
1606                 if (reloadFl) {
1607                         pvr2_trace(PVR2_TRACE_INIT,
1608                                    "Check for FX2 firmware failed"
1609                                    "; possibly firmware needs to be loaded");
1610                 }
1611         }
1612         if (reloadFl) {
1613                 if (pvr2_upload_firmware1(hdw) != 0) {
1614                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1615                                    "Failure uploading firmware1");
1616                 }
1617                 return;
1618         }
1619         hdw->fw1_state = FW1_STATE_OK;
1620
1621         if (initusbreset) {
1622                 pvr2_hdw_device_reset(hdw);
1623         }
1624         if (!pvr2_hdw_dev_ok(hdw)) return;
1625
1626         for (idx = 0; idx < pvr2_client_lists[hdw->hdw_type].cnt; idx++) {
1627                 request_module(pvr2_client_lists[hdw->hdw_type].lst[idx]);
1628         }
1629
1630         pvr2_hdw_cmd_powerup(hdw);
1631         if (!pvr2_hdw_dev_ok(hdw)) return;
1632
1633         if (pvr2_upload_firmware2(hdw)){
1634                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,"device unstable!!");
1635                 pvr2_hdw_render_useless(hdw);
1636                 return;
1637         }
1638
1639         // This step MUST happen after the earlier powerup step.
1640         pvr2_i2c_core_init(hdw);
1641         if (!pvr2_hdw_dev_ok(hdw)) return;
1642
1643         for (idx = 0; idx < CTRLDEF_COUNT; idx++) {
1644                 cptr = hdw->controls + idx;
1645                 if (cptr->info->skip_init) continue;
1646                 if (!cptr->info->set_value) continue;
1647                 cptr->info->set_value(cptr,~0,cptr->info->default_value);
1648         }
1649
1650         // Do not use pvr2_reset_ctl_endpoints() here.  It is not
1651         // thread-safe against the normal pvr2_send_request() mechanism.
1652         // (We should make it thread safe).
1653
1654         ret = pvr2_hdw_get_eeprom_addr(hdw);
1655         if (!pvr2_hdw_dev_ok(hdw)) return;
1656         if (ret < 0) {
1657                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1658                            "Unable to determine location of eeprom, skipping");
1659         } else {
1660                 hdw->eeprom_addr = ret;
1661                 pvr2_eeprom_analyze(hdw);
1662                 if (!pvr2_hdw_dev_ok(hdw)) return;
1663         }
1664
1665         pvr2_hdw_setup_std(hdw);
1666
1667         if (!get_default_tuner_type(hdw)) {
1668                 pvr2_trace(PVR2_TRACE_INIT,
1669                            "pvr2_hdw_setup: Tuner type overridden to %d",
1670                            hdw->tuner_type);
1671         }
1672
1673         hdw->tuner_updated = !0;
1674         pvr2_i2c_core_check_stale(hdw);
1675         hdw->tuner_updated = 0;
1676
1677         if (!pvr2_hdw_dev_ok(hdw)) return;
1678
1679         pvr2_hdw_commit_ctl_internal(hdw);
1680         if (!pvr2_hdw_dev_ok(hdw)) return;
1681
1682         hdw->vid_stream = pvr2_stream_create();
1683         if (!pvr2_hdw_dev_ok(hdw)) return;
1684         pvr2_trace(PVR2_TRACE_INIT,
1685                    "pvr2_hdw_setup: video stream is %p",hdw->vid_stream);
1686         if (hdw->vid_stream) {
1687                 idx = get_default_error_tolerance(hdw);
1688                 if (idx) {
1689                         pvr2_trace(PVR2_TRACE_INIT,
1690                                    "pvr2_hdw_setup: video stream %p"
1691                                    " setting tolerance %u",
1692                                    hdw->vid_stream,idx);
1693                 }
1694                 pvr2_stream_setup(hdw->vid_stream,hdw->usb_dev,
1695                                   PVR2_VID_ENDPOINT,idx);
1696         }
1697
1698         if (!pvr2_hdw_dev_ok(hdw)) return;
1699
1700         /* Make sure everything is up to date */
1701         pvr2_i2c_core_sync(hdw);
1702
1703         if (!pvr2_hdw_dev_ok(hdw)) return;
1704
1705         hdw->flag_init_ok = !0;
1706 }
1707
1708
1709 int pvr2_hdw_setup(struct pvr2_hdw *hdw)
1710 {
1711         pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_setup(hdw=%p) begin",hdw);
1712         LOCK_TAKE(hdw->big_lock); do {
1713                 pvr2_hdw_setup_low(hdw);
1714                 pvr2_trace(PVR2_TRACE_INIT,
1715                            "pvr2_hdw_setup(hdw=%p) done, ok=%d init_ok=%d",
1716                            hdw,hdw->flag_ok,hdw->flag_init_ok);
1717                 if (pvr2_hdw_dev_ok(hdw)) {
1718                         if (pvr2_hdw_init_ok(hdw)) {
1719                                 pvr2_trace(
1720                                         PVR2_TRACE_INFO,
1721                                         "Device initialization"
1722                                         " completed successfully.");
1723                                 break;
1724                         }
1725                         if (hdw->fw1_state == FW1_STATE_RELOAD) {
1726                                 pvr2_trace(
1727                                         PVR2_TRACE_INFO,
1728                                         "Device microcontroller firmware"
1729                                         " (re)loaded; it should now reset"
1730                                         " and reconnect.");
1731                                 break;
1732                         }
1733                         pvr2_trace(
1734                                 PVR2_TRACE_ERROR_LEGS,
1735                                 "Device initialization was not successful.");
1736                         if (hdw->fw1_state == FW1_STATE_MISSING) {
1737                                 pvr2_trace(
1738                                         PVR2_TRACE_ERROR_LEGS,
1739                                         "Giving up since device"
1740                                         " microcontroller firmware"
1741                                         " appears to be missing.");
1742                                 break;
1743                         }
1744                 }
1745                 if (procreload) {
1746                         pvr2_trace(
1747                                 PVR2_TRACE_ERROR_LEGS,
1748                                 "Attempting pvrusb2 recovery by reloading"
1749                                 " primary firmware.");
1750                         pvr2_trace(
1751                                 PVR2_TRACE_ERROR_LEGS,
1752                                 "If this works, device should disconnect"
1753                                 " and reconnect in a sane state.");
1754                         hdw->fw1_state = FW1_STATE_UNKNOWN;
1755                         pvr2_upload_firmware1(hdw);
1756                 } else {
1757                         pvr2_trace(
1758                                 PVR2_TRACE_ERROR_LEGS,
1759                                 "***WARNING*** pvrusb2 device hardware"
1760                                 " appears to be jammed"
1761                                 " and I can't clear it.");
1762                         pvr2_trace(
1763                                 PVR2_TRACE_ERROR_LEGS,
1764                                 "You might need to power cycle"
1765                                 " the pvrusb2 device"
1766                                 " in order to recover.");
1767                 }
1768         } while (0); LOCK_GIVE(hdw->big_lock);
1769         pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_setup(hdw=%p) end",hdw);
1770         return hdw->flag_init_ok;
1771 }
1772
1773
1774 /* Create and return a structure for interacting with the underlying
1775    hardware */
1776 struct pvr2_hdw *pvr2_hdw_create(struct usb_interface *intf,
1777                                  const struct usb_device_id *devid)
1778 {
1779         unsigned int idx,cnt1,cnt2;
1780         struct pvr2_hdw *hdw;
1781         unsigned int hdw_type;
1782         int valid_std_mask;
1783         struct pvr2_ctrl *cptr;
1784         __u8 ifnum;
1785         struct v4l2_queryctrl qctrl;
1786         struct pvr2_ctl_info *ciptr;
1787
1788         hdw_type = devid - pvr2_device_table;
1789         if (hdw_type >=
1790             sizeof(pvr2_device_names)/sizeof(pvr2_device_names[0])) {
1791                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1792                            "Bogus device type of %u reported",hdw_type);
1793                 return NULL;
1794         }
1795
1796         hdw = kmalloc(sizeof(*hdw),GFP_KERNEL);
1797         pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_create: hdw=%p, type \"%s\"",
1798                    hdw,pvr2_device_names[hdw_type]);
1799         if (!hdw) goto fail;
1800         memset(hdw,0,sizeof(*hdw));
1801         cx2341x_fill_defaults(&hdw->enc_ctl_state);
1802
1803         hdw->control_cnt = CTRLDEF_COUNT;
1804         hdw->control_cnt += MPEGDEF_COUNT;
1805         hdw->controls = kmalloc(sizeof(struct pvr2_ctrl) * hdw->control_cnt,
1806                                 GFP_KERNEL);
1807         if (!hdw->controls) goto fail;
1808         memset(hdw->controls,0,sizeof(struct pvr2_ctrl) * hdw->control_cnt);
1809         hdw->hdw_type = hdw_type;
1810         for (idx = 0; idx < hdw->control_cnt; idx++) {
1811                 cptr = hdw->controls + idx;
1812                 cptr->hdw = hdw;
1813         }
1814         for (idx = 0; idx < 32; idx++) {
1815                 hdw->std_mask_ptrs[idx] = hdw->std_mask_names[idx];
1816         }
1817         for (idx = 0; idx < CTRLDEF_COUNT; idx++) {
1818                 cptr = hdw->controls + idx;
1819                 cptr->info = control_defs+idx;
1820         }
1821         /* Define and configure additional controls from cx2341x module. */
1822         hdw->mpeg_ctrl_info = kmalloc(
1823                 sizeof(*(hdw->mpeg_ctrl_info)) * MPEGDEF_COUNT, GFP_KERNEL);
1824         if (!hdw->mpeg_ctrl_info) goto fail;
1825         memset(hdw->mpeg_ctrl_info,0,
1826                sizeof(*(hdw->mpeg_ctrl_info)) * MPEGDEF_COUNT);
1827         for (idx = 0; idx < MPEGDEF_COUNT; idx++) {
1828                 cptr = hdw->controls + idx + CTRLDEF_COUNT;
1829                 ciptr = &(hdw->mpeg_ctrl_info[idx].info);
1830                 ciptr->desc = hdw->mpeg_ctrl_info[idx].desc;
1831                 ciptr->name = mpeg_ids[idx].strid;
1832                 ciptr->v4l_id = mpeg_ids[idx].id;
1833                 ciptr->skip_init = !0;
1834                 ciptr->get_value = ctrl_cx2341x_get;
1835                 ciptr->get_v4lflags = ctrl_cx2341x_getv4lflags;
1836                 ciptr->is_dirty = ctrl_cx2341x_is_dirty;
1837                 if (!idx) ciptr->clear_dirty = ctrl_cx2341x_clear_dirty;
1838                 qctrl.id = ciptr->v4l_id;
1839                 cx2341x_ctrl_query(&hdw->enc_ctl_state,&qctrl);
1840                 if (!(qctrl.flags & V4L2_CTRL_FLAG_READ_ONLY)) {
1841                         ciptr->set_value = ctrl_cx2341x_set;
1842                 }
1843                 strncpy(hdw->mpeg_ctrl_info[idx].desc,qctrl.name,
1844                         PVR2_CTLD_INFO_DESC_SIZE);
1845                 hdw->mpeg_ctrl_info[idx].desc[PVR2_CTLD_INFO_DESC_SIZE-1] = 0;
1846                 ciptr->default_value = qctrl.default_value;
1847                 switch (qctrl.type) {
1848                 default:
1849                 case V4L2_CTRL_TYPE_INTEGER:
1850                         ciptr->type = pvr2_ctl_int;
1851                         ciptr->def.type_int.min_value = qctrl.minimum;
1852                         ciptr->def.type_int.max_value = qctrl.maximum;
1853                         break;
1854                 case V4L2_CTRL_TYPE_BOOLEAN:
1855                         ciptr->type = pvr2_ctl_bool;
1856                         break;
1857                 case V4L2_CTRL_TYPE_MENU:
1858                         ciptr->type = pvr2_ctl_enum;
1859                         ciptr->def.type_enum.value_names =
1860                                 cx2341x_ctrl_get_menu(ciptr->v4l_id);
1861                         for (cnt1 = 0;
1862                              ciptr->def.type_enum.value_names[cnt1] != NULL;
1863                              cnt1++) { }
1864                         ciptr->def.type_enum.count = cnt1;
1865                         break;
1866                 }
1867                 cptr->info = ciptr;
1868         }
1869
1870         // Initialize video standard enum dynamic control
1871         cptr = pvr2_hdw_get_ctrl_by_id(hdw,PVR2_CID_STDENUM);
1872         if (cptr) {
1873                 memcpy(&hdw->std_info_enum,cptr->info,
1874                        sizeof(hdw->std_info_enum));
1875                 cptr->info = &hdw->std_info_enum;
1876
1877         }
1878         // Initialize control data regarding video standard masks
1879         valid_std_mask = pvr2_std_get_usable();
1880         for (idx = 0; idx < 32; idx++) {
1881                 if (!(valid_std_mask & (1 << idx))) continue;
1882                 cnt1 = pvr2_std_id_to_str(
1883                         hdw->std_mask_names[idx],
1884                         sizeof(hdw->std_mask_names[idx])-1,
1885                         1 << idx);
1886                 hdw->std_mask_names[idx][cnt1] = 0;
1887         }
1888         cptr = pvr2_hdw_get_ctrl_by_id(hdw,PVR2_CID_STDAVAIL);
1889         if (cptr) {
1890                 memcpy(&hdw->std_info_avail,cptr->info,
1891                        sizeof(hdw->std_info_avail));
1892                 cptr->info = &hdw->std_info_avail;
1893                 hdw->std_info_avail.def.type_bitmask.bit_names =
1894                         hdw->std_mask_ptrs;
1895                 hdw->std_info_avail.def.type_bitmask.valid_bits =
1896                         valid_std_mask;
1897         }
1898         cptr = pvr2_hdw_get_ctrl_by_id(hdw,PVR2_CID_STDCUR);
1899         if (cptr) {
1900                 memcpy(&hdw->std_info_cur,cptr->info,
1901                        sizeof(hdw->std_info_cur));
1902                 cptr->info = &hdw->std_info_cur;
1903                 hdw->std_info_cur.def.type_bitmask.bit_names =
1904                         hdw->std_mask_ptrs;
1905                 hdw->std_info_avail.def.type_bitmask.valid_bits =
1906                         valid_std_mask;
1907         }
1908
1909         hdw->eeprom_addr = -1;
1910         hdw->unit_number = -1;
1911         hdw->v4l_minor_number_video = -1;
1912         hdw->v4l_minor_number_vbi = -1;
1913         hdw->v4l_minor_number_radio = -1;
1914         hdw->ctl_write_buffer = kmalloc(PVR2_CTL_BUFFSIZE,GFP_KERNEL);
1915         if (!hdw->ctl_write_buffer) goto fail;
1916         hdw->ctl_read_buffer = kmalloc(PVR2_CTL_BUFFSIZE,GFP_KERNEL);
1917         if (!hdw->ctl_read_buffer) goto fail;
1918         hdw->ctl_write_urb = usb_alloc_urb(0,GFP_KERNEL);
1919         if (!hdw->ctl_write_urb) goto fail;
1920         hdw->ctl_read_urb = usb_alloc_urb(0,GFP_KERNEL);
1921         if (!hdw->ctl_read_urb) goto fail;
1922
1923         down(&pvr2_unit_sem); do {
1924                 for (idx = 0; idx < PVR_NUM; idx++) {
1925                         if (unit_pointers[idx]) continue;
1926                         hdw->unit_number = idx;
1927                         unit_pointers[idx] = hdw;
1928                         break;
1929                 }
1930         } while (0); up(&pvr2_unit_sem);
1931
1932         cnt1 = 0;
1933         cnt2 = scnprintf(hdw->name+cnt1,sizeof(hdw->name)-cnt1,"pvrusb2");
1934         cnt1 += cnt2;
1935         if (hdw->unit_number >= 0) {
1936                 cnt2 = scnprintf(hdw->name+cnt1,sizeof(hdw->name)-cnt1,"_%c",
1937                                  ('a' + hdw->unit_number));
1938                 cnt1 += cnt2;
1939         }
1940         if (cnt1 >= sizeof(hdw->name)) cnt1 = sizeof(hdw->name)-1;
1941         hdw->name[cnt1] = 0;
1942
1943         pvr2_trace(PVR2_TRACE_INIT,"Driver unit number is %d, name is %s",
1944                    hdw->unit_number,hdw->name);
1945
1946         hdw->tuner_type = -1;
1947         hdw->flag_ok = !0;
1948         /* Initialize the mask of subsystems that we will shut down when we
1949            stop streaming. */
1950         hdw->subsys_stream_mask = PVR2_SUBSYS_RUN_ALL;
1951         hdw->subsys_stream_mask |= (1<<PVR2_SUBSYS_B_ENC_CFG);
1952
1953         pvr2_trace(PVR2_TRACE_INIT,"subsys_stream_mask: 0x%lx",
1954                    hdw->subsys_stream_mask);
1955
1956         hdw->usb_intf = intf;
1957         hdw->usb_dev = interface_to_usbdev(intf);
1958
1959         ifnum = hdw->usb_intf->cur_altsetting->desc.bInterfaceNumber;
1960         usb_set_interface(hdw->usb_dev,ifnum,0);
1961
1962         mutex_init(&hdw->ctl_lock_mutex);
1963         mutex_init(&hdw->big_lock_mutex);
1964
1965         return hdw;
1966  fail:
1967         if (hdw) {
1968                 usb_free_urb(hdw->ctl_read_urb);
1969                 usb_free_urb(hdw->ctl_write_urb);
1970                 kfree(hdw->ctl_read_buffer);
1971                 kfree(hdw->ctl_write_buffer);
1972                 kfree(hdw->controls);
1973                 kfree(hdw->mpeg_ctrl_info);
1974                 kfree(hdw);
1975         }
1976         return NULL;
1977 }
1978
1979
1980 /* Remove _all_ associations between this driver and the underlying USB
1981    layer. */
1982 static void pvr2_hdw_remove_usb_stuff(struct pvr2_hdw *hdw)
1983 {
1984         if (hdw->flag_disconnected) return;
1985         pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_remove_usb_stuff: hdw=%p",hdw);
1986         if (hdw->ctl_read_urb) {
1987                 usb_kill_urb(hdw->ctl_read_urb);
1988                 usb_free_urb(hdw->ctl_read_urb);
1989                 hdw->ctl_read_urb = NULL;
1990         }
1991         if (hdw->ctl_write_urb) {
1992                 usb_kill_urb(hdw->ctl_write_urb);
1993                 usb_free_urb(hdw->ctl_write_urb);
1994                 hdw->ctl_write_urb = NULL;
1995         }
1996         if (hdw->ctl_read_buffer) {
1997                 kfree(hdw->ctl_read_buffer);
1998                 hdw->ctl_read_buffer = NULL;
1999         }
2000         if (hdw->ctl_write_buffer) {
2001                 kfree(hdw->ctl_write_buffer);
2002                 hdw->ctl_write_buffer = NULL;
2003         }
2004         pvr2_hdw_render_useless_unlocked(hdw);
2005         hdw->flag_disconnected = !0;
2006         hdw->usb_dev = NULL;
2007         hdw->usb_intf = NULL;
2008 }
2009
2010
2011 /* Destroy hardware interaction structure */
2012 void pvr2_hdw_destroy(struct pvr2_hdw *hdw)
2013 {
2014         pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_destroy: hdw=%p",hdw);
2015         if (hdw->fw_buffer) {
2016                 kfree(hdw->fw_buffer);
2017                 hdw->fw_buffer = NULL;
2018         }
2019         if (hdw->vid_stream) {
2020                 pvr2_stream_destroy(hdw->vid_stream);
2021                 hdw->vid_stream = NULL;
2022         }
2023         if (hdw->audio_stat) {
2024                 hdw->audio_stat->detach(hdw->audio_stat->ctxt);
2025         }
2026         if (hdw->decoder_ctrl) {
2027                 hdw->decoder_ctrl->detach(hdw->decoder_ctrl->ctxt);
2028         }
2029         pvr2_i2c_core_done(hdw);
2030         pvr2_hdw_remove_usb_stuff(hdw);
2031         down(&pvr2_unit_sem); do {
2032                 if ((hdw->unit_number >= 0) &&
2033                     (hdw->unit_number < PVR_NUM) &&
2034                     (unit_pointers[hdw->unit_number] == hdw)) {
2035                         unit_pointers[hdw->unit_number] = NULL;
2036                 }
2037         } while (0); up(&pvr2_unit_sem);
2038         kfree(hdw->controls);
2039         kfree(hdw->mpeg_ctrl_info);
2040         kfree(hdw->std_defs);
2041         kfree(hdw->std_enum_names);
2042         kfree(hdw);
2043 }
2044
2045
2046 int pvr2_hdw_init_ok(struct pvr2_hdw *hdw)
2047 {
2048         return hdw->flag_init_ok;
2049 }
2050
2051
2052 int pvr2_hdw_dev_ok(struct pvr2_hdw *hdw)
2053 {
2054         return (hdw && hdw->flag_ok);
2055 }
2056
2057
2058 /* Called when hardware has been unplugged */
2059 void pvr2_hdw_disconnect(struct pvr2_hdw *hdw)
2060 {
2061         pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_disconnect(hdw=%p)",hdw);
2062         LOCK_TAKE(hdw->big_lock);
2063         LOCK_TAKE(hdw->ctl_lock);
2064         pvr2_hdw_remove_usb_stuff(hdw);
2065         LOCK_GIVE(hdw->ctl_lock);
2066         LOCK_GIVE(hdw->big_lock);
2067 }
2068
2069
2070 // Attempt to autoselect an appropriate value for std_enum_cur given
2071 // whatever is currently in std_mask_cur
2072 static void pvr2_hdw_internal_find_stdenum(struct pvr2_hdw *hdw)
2073 {
2074         unsigned int idx;
2075         for (idx = 1; idx < hdw->std_enum_cnt; idx++) {
2076                 if (hdw->std_defs[idx-1].id == hdw->std_mask_cur) {
2077                         hdw->std_enum_cur = idx;
2078                         return;
2079                 }
2080         }
2081         hdw->std_enum_cur = 0;
2082 }
2083
2084
2085 // Calculate correct set of enumerated standards based on currently known
2086 // set of available standards bits.
2087 static void pvr2_hdw_internal_set_std_avail(struct pvr2_hdw *hdw)
2088 {
2089         struct v4l2_standard *newstd;
2090         unsigned int std_cnt;
2091         unsigned int idx;
2092
2093         newstd = pvr2_std_create_enum(&std_cnt,hdw->std_mask_avail);
2094
2095         if (hdw->std_defs) {
2096                 kfree(hdw->std_defs);
2097                 hdw->std_defs = NULL;
2098         }
2099         hdw->std_enum_cnt = 0;
2100         if (hdw->std_enum_names) {
2101                 kfree(hdw->std_enum_names);
2102                 hdw->std_enum_names = NULL;
2103         }
2104
2105         if (!std_cnt) {
2106                 pvr2_trace(
2107                         PVR2_TRACE_ERROR_LEGS,
2108                         "WARNING: Failed to identify any viable standards");
2109         }
2110         hdw->std_enum_names = kmalloc(sizeof(char *)*(std_cnt+1),GFP_KERNEL);
2111         hdw->std_enum_names[0] = "none";
2112         for (idx = 0; idx < std_cnt; idx++) {
2113                 hdw->std_enum_names[idx+1] =
2114                         newstd[idx].name;
2115         }
2116         // Set up the dynamic control for this standard
2117         hdw->std_info_enum.def.type_enum.value_names = hdw->std_enum_names;
2118         hdw->std_info_enum.def.type_enum.count = std_cnt+1;
2119         hdw->std_defs = newstd;
2120         hdw->std_enum_cnt = std_cnt+1;
2121         hdw->std_enum_cur = 0;
2122         hdw->std_info_cur.def.type_bitmask.valid_bits = hdw->std_mask_avail;
2123 }
2124
2125
2126 int pvr2_hdw_get_stdenum_value(struct pvr2_hdw *hdw,
2127                                struct v4l2_standard *std,
2128                                unsigned int idx)
2129 {
2130         int ret = -EINVAL;
2131         if (!idx) return ret;
2132         LOCK_TAKE(hdw->big_lock); do {
2133                 if (idx >= hdw->std_enum_cnt) break;
2134                 idx--;
2135                 memcpy(std,hdw->std_defs+idx,sizeof(*std));
2136                 ret = 0;
2137         } while (0); LOCK_GIVE(hdw->big_lock);
2138         return ret;
2139 }
2140
2141
2142 /* Get the number of defined controls */
2143 unsigned int pvr2_hdw_get_ctrl_count(struct pvr2_hdw *hdw)
2144 {
2145         return hdw->control_cnt;
2146 }
2147
2148
2149 /* Retrieve a control handle given its index (0..count-1) */
2150 struct pvr2_ctrl *pvr2_hdw_get_ctrl_by_index(struct pvr2_hdw *hdw,
2151                                              unsigned int idx)
2152 {
2153         if (idx >= hdw->control_cnt) return NULL;
2154         return hdw->controls + idx;
2155 }
2156
2157
2158 /* Retrieve a control handle given its index (0..count-1) */
2159 struct pvr2_ctrl *pvr2_hdw_get_ctrl_by_id(struct pvr2_hdw *hdw,
2160                                           unsigned int ctl_id)
2161 {
2162         struct pvr2_ctrl *cptr;
2163         unsigned int idx;
2164         int i;
2165
2166         /* This could be made a lot more efficient, but for now... */
2167         for (idx = 0; idx < hdw->control_cnt; idx++) {
2168                 cptr = hdw->controls + idx;
2169                 i = cptr->info->internal_id;
2170                 if (i && (i == ctl_id)) return cptr;
2171         }
2172         return NULL;
2173 }
2174
2175
2176 /* Given a V4L ID, retrieve the control structure associated with it. */
2177 struct pvr2_ctrl *pvr2_hdw_get_ctrl_v4l(struct pvr2_hdw *hdw,unsigned int ctl_id)
2178 {
2179         struct pvr2_ctrl *cptr;
2180         unsigned int idx;
2181         int i;
2182
2183         /* This could be made a lot more efficient, but for now... */
2184         for (idx = 0; idx < hdw->control_cnt; idx++) {
2185                 cptr = hdw->controls + idx;
2186                 i = cptr->info->v4l_id;
2187                 if (i && (i == ctl_id)) return cptr;
2188         }
2189         return NULL;
2190 }
2191
2192
2193 /* Given a V4L ID for its immediate predecessor, retrieve the control
2194    structure associated with it. */
2195 struct pvr2_ctrl *pvr2_hdw_get_ctrl_nextv4l(struct pvr2_hdw *hdw,
2196                                             unsigned int ctl_id)
2197 {
2198         struct pvr2_ctrl *cptr,*cp2;
2199         unsigned int idx;
2200         int i;
2201
2202         /* This could be made a lot more efficient, but for now... */
2203         cp2 = NULL;
2204         for (idx = 0; idx < hdw->control_cnt; idx++) {
2205                 cptr = hdw->controls + idx;
2206                 i = cptr->info->v4l_id;
2207                 if (!i) continue;
2208                 if (i <= ctl_id) continue;
2209                 if (cp2 && (cp2->info->v4l_id < i)) continue;
2210                 cp2 = cptr;
2211         }
2212         return cp2;
2213         return NULL;
2214 }
2215
2216
2217 static const char *get_ctrl_typename(enum pvr2_ctl_type tp)
2218 {
2219         switch (tp) {
2220         case pvr2_ctl_int: return "integer";
2221         case pvr2_ctl_enum: return "enum";
2222         case pvr2_ctl_bool: return "boolean";
2223         case pvr2_ctl_bitmask: return "bitmask";
2224         }
2225         return "";
2226 }
2227
2228
2229 /* Commit all control changes made up to this point.  Subsystems can be
2230    indirectly affected by these changes.  For a given set of things being
2231    committed, we'll clear the affected subsystem bits and then once we're
2232    done committing everything we'll make a request to restore the subsystem
2233    state(s) back to their previous value before this function was called.
2234    Thus we can automatically reconfigure affected pieces of the driver as
2235    controls are changed. */
2236 static int pvr2_hdw_commit_ctl_internal(struct pvr2_hdw *hdw)
2237 {
2238         unsigned long saved_subsys_mask = hdw->subsys_enabled_mask;
2239         unsigned long stale_subsys_mask = 0;
2240         unsigned int idx;
2241         struct pvr2_ctrl *cptr;
2242         int value;
2243         int commit_flag = 0;
2244         char buf[100];
2245         unsigned int bcnt,ccnt;
2246
2247         for (idx = 0; idx < hdw->control_cnt; idx++) {
2248                 cptr = hdw->controls + idx;
2249                 if (cptr->info->is_dirty == 0) continue;
2250                 if (!cptr->info->is_dirty(cptr)) continue;
2251                 if (!commit_flag) {
2252                         commit_flag = !0;
2253                 }
2254
2255                 bcnt = scnprintf(buf,sizeof(buf),"\"%s\" <-- ",
2256                                  cptr->info->name);
2257                 value = 0;
2258                 cptr->info->get_value(cptr,&value);
2259                 pvr2_ctrl_value_to_sym_internal(cptr,~0,value,
2260                                                 buf+bcnt,
2261                                                 sizeof(buf)-bcnt,&ccnt);
2262                 bcnt += ccnt;
2263                 bcnt += scnprintf(buf+bcnt,sizeof(buf)-bcnt," <%s>",
2264                                   get_ctrl_typename(cptr->info->type));
2265                 pvr2_trace(PVR2_TRACE_CTL,
2266                            "/*--TRACE_COMMIT--*/ %.*s",
2267                            bcnt,buf);
2268         }
2269
2270         if (!commit_flag) {
2271                 /* Nothing has changed */
2272                 return 0;
2273         }
2274
2275         /* When video standard changes, reset the hres and vres values -
2276            but if the user has pending changes there, then let the changes
2277            take priority. */
2278         if (hdw->std_dirty) {
2279                 /* Rewrite the vertical resolution to be appropriate to the
2280                    video standard that has been selected. */
2281                 int nvres;
2282                 if (hdw->std_mask_cur & V4L2_STD_525_60) {
2283                         nvres = 480;
2284                 } else {
2285                         nvres = 576;
2286                 }
2287                 if (nvres != hdw->res_ver_val) {
2288                         hdw->res_ver_val = nvres;
2289                         hdw->res_ver_dirty = !0;
2290                 }
2291         }
2292
2293         if (hdw->std_dirty ||
2294             hdw->enc_stale ||
2295             hdw->srate_dirty ||
2296             hdw->res_ver_dirty ||
2297             hdw->res_hor_dirty ||
2298             0) {
2299                 /* If any of this changes, then the encoder needs to be
2300                    reconfigured, and we need to reset the stream. */
2301                 stale_subsys_mask |= (1<<PVR2_SUBSYS_B_ENC_CFG);
2302         }
2303
2304         if (hdw->input_dirty) {
2305                 /* pk: If input changes to or from radio, then the encoder
2306                    needs to be restarted (for ENC_MUTE_VIDEO to work) */
2307                 stale_subsys_mask |= (1<<PVR2_SUBSYS_B_ENC_RUN);
2308         }
2309
2310
2311         if (hdw->srate_dirty) {
2312                 /* Write new sample rate into control structure since
2313                  * the master copy is stale.  We must track srate
2314                  * separate from the mpeg control structure because
2315                  * other logic also uses this value. */
2316                 struct v4l2_ext_controls cs;
2317                 struct v4l2_ext_control c1;
2318                 memset(&cs,0,sizeof(cs));
2319                 memset(&c1,0,sizeof(c1));
2320                 cs.controls = &c1;
2321                 cs.count = 1;
2322                 c1.id = V4L2_CID_MPEG_AUDIO_SAMPLING_FREQ;
2323                 c1.value = hdw->srate_val;
2324                 cx2341x_ext_ctrls(&hdw->enc_ctl_state,&cs,VIDIOC_S_EXT_CTRLS);
2325         }
2326
2327         /* Scan i2c core at this point - before we clear all the dirty
2328            bits.  Various parts of the i2c core will notice dirty bits as
2329            appropriate and arrange to broadcast or directly send updates to
2330            the client drivers in order to keep everything in sync */
2331         pvr2_i2c_core_check_stale(hdw);
2332
2333         for (idx = 0; idx < hdw->control_cnt; idx++) {
2334                 cptr = hdw->controls + idx;
2335                 if (!cptr->info->clear_dirty) continue;
2336                 cptr->info->clear_dirty(cptr);
2337         }
2338
2339         /* Now execute i2c core update */
2340         pvr2_i2c_core_sync(hdw);
2341
2342         pvr2_hdw_subsys_bit_chg_no_lock(hdw,stale_subsys_mask,0);
2343         pvr2_hdw_subsys_bit_chg_no_lock(hdw,~0,saved_subsys_mask);
2344
2345         return 0;
2346 }
2347
2348
2349 int pvr2_hdw_commit_ctl(struct pvr2_hdw *hdw)
2350 {
2351         LOCK_TAKE(hdw->big_lock); do {
2352                 pvr2_hdw_commit_ctl_internal(hdw);
2353         } while (0); LOCK_GIVE(hdw->big_lock);
2354         return 0;
2355 }
2356
2357
2358 void pvr2_hdw_poll(struct pvr2_hdw *hdw)
2359 {
2360         LOCK_TAKE(hdw->big_lock); do {
2361                 pvr2_i2c_core_sync(hdw);
2362         } while (0); LOCK_GIVE(hdw->big_lock);
2363 }
2364
2365
2366 void pvr2_hdw_setup_poll_trigger(struct pvr2_hdw *hdw,
2367                                  void (*func)(void *),
2368                                  void *data)
2369 {
2370         LOCK_TAKE(hdw->big_lock); do {
2371                 hdw->poll_trigger_func = func;
2372                 hdw->poll_trigger_data = data;
2373         } while (0); LOCK_GIVE(hdw->big_lock);
2374 }
2375
2376
2377 void pvr2_hdw_poll_trigger_unlocked(struct pvr2_hdw *hdw)
2378 {
2379         if (hdw->poll_trigger_func) {
2380                 hdw->poll_trigger_func(hdw->poll_trigger_data);
2381         }
2382 }
2383
2384 /* Return name for this driver instance */
2385 const char *pvr2_hdw_get_driver_name(struct pvr2_hdw *hdw)
2386 {
2387         return hdw->name;
2388 }
2389
2390
2391 /* Return bit mask indicating signal status */
2392 static unsigned int pvr2_hdw_get_signal_status_internal(struct pvr2_hdw *hdw)
2393 {
2394         unsigned int msk = 0;
2395         switch (hdw->input_val) {
2396         case PVR2_CVAL_INPUT_TV:
2397         case PVR2_CVAL_INPUT_RADIO:
2398                 if (hdw->decoder_ctrl &&
2399                     hdw->decoder_ctrl->tuned(hdw->decoder_ctrl->ctxt)) {
2400                         msk |= PVR2_SIGNAL_OK;
2401                         if (hdw->audio_stat &&
2402                             hdw->audio_stat->status(hdw->audio_stat->ctxt)) {
2403                                 if (hdw->flag_stereo) {
2404                                         msk |= PVR2_SIGNAL_STEREO;
2405                                 }
2406                                 if (hdw->flag_bilingual) {
2407                                         msk |= PVR2_SIGNAL_SAP;
2408                                 }
2409                         }
2410                 }
2411                 break;
2412         default:
2413                 msk |= PVR2_SIGNAL_OK | PVR2_SIGNAL_STEREO;
2414         }
2415         return msk;
2416 }
2417
2418
2419 int pvr2_hdw_is_hsm(struct pvr2_hdw *hdw)
2420 {
2421         int result;
2422         LOCK_TAKE(hdw->ctl_lock); do {
2423                 hdw->cmd_buffer[0] = 0x0b;
2424                 result = pvr2_send_request(hdw,
2425                                            hdw->cmd_buffer,1,
2426                                            hdw->cmd_buffer,1);
2427                 if (result < 0) break;
2428                 result = (hdw->cmd_buffer[0] != 0);
2429         } while(0); LOCK_GIVE(hdw->ctl_lock);
2430         return result;
2431 }
2432
2433
2434 /* Return bit mask indicating signal status */
2435 unsigned int pvr2_hdw_get_signal_status(struct pvr2_hdw *hdw)
2436 {
2437         unsigned int msk = 0;
2438         LOCK_TAKE(hdw->big_lock); do {
2439                 msk = pvr2_hdw_get_signal_status_internal(hdw);
2440         } while (0); LOCK_GIVE(hdw->big_lock);
2441         return msk;
2442 }
2443
2444
2445 /* Get handle to video output stream */
2446 struct pvr2_stream *pvr2_hdw_get_video_stream(struct pvr2_hdw *hp)
2447 {
2448         return hp->vid_stream;
2449 }
2450
2451
2452 void pvr2_hdw_trigger_module_log(struct pvr2_hdw *hdw)
2453 {
2454         int nr = pvr2_hdw_get_unit_number(hdw);
2455         LOCK_TAKE(hdw->big_lock); do {
2456                 hdw->log_requested = !0;
2457                 printk(KERN_INFO "pvrusb2: =================  START STATUS CARD #%d  =================\n", nr);
2458                 pvr2_i2c_core_check_stale(hdw);
2459                 hdw->log_requested = 0;
2460                 pvr2_i2c_core_sync(hdw);
2461                 pvr2_trace(PVR2_TRACE_INFO,"cx2341x config:");
2462                 cx2341x_log_status(&hdw->enc_ctl_state, "pvrusb2");
2463                 printk(KERN_INFO "pvrusb2: ==================  END STATUS CARD #%d  ==================\n", nr);
2464         } while (0); LOCK_GIVE(hdw->big_lock);
2465 }
2466
2467 void pvr2_hdw_cpufw_set_enabled(struct pvr2_hdw *hdw, int enable_flag)
2468 {
2469         int ret;
2470         u16 address;
2471         unsigned int pipe;
2472         LOCK_TAKE(hdw->big_lock); do {
2473                 if ((hdw->fw_buffer == 0) == !enable_flag) break;
2474
2475                 if (!enable_flag) {
2476                         pvr2_trace(PVR2_TRACE_FIRMWARE,
2477                                    "Cleaning up after CPU firmware fetch");
2478                         kfree(hdw->fw_buffer);
2479                         hdw->fw_buffer = NULL;
2480                         hdw->fw_size = 0;
2481                         /* Now release the CPU.  It will disconnect and
2482                            reconnect later. */
2483                         pvr2_hdw_cpureset_assert(hdw,0);
2484                         break;
2485                 }
2486
2487                 pvr2_trace(PVR2_TRACE_FIRMWARE,
2488                            "Preparing to suck out CPU firmware");
2489                 hdw->fw_size = 0x2000;
2490                 hdw->fw_buffer = kmalloc(hdw->fw_size,GFP_KERNEL);
2491                 if (!hdw->fw_buffer) {
2492                         hdw->fw_size = 0;
2493                         break;
2494                 }
2495
2496                 memset(hdw->fw_buffer,0,hdw->fw_size);
2497
2498                 /* We have to hold the CPU during firmware upload. */
2499                 pvr2_hdw_cpureset_assert(hdw,1);
2500
2501                 /* download the firmware from address 0000-1fff in 2048
2502                    (=0x800) bytes chunk. */
2503
2504                 pvr2_trace(PVR2_TRACE_FIRMWARE,"Grabbing CPU firmware");
2505                 pipe = usb_rcvctrlpipe(hdw->usb_dev, 0);
2506                 for(address = 0; address < hdw->fw_size; address += 0x800) {
2507                         ret = usb_control_msg(hdw->usb_dev,pipe,0xa0,0xc0,
2508                                               address,0,
2509                                               hdw->fw_buffer+address,0x800,HZ);
2510                         if (ret < 0) break;
2511                 }
2512
2513                 pvr2_trace(PVR2_TRACE_FIRMWARE,"Done grabbing CPU firmware");
2514
2515         } while (0); LOCK_GIVE(hdw->big_lock);
2516 }
2517
2518
2519 /* Return true if we're in a mode for retrieval CPU firmware */
2520 int pvr2_hdw_cpufw_get_enabled(struct pvr2_hdw *hdw)
2521 {
2522         return hdw->fw_buffer != 0;
2523 }
2524
2525
2526 int pvr2_hdw_cpufw_get(struct pvr2_hdw *hdw,unsigned int offs,
2527                        char *buf,unsigned int cnt)
2528 {
2529         int ret = -EINVAL;
2530         LOCK_TAKE(hdw->big_lock); do {
2531                 if (!buf) break;
2532                 if (!cnt) break;
2533
2534                 if (!hdw->fw_buffer) {
2535                         ret = -EIO;
2536                         break;
2537                 }
2538
2539                 if (offs >= hdw->fw_size) {
2540                         pvr2_trace(PVR2_TRACE_FIRMWARE,
2541                                    "Read firmware data offs=%d EOF",
2542                                    offs);
2543                         ret = 0;
2544                         break;
2545                 }
2546
2547                 if (offs + cnt > hdw->fw_size) cnt = hdw->fw_size - offs;
2548
2549                 memcpy(buf,hdw->fw_buffer+offs,cnt);
2550
2551                 pvr2_trace(PVR2_TRACE_FIRMWARE,
2552                            "Read firmware data offs=%d cnt=%d",
2553                            offs,cnt);
2554                 ret = cnt;
2555         } while (0); LOCK_GIVE(hdw->big_lock);
2556
2557         return ret;
2558 }
2559
2560
2561 int pvr2_hdw_v4l_get_minor_number(struct pvr2_hdw *hdw,
2562                                   enum pvr2_v4l_type index)
2563 {
2564         switch (index) {
2565         case pvr2_v4l_type_video: return hdw->v4l_minor_number_video;
2566         case pvr2_v4l_type_vbi: return hdw->v4l_minor_number_vbi;
2567         case pvr2_v4l_type_radio: return hdw->v4l_minor_number_radio;
2568         default: return -1;
2569         }
2570 }
2571
2572
2573 /* Store a v4l minor device number */
2574 void pvr2_hdw_v4l_store_minor_number(struct pvr2_hdw *hdw,
2575                                      enum pvr2_v4l_type index,int v)
2576 {
2577         switch (index) {
2578         case pvr2_v4l_type_video: hdw->v4l_minor_number_video = v;
2579         case pvr2_v4l_type_vbi: hdw->v4l_minor_number_vbi = v;
2580         case pvr2_v4l_type_radio: hdw->v4l_minor_number_radio = v;
2581         default: break;
2582         }
2583 }
2584
2585
2586 static void pvr2_ctl_write_complete(struct urb *urb)
2587 {
2588         struct pvr2_hdw *hdw = urb->context;
2589         hdw->ctl_write_pend_flag = 0;
2590         if (hdw->ctl_read_pend_flag) return;
2591         complete(&hdw->ctl_done);
2592 }
2593
2594
2595 static void pvr2_ctl_read_complete(struct urb *urb)
2596 {
2597         struct pvr2_hdw *hdw = urb->context;
2598         hdw->ctl_read_pend_flag = 0;
2599         if (hdw->ctl_write_pend_flag) return;
2600         complete(&hdw->ctl_done);
2601 }
2602
2603
2604 static void pvr2_ctl_timeout(unsigned long data)
2605 {
2606         struct pvr2_hdw *hdw = (struct pvr2_hdw *)data;
2607         if (hdw->ctl_write_pend_flag || hdw->ctl_read_pend_flag) {
2608                 hdw->ctl_timeout_flag = !0;
2609                 if (hdw->ctl_write_pend_flag)
2610                         usb_unlink_urb(hdw->ctl_write_urb);
2611                 if (hdw->ctl_read_pend_flag)
2612                         usb_unlink_urb(hdw->ctl_read_urb);
2613         }
2614 }
2615
2616
2617 /* Issue a command and get a response from the device.  This extended
2618    version includes a probe flag (which if set means that device errors
2619    should not be logged or treated as fatal) and a timeout in jiffies.
2620    This can be used to non-lethally probe the health of endpoint 1. */
2621 static int pvr2_send_request_ex(struct pvr2_hdw *hdw,
2622                                 unsigned int timeout,int probe_fl,
2623                                 void *write_data,unsigned int write_len,
2624                                 void *read_data,unsigned int read_len)
2625 {
2626         unsigned int idx;
2627         int status = 0;
2628         struct timer_list timer;
2629         if (!hdw->ctl_lock_held) {
2630                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2631                            "Attempted to execute control transfer"
2632                            " without lock!!");
2633                 return -EDEADLK;
2634         }
2635         if ((!hdw->flag_ok) && !probe_fl) {
2636                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2637                            "Attempted to execute control transfer"
2638                            " when device not ok");
2639                 return -EIO;
2640         }
2641         if (!(hdw->ctl_read_urb && hdw->ctl_write_urb)) {
2642                 if (!probe_fl) {
2643                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2644                                    "Attempted to execute control transfer"
2645                                    " when USB is disconnected");
2646                 }
2647                 return -ENOTTY;
2648         }
2649
2650         /* Ensure that we have sane parameters */
2651         if (!write_data) write_len = 0;
2652         if (!read_data) read_len = 0;
2653         if (write_len > PVR2_CTL_BUFFSIZE) {
2654                 pvr2_trace(
2655                         PVR2_TRACE_ERROR_LEGS,
2656                         "Attempted to execute %d byte"
2657                         " control-write transfer (limit=%d)",
2658                         write_len,PVR2_CTL_BUFFSIZE);
2659                 return -EINVAL;
2660         }
2661         if (read_len > PVR2_CTL_BUFFSIZE) {
2662                 pvr2_trace(
2663                         PVR2_TRACE_ERROR_LEGS,
2664                         "Attempted to execute %d byte"
2665                         " control-read transfer (limit=%d)",
2666                         write_len,PVR2_CTL_BUFFSIZE);
2667                 return -EINVAL;
2668         }
2669         if ((!write_len) && (!read_len)) {
2670                 pvr2_trace(
2671                         PVR2_TRACE_ERROR_LEGS,
2672                         "Attempted to execute null control transfer?");
2673                 return -EINVAL;
2674         }
2675
2676
2677         hdw->cmd_debug_state = 1;
2678         if (write_len) {
2679                 hdw->cmd_debug_code = ((unsigned char *)write_data)[0];
2680         } else {
2681                 hdw->cmd_debug_code = 0;
2682         }
2683         hdw->cmd_debug_write_len = write_len;
2684         hdw->cmd_debug_read_len = read_len;
2685
2686         /* Initialize common stuff */
2687         init_completion(&hdw->ctl_done);
2688         hdw->ctl_timeout_flag = 0;
2689         hdw->ctl_write_pend_flag = 0;
2690         hdw->ctl_read_pend_flag = 0;
2691         init_timer(&timer);
2692         timer.expires = jiffies + timeout;
2693         timer.data = (unsigned long)hdw;
2694         timer.function = pvr2_ctl_timeout;
2695
2696         if (write_len) {
2697                 hdw->cmd_debug_state = 2;
2698                 /* Transfer write data to internal buffer */
2699                 for (idx = 0; idx < write_len; idx++) {
2700                         hdw->ctl_write_buffer[idx] =
2701                                 ((unsigned char *)write_data)[idx];
2702                 }
2703                 /* Initiate a write request */
2704                 usb_fill_bulk_urb(hdw->ctl_write_urb,
2705                                   hdw->usb_dev,
2706                                   usb_sndbulkpipe(hdw->usb_dev,
2707                                                   PVR2_CTL_WRITE_ENDPOINT),
2708                                   hdw->ctl_write_buffer,
2709                                   write_len,
2710                                   pvr2_ctl_write_complete,
2711                                   hdw);
2712                 hdw->ctl_write_urb->actual_length = 0;
2713                 hdw->ctl_write_pend_flag = !0;
2714                 status = usb_submit_urb(hdw->ctl_write_urb,GFP_KERNEL);
2715                 if (status < 0) {
2716                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2717                                    "Failed to submit write-control"
2718                                    " URB status=%d",status);
2719                         hdw->ctl_write_pend_flag = 0;
2720                         goto done;
2721                 }
2722         }
2723
2724         if (read_len) {
2725                 hdw->cmd_debug_state = 3;
2726                 memset(hdw->ctl_read_buffer,0x43,read_len);
2727                 /* Initiate a read request */
2728                 usb_fill_bulk_urb(hdw->ctl_read_urb,
2729                                   hdw->usb_dev,
2730                                   usb_rcvbulkpipe(hdw->usb_dev,
2731                                                   PVR2_CTL_READ_ENDPOINT),
2732                                   hdw->ctl_read_buffer,
2733                                   read_len,
2734                                   pvr2_ctl_read_complete,
2735                                   hdw);
2736                 hdw->ctl_read_urb->actual_length = 0;
2737                 hdw->ctl_read_pend_flag = !0;
2738                 status = usb_submit_urb(hdw->ctl_read_urb,GFP_KERNEL);
2739                 if (status < 0) {
2740                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2741                                    "Failed to submit read-control"
2742                                    " URB status=%d",status);
2743                         hdw->ctl_read_pend_flag = 0;
2744                         goto done;
2745                 }
2746         }
2747
2748         /* Start timer */
2749         add_timer(&timer);
2750
2751         /* Now wait for all I/O to complete */
2752         hdw->cmd_debug_state = 4;
2753         while (hdw->ctl_write_pend_flag || hdw->ctl_read_pend_flag) {
2754                 wait_for_completion(&hdw->ctl_done);
2755         }
2756         hdw->cmd_debug_state = 5;
2757
2758         /* Stop timer */
2759         del_timer_sync(&timer);
2760
2761         hdw->cmd_debug_state = 6;
2762         status = 0;
2763
2764         if (hdw->ctl_timeout_flag) {
2765                 status = -ETIMEDOUT;
2766                 if (!probe_fl) {
2767                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2768                                    "Timed out control-write");
2769                 }
2770                 goto done;
2771         }
2772
2773         if (write_len) {
2774                 /* Validate results of write request */
2775                 if ((hdw->ctl_write_urb->status != 0) &&
2776                     (hdw->ctl_write_urb->status != -ENOENT) &&
2777                     (hdw->ctl_write_urb->status != -ESHUTDOWN) &&
2778                     (hdw->ctl_write_urb->status != -ECONNRESET)) {
2779                         /* USB subsystem is reporting some kind of failure
2780                            on the write */
2781                         status = hdw->ctl_write_urb->status;
2782                         if (!probe_fl) {
2783                                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2784                                            "control-write URB failure,"
2785                                            " status=%d",
2786                                            status);
2787                         }
2788                         goto done;
2789                 }
2790                 if (hdw->ctl_write_urb->actual_length < write_len) {
2791                         /* Failed to write enough data */
2792                         status = -EIO;
2793                         if (!probe_fl) {
2794                                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2795                                            "control-write URB short,"
2796                                            " expected=%d got=%d",
2797                                            write_len,
2798                                            hdw->ctl_write_urb->actual_length);
2799                         }
2800                         goto done;
2801                 }
2802         }
2803         if (read_len) {
2804                 /* Validate results of read request */
2805                 if ((hdw->ctl_read_urb->status != 0) &&
2806                     (hdw->ctl_read_urb->status != -ENOENT) &&
2807                     (hdw->ctl_read_urb->status != -ESHUTDOWN) &&
2808                     (hdw->ctl_read_urb->status != -ECONNRESET)) {
2809                         /* USB subsystem is reporting some kind of failure
2810                            on the read */
2811                         status = hdw->ctl_read_urb->status;
2812                         if (!probe_fl) {
2813                                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2814                                            "control-read URB failure,"
2815                                            " status=%d",
2816                                            status);
2817                         }
2818                         goto done;
2819                 }
2820                 if (hdw->ctl_read_urb->actual_length < read_len) {
2821                         /* Failed to read enough data */
2822                         status = -EIO;
2823                         if (!probe_fl) {
2824                                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2825                                            "control-read URB short,"
2826                                            " expected=%d got=%d",
2827                                            read_len,
2828                                            hdw->ctl_read_urb->actual_length);
2829                         }
2830                         goto done;
2831                 }
2832                 /* Transfer retrieved data out from internal buffer */
2833                 for (idx = 0; idx < read_len; idx++) {
2834                         ((unsigned char *)read_data)[idx] =
2835                                 hdw->ctl_read_buffer[idx];
2836                 }
2837         }
2838
2839  done:
2840
2841         hdw->cmd_debug_state = 0;
2842         if ((status < 0) && (!probe_fl)) {
2843                 pvr2_hdw_render_useless_unlocked(hdw);
2844         }
2845         return status;
2846 }
2847
2848
2849 int pvr2_send_request(struct pvr2_hdw *hdw,
2850                       void *write_data,unsigned int write_len,
2851                       void *read_data,unsigned int read_len)
2852 {
2853         return pvr2_send_request_ex(hdw,HZ*4,0,
2854                                     write_data,write_len,
2855                                     read_data,read_len);
2856 }
2857
2858 int pvr2_write_register(struct pvr2_hdw *hdw, u16 reg, u32 data)
2859 {
2860         int ret;
2861
2862         LOCK_TAKE(hdw->ctl_lock);
2863
2864         hdw->cmd_buffer[0] = 0x04;  /* write register prefix */
2865         PVR2_DECOMPOSE_LE(hdw->cmd_buffer,1,data);
2866         hdw->cmd_buffer[5] = 0;
2867         hdw->cmd_buffer[6] = (reg >> 8) & 0xff;
2868         hdw->cmd_buffer[7] = reg & 0xff;
2869
2870
2871         ret = pvr2_send_request(hdw, hdw->cmd_buffer, 8, hdw->cmd_buffer, 0);
2872
2873         LOCK_GIVE(hdw->ctl_lock);
2874
2875         return ret;
2876 }
2877
2878
2879 static int pvr2_read_register(struct pvr2_hdw *hdw, u16 reg, u32 *data)
2880 {
2881         int ret = 0;
2882
2883         LOCK_TAKE(hdw->ctl_lock);
2884
2885         hdw->cmd_buffer[0] = 0x05;  /* read register prefix */
2886         hdw->cmd_buffer[1] = 0;
2887         hdw->cmd_buffer[2] = 0;
2888         hdw->cmd_buffer[3] = 0;
2889         hdw->cmd_buffer[4] = 0;
2890         hdw->cmd_buffer[5] = 0;
2891         hdw->cmd_buffer[6] = (reg >> 8) & 0xff;
2892         hdw->cmd_buffer[7] = reg & 0xff;
2893
2894         ret |= pvr2_send_request(hdw, hdw->cmd_buffer, 8, hdw->cmd_buffer, 4);
2895         *data = PVR2_COMPOSE_LE(hdw->cmd_buffer,0);
2896
2897         LOCK_GIVE(hdw->ctl_lock);
2898
2899         return ret;
2900 }
2901
2902
2903 static int pvr2_write_u16(struct pvr2_hdw *hdw, u16 data, int res)
2904 {
2905         int ret;
2906
2907         LOCK_TAKE(hdw->ctl_lock);
2908
2909         hdw->cmd_buffer[0] = (data >> 8) & 0xff;
2910         hdw->cmd_buffer[1] = data & 0xff;
2911
2912         ret = pvr2_send_request(hdw, hdw->cmd_buffer, 2, hdw->cmd_buffer, res);
2913
2914         LOCK_GIVE(hdw->ctl_lock);
2915
2916         return ret;
2917 }
2918
2919
2920 static int pvr2_write_u8(struct pvr2_hdw *hdw, u8 data, int res)
2921 {
2922         int ret;
2923
2924         LOCK_TAKE(hdw->ctl_lock);
2925
2926         hdw->cmd_buffer[0] = data;
2927
2928         ret = pvr2_send_request(hdw, hdw->cmd_buffer, 1, hdw->cmd_buffer, res);
2929
2930         LOCK_GIVE(hdw->ctl_lock);
2931
2932         return ret;
2933 }
2934
2935
2936 static void pvr2_hdw_render_useless_unlocked(struct pvr2_hdw *hdw)
2937 {
2938         if (!hdw->flag_ok) return;
2939         pvr2_trace(PVR2_TRACE_INIT,"render_useless");
2940         hdw->flag_ok = 0;
2941         if (hdw->vid_stream) {
2942                 pvr2_stream_setup(hdw->vid_stream,NULL,0,0);
2943         }
2944         hdw->flag_streaming_enabled = 0;
2945         hdw->subsys_enabled_mask = 0;
2946 }
2947
2948
2949 void pvr2_hdw_render_useless(struct pvr2_hdw *hdw)
2950 {
2951         LOCK_TAKE(hdw->ctl_lock);
2952         pvr2_hdw_render_useless_unlocked(hdw);
2953         LOCK_GIVE(hdw->ctl_lock);
2954 }
2955
2956
2957 void pvr2_hdw_device_reset(struct pvr2_hdw *hdw)
2958 {
2959         int ret;
2960         pvr2_trace(PVR2_TRACE_INIT,"Performing a device reset...");
2961         ret = usb_lock_device_for_reset(hdw->usb_dev,NULL);
2962         if (ret == 1) {
2963                 ret = usb_reset_device(hdw->usb_dev);
2964                 usb_unlock_device(hdw->usb_dev);
2965         } else {
2966                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2967                            "Failed to lock USB device ret=%d",ret);
2968         }
2969         if (init_pause_msec) {
2970                 pvr2_trace(PVR2_TRACE_INFO,
2971                            "Waiting %u msec for hardware to settle",
2972                            init_pause_msec);
2973                 msleep(init_pause_msec);
2974         }
2975
2976 }
2977
2978
2979 void pvr2_hdw_cpureset_assert(struct pvr2_hdw *hdw,int val)
2980 {
2981         char da[1];
2982         unsigned int pipe;
2983         int ret;
2984
2985         if (!hdw->usb_dev) return;
2986
2987         pvr2_trace(PVR2_TRACE_INIT,"cpureset_assert(%d)",val);
2988
2989         da[0] = val ? 0x01 : 0x00;
2990
2991         /* Write the CPUCS register on the 8051.  The lsb of the register
2992            is the reset bit; a 1 asserts reset while a 0 clears it. */
2993         pipe = usb_sndctrlpipe(hdw->usb_dev, 0);
2994         ret = usb_control_msg(hdw->usb_dev,pipe,0xa0,0x40,0xe600,0,da,1,HZ);
2995         if (ret < 0) {
2996                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2997                            "cpureset_assert(%d) error=%d",val,ret);
2998                 pvr2_hdw_render_useless(hdw);
2999         }
3000 }
3001
3002
3003 int pvr2_hdw_cmd_deep_reset(struct pvr2_hdw *hdw)
3004 {
3005         int status;
3006         LOCK_TAKE(hdw->ctl_lock); do {
3007                 pvr2_trace(PVR2_TRACE_INIT,"Requesting uproc hard reset");
3008                 hdw->flag_ok = !0;
3009                 hdw->cmd_buffer[0] = 0xdd;
3010                 status = pvr2_send_request(hdw,hdw->cmd_buffer,1,NULL,0);
3011         } while (0); LOCK_GIVE(hdw->ctl_lock);
3012         return status;
3013 }
3014
3015
3016 int pvr2_hdw_cmd_powerup(struct pvr2_hdw *hdw)
3017 {
3018         int status;
3019         LOCK_TAKE(hdw->ctl_lock); do {
3020                 pvr2_trace(PVR2_TRACE_INIT,"Requesting powerup");
3021                 hdw->cmd_buffer[0] = 0xde;
3022                 status = pvr2_send_request(hdw,hdw->cmd_buffer,1,NULL,0);
3023         } while (0); LOCK_GIVE(hdw->ctl_lock);
3024         return status;
3025 }
3026
3027
3028 int pvr2_hdw_cmd_decoder_reset(struct pvr2_hdw *hdw)
3029 {
3030         if (!hdw->decoder_ctrl) {
3031                 pvr2_trace(PVR2_TRACE_INIT,
3032                            "Unable to reset decoder: nothing attached");
3033                 return -ENOTTY;
3034         }
3035
3036         if (!hdw->decoder_ctrl->force_reset) {
3037                 pvr2_trace(PVR2_TRACE_INIT,
3038                            "Unable to reset decoder: not implemented");
3039                 return -ENOTTY;
3040         }
3041
3042         pvr2_trace(PVR2_TRACE_INIT,
3043                    "Requesting decoder reset");
3044         hdw->decoder_ctrl->force_reset(hdw->decoder_ctrl->ctxt);
3045         return 0;
3046 }
3047
3048
3049 /* Stop / start video stream transport */
3050 static int pvr2_hdw_cmd_usbstream(struct pvr2_hdw *hdw,int runFl)
3051 {
3052         int status;
3053         LOCK_TAKE(hdw->ctl_lock); do {
3054                 hdw->cmd_buffer[0] = (runFl ? 0x36 : 0x37);
3055                 status = pvr2_send_request(hdw,hdw->cmd_buffer,1,NULL,0);
3056         } while (0); LOCK_GIVE(hdw->ctl_lock);
3057         if (!status) {
3058                 hdw->subsys_enabled_mask =
3059                         ((hdw->subsys_enabled_mask &
3060                           ~(1<<PVR2_SUBSYS_B_USBSTREAM_RUN)) |
3061                          (runFl ? (1<<PVR2_SUBSYS_B_USBSTREAM_RUN) : 0));
3062         }
3063         return status;
3064 }
3065
3066
3067 void pvr2_hdw_get_debug_info(const struct pvr2_hdw *hdw,
3068                              struct pvr2_hdw_debug_info *ptr)
3069 {
3070         ptr->big_lock_held = hdw->big_lock_held;
3071         ptr->ctl_lock_held = hdw->ctl_lock_held;
3072         ptr->flag_ok = hdw->flag_ok;
3073         ptr->flag_disconnected = hdw->flag_disconnected;
3074         ptr->flag_init_ok = hdw->flag_init_ok;
3075         ptr->flag_streaming_enabled = hdw->flag_streaming_enabled;
3076         ptr->subsys_flags = hdw->subsys_enabled_mask;
3077         ptr->cmd_debug_state = hdw->cmd_debug_state;
3078         ptr->cmd_code = hdw->cmd_debug_code;
3079         ptr->cmd_debug_write_len = hdw->cmd_debug_write_len;
3080         ptr->cmd_debug_read_len = hdw->cmd_debug_read_len;
3081         ptr->cmd_debug_timeout = hdw->ctl_timeout_flag;
3082         ptr->cmd_debug_write_pend = hdw->ctl_write_pend_flag;
3083         ptr->cmd_debug_read_pend = hdw->ctl_read_pend_flag;
3084         ptr->cmd_debug_rstatus = hdw->ctl_read_urb->status;
3085         ptr->cmd_debug_wstatus = hdw->ctl_read_urb->status;
3086 }
3087
3088
3089 int pvr2_hdw_gpio_get_dir(struct pvr2_hdw *hdw,u32 *dp)
3090 {
3091         return pvr2_read_register(hdw,PVR2_GPIO_DIR,dp);
3092 }
3093
3094
3095 int pvr2_hdw_gpio_get_out(struct pvr2_hdw *hdw,u32 *dp)
3096 {
3097         return pvr2_read_register(hdw,PVR2_GPIO_OUT,dp);
3098 }
3099
3100
3101 int pvr2_hdw_gpio_get_in(struct pvr2_hdw *hdw,u32 *dp)
3102 {
3103         return pvr2_read_register(hdw,PVR2_GPIO_IN,dp);
3104 }
3105
3106
3107 int pvr2_hdw_gpio_chg_dir(struct pvr2_hdw *hdw,u32 msk,u32 val)
3108 {
3109         u32 cval,nval;
3110         int ret;
3111         if (~msk) {
3112                 ret = pvr2_read_register(hdw,PVR2_GPIO_DIR,&cval);
3113                 if (ret) return ret;
3114                 nval = (cval & ~msk) | (val & msk);
3115                 pvr2_trace(PVR2_TRACE_GPIO,
3116                            "GPIO direction changing 0x%x:0x%x"
3117                            " from 0x%x to 0x%x",
3118                            msk,val,cval,nval);
3119         } else {
3120                 nval = val;
3121                 pvr2_trace(PVR2_TRACE_GPIO,
3122                            "GPIO direction changing to 0x%x",nval);
3123         }
3124         return pvr2_write_register(hdw,PVR2_GPIO_DIR,nval);
3125 }
3126
3127
3128 int pvr2_hdw_gpio_chg_out(struct pvr2_hdw *hdw,u32 msk,u32 val)
3129 {
3130         u32 cval,nval;
3131         int ret;
3132         if (~msk) {
3133                 ret = pvr2_read_register(hdw,PVR2_GPIO_OUT,&cval);
3134                 if (ret) return ret;
3135                 nval = (cval & ~msk) | (val & msk);
3136                 pvr2_trace(PVR2_TRACE_GPIO,
3137                            "GPIO output changing 0x%x:0x%x from 0x%x to 0x%x",
3138                            msk,val,cval,nval);
3139         } else {
3140                 nval = val;
3141                 pvr2_trace(PVR2_TRACE_GPIO,
3142                            "GPIO output changing to 0x%x",nval);
3143         }
3144         return pvr2_write_register(hdw,PVR2_GPIO_OUT,nval);
3145 }
3146
3147
3148 /* Find I2C address of eeprom */
3149 static int pvr2_hdw_get_eeprom_addr(struct pvr2_hdw *hdw)
3150 {
3151         int result;
3152         LOCK_TAKE(hdw->ctl_lock); do {
3153                 hdw->cmd_buffer[0] = 0xeb;
3154                 result = pvr2_send_request(hdw,
3155                                            hdw->cmd_buffer,1,
3156                                            hdw->cmd_buffer,1);
3157                 if (result < 0) break;
3158                 result = hdw->cmd_buffer[0];
3159         } while(0); LOCK_GIVE(hdw->ctl_lock);
3160         return result;
3161 }
3162
3163
3164 int pvr2_hdw_register_access(struct pvr2_hdw *hdw,
3165                              u32 chip_id,unsigned long reg_id,
3166                              int setFl,u32 *val_ptr)
3167 {
3168 #ifdef CONFIG_VIDEO_ADV_DEBUG
3169         struct list_head *item;
3170         struct pvr2_i2c_client *cp;
3171         struct v4l2_register req;
3172         int stat = 0;
3173         int okFl = 0;
3174
3175         req.i2c_id = chip_id;
3176         req.reg = reg_id;
3177         if (setFl) req.val = *val_ptr;
3178         mutex_lock(&hdw->i2c_list_lock); do {
3179                 list_for_each(item,&hdw->i2c_clients) {
3180                         cp = list_entry(item,struct pvr2_i2c_client,list);
3181                         if (cp->client->driver->id != chip_id) continue;
3182                         stat = pvr2_i2c_client_cmd(
3183                                 cp,(setFl ? VIDIOC_INT_S_REGISTER :
3184                                     VIDIOC_INT_G_REGISTER),&req);
3185                         if (!setFl) *val_ptr = req.val;
3186                         okFl = !0;
3187                         break;
3188                 }
3189         } while (0); mutex_unlock(&hdw->i2c_list_lock);
3190         if (okFl) {
3191                 return stat;
3192         }
3193         return -EINVAL;
3194 #else
3195         return -ENOSYS;
3196 #endif
3197 }
3198
3199
3200 /*
3201   Stuff for Emacs to see, in order to encourage consistent editing style:
3202   *** Local Variables: ***
3203   *** mode: c ***
3204   *** fill-column: 75 ***
3205   *** tab-width: 8 ***
3206   *** c-basic-offset: 8 ***
3207   *** End: ***
3208   */