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