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