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