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