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