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