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