V4L/DVB (6695): pvrusb2: Implement functions to pass descriptive hardware info
[safe/jmp/linux-2.6] / drivers / media / video / pvrusb2 / pvrusb2-hdw.c
1 /*
2  *
3  *  $Id$
4  *
5  *  Copyright (C) 2005 Mike Isely <isely@pobox.com>
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  */
21
22 #include <linux/errno.h>
23 #include <linux/string.h>
24 #include <linux/slab.h>
25 #include <linux/firmware.h>
26 #include <linux/videodev2.h>
27 #include <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 #include "pvrusb2-fx2-cmd.h"
40
41 #define TV_MIN_FREQ     55250000L
42 #define TV_MAX_FREQ    850000000L
43
44 static struct pvr2_hdw *unit_pointers[PVR_NUM] = {[ 0 ... PVR_NUM-1 ] = NULL};
45 static DEFINE_MUTEX(pvr2_unit_mtx);
46
47 static int ctlchg = 0;
48 static int initusbreset = 1;
49 static int procreload = 0;
50 static int tuner[PVR_NUM] = { [0 ... PVR_NUM-1] = -1 };
51 static int tolerance[PVR_NUM] = { [0 ... PVR_NUM-1] = 0 };
52 static int video_std[PVR_NUM] = { [0 ... PVR_NUM-1] = 0 };
53 static int init_pause_msec = 0;
54
55 module_param(ctlchg, int, S_IRUGO|S_IWUSR);
56 MODULE_PARM_DESC(ctlchg, "0=optimize ctl change 1=always accept new ctl value");
57 module_param(init_pause_msec, int, S_IRUGO|S_IWUSR);
58 MODULE_PARM_DESC(init_pause_msec, "hardware initialization settling delay");
59 module_param(initusbreset, int, S_IRUGO|S_IWUSR);
60 MODULE_PARM_DESC(initusbreset, "Do USB reset device on probe");
61 module_param(procreload, int, S_IRUGO|S_IWUSR);
62 MODULE_PARM_DESC(procreload,
63                  "Attempt init failure recovery with firmware reload");
64 module_param_array(tuner,    int, NULL, 0444);
65 MODULE_PARM_DESC(tuner,"specify installed tuner type");
66 module_param_array(video_std,    int, NULL, 0444);
67 MODULE_PARM_DESC(video_std,"specify initial video standard");
68 module_param_array(tolerance,    int, NULL, 0444);
69 MODULE_PARM_DESC(tolerance,"specify stream error tolerance");
70
71 #define PVR2_CTL_WRITE_ENDPOINT  0x01
72 #define PVR2_CTL_READ_ENDPOINT   0x81
73
74 #define PVR2_GPIO_IN 0x9008
75 #define PVR2_GPIO_OUT 0x900c
76 #define PVR2_GPIO_DIR 0x9020
77
78 #define trace_firmware(...) pvr2_trace(PVR2_TRACE_FIRMWARE,__VA_ARGS__)
79
80 #define PVR2_FIRMWARE_ENDPOINT   0x02
81
82 /* size of a firmware chunk */
83 #define FIRMWARE_CHUNK_SIZE 0x2000
84
85 /* Define the list of additional controls we'll dynamically construct based
86    on query of the cx2341x module. */
87 struct pvr2_mpeg_ids {
88         const char *strid;
89         int id;
90 };
91 static const struct pvr2_mpeg_ids mpeg_ids[] = {
92         {
93                 .strid = "audio_layer",
94                 .id = V4L2_CID_MPEG_AUDIO_ENCODING,
95         },{
96                 .strid = "audio_bitrate",
97                 .id = V4L2_CID_MPEG_AUDIO_L2_BITRATE,
98         },{
99                 /* Already using audio_mode elsewhere :-( */
100                 .strid = "mpeg_audio_mode",
101                 .id = V4L2_CID_MPEG_AUDIO_MODE,
102         },{
103                 .strid = "mpeg_audio_mode_extension",
104                 .id = V4L2_CID_MPEG_AUDIO_MODE_EXTENSION,
105         },{
106                 .strid = "audio_emphasis",
107                 .id = V4L2_CID_MPEG_AUDIO_EMPHASIS,
108         },{
109                 .strid = "audio_crc",
110                 .id = V4L2_CID_MPEG_AUDIO_CRC,
111         },{
112                 .strid = "video_aspect",
113                 .id = V4L2_CID_MPEG_VIDEO_ASPECT,
114         },{
115                 .strid = "video_b_frames",
116                 .id = V4L2_CID_MPEG_VIDEO_B_FRAMES,
117         },{
118                 .strid = "video_gop_size",
119                 .id = V4L2_CID_MPEG_VIDEO_GOP_SIZE,
120         },{
121                 .strid = "video_gop_closure",
122                 .id = V4L2_CID_MPEG_VIDEO_GOP_CLOSURE,
123         },{
124                 .strid = "video_bitrate_mode",
125                 .id = V4L2_CID_MPEG_VIDEO_BITRATE_MODE,
126         },{
127                 .strid = "video_bitrate",
128                 .id = V4L2_CID_MPEG_VIDEO_BITRATE,
129         },{
130                 .strid = "video_bitrate_peak",
131                 .id = V4L2_CID_MPEG_VIDEO_BITRATE_PEAK,
132         },{
133                 .strid = "video_temporal_decimation",
134                 .id = V4L2_CID_MPEG_VIDEO_TEMPORAL_DECIMATION,
135         },{
136                 .strid = "stream_type",
137                 .id = V4L2_CID_MPEG_STREAM_TYPE,
138         },{
139                 .strid = "video_spatial_filter_mode",
140                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER_MODE,
141         },{
142                 .strid = "video_spatial_filter",
143                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_SPATIAL_FILTER,
144         },{
145                 .strid = "video_luma_spatial_filter_type",
146                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_SPATIAL_FILTER_TYPE,
147         },{
148                 .strid = "video_chroma_spatial_filter_type",
149                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_SPATIAL_FILTER_TYPE,
150         },{
151                 .strid = "video_temporal_filter_mode",
152                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER_MODE,
153         },{
154                 .strid = "video_temporal_filter",
155                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_TEMPORAL_FILTER,
156         },{
157                 .strid = "video_median_filter_type",
158                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_MEDIAN_FILTER_TYPE,
159         },{
160                 .strid = "video_luma_median_filter_top",
161                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_TOP,
162         },{
163                 .strid = "video_luma_median_filter_bottom",
164                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_LUMA_MEDIAN_FILTER_BOTTOM,
165         },{
166                 .strid = "video_chroma_median_filter_top",
167                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_TOP,
168         },{
169                 .strid = "video_chroma_median_filter_bottom",
170                 .id = V4L2_CID_MPEG_CX2341X_VIDEO_CHROMA_MEDIAN_FILTER_BOTTOM,
171         }
172 };
173 #define MPEGDEF_COUNT ARRAY_SIZE(mpeg_ids)
174
175
176 static const char *control_values_srate[] = {
177         [V4L2_MPEG_AUDIO_SAMPLING_FREQ_44100]   = "44.1 kHz",
178         [V4L2_MPEG_AUDIO_SAMPLING_FREQ_48000]   = "48 kHz",
179         [V4L2_MPEG_AUDIO_SAMPLING_FREQ_32000]   = "32 kHz",
180 };
181
182
183
184 static const char *control_values_input[] = {
185         [PVR2_CVAL_INPUT_TV]        = "television",  /*xawtv needs this name*/
186         [PVR2_CVAL_INPUT_RADIO]     = "radio",
187         [PVR2_CVAL_INPUT_SVIDEO]    = "s-video",
188         [PVR2_CVAL_INPUT_COMPOSITE] = "composite",
189 };
190
191
192 static const char *control_values_audiomode[] = {
193         [V4L2_TUNER_MODE_MONO]   = "Mono",
194         [V4L2_TUNER_MODE_STEREO] = "Stereo",
195         [V4L2_TUNER_MODE_LANG1]  = "Lang1",
196         [V4L2_TUNER_MODE_LANG2]  = "Lang2",
197         [V4L2_TUNER_MODE_LANG1_LANG2] = "Lang1+Lang2",
198 };
199
200
201 static const char *control_values_hsm[] = {
202         [PVR2_CVAL_HSM_FAIL] = "Fail",
203         [PVR2_CVAL_HSM_HIGH] = "High",
204         [PVR2_CVAL_HSM_FULL] = "Full",
205 };
206
207
208 static const char *pvr2_state_names[] = {
209         [PVR2_STATE_NONE] =    "none",
210         [PVR2_STATE_DEAD] =    "dead",
211         [PVR2_STATE_COLD] =    "cold",
212         [PVR2_STATE_WARM] =    "warm",
213         [PVR2_STATE_ERROR] =   "error",
214         [PVR2_STATE_READY] =   "ready",
215         [PVR2_STATE_RUN] =     "run",
216 };
217
218
219 static void pvr2_hdw_state_sched(struct pvr2_hdw *);
220 static int pvr2_hdw_state_eval(struct pvr2_hdw *);
221 static void pvr2_hdw_set_cur_freq(struct pvr2_hdw *,unsigned long);
222 static void pvr2_hdw_worker_i2c(struct work_struct *work);
223 static void pvr2_hdw_worker_poll(struct work_struct *work);
224 static void pvr2_hdw_worker_init(struct work_struct *work);
225 static int pvr2_hdw_wait(struct pvr2_hdw *,int state);
226 static int pvr2_hdw_untrip_unlocked(struct pvr2_hdw *);
227 static void pvr2_hdw_state_log_state(struct pvr2_hdw *);
228 static int pvr2_hdw_cmd_usbstream(struct pvr2_hdw *hdw,int runFl);
229 static int pvr2_hdw_commit_setup(struct pvr2_hdw *hdw);
230 static int pvr2_hdw_get_eeprom_addr(struct pvr2_hdw *hdw);
231 static void pvr2_hdw_internal_find_stdenum(struct pvr2_hdw *hdw);
232 static void pvr2_hdw_internal_set_std_avail(struct pvr2_hdw *hdw);
233 static void pvr2_hdw_quiescent_timeout(unsigned long);
234 static void pvr2_hdw_encoder_wait_timeout(unsigned long);
235 static int pvr2_send_request_ex(struct pvr2_hdw *hdw,
236                                 unsigned int timeout,int probe_fl,
237                                 void *write_data,unsigned int write_len,
238                                 void *read_data,unsigned int read_len);
239
240
241 static void trace_stbit(const char *name,int val)
242 {
243         pvr2_trace(PVR2_TRACE_STBITS,
244                    "State bit %s <-- %s",
245                    name,(val ? "true" : "false"));
246 }
247
248 static int ctrl_channelfreq_get(struct pvr2_ctrl *cptr,int *vp)
249 {
250         struct pvr2_hdw *hdw = cptr->hdw;
251         if ((hdw->freqProgSlot > 0) && (hdw->freqProgSlot <= FREQTABLE_SIZE)) {
252                 *vp = hdw->freqTable[hdw->freqProgSlot-1];
253         } else {
254                 *vp = 0;
255         }
256         return 0;
257 }
258
259 static int ctrl_channelfreq_set(struct pvr2_ctrl *cptr,int m,int v)
260 {
261         struct pvr2_hdw *hdw = cptr->hdw;
262         unsigned int slotId = hdw->freqProgSlot;
263         if ((slotId > 0) && (slotId <= FREQTABLE_SIZE)) {
264                 hdw->freqTable[slotId-1] = v;
265                 /* Handle side effects correctly - if we're tuned to this
266                    slot, then forgot the slot id relation since the stored
267                    frequency has been changed. */
268                 if (hdw->freqSelector) {
269                         if (hdw->freqSlotRadio == slotId) {
270                                 hdw->freqSlotRadio = 0;
271                         }
272                 } else {
273                         if (hdw->freqSlotTelevision == slotId) {
274                                 hdw->freqSlotTelevision = 0;
275                         }
276                 }
277         }
278         return 0;
279 }
280
281 static int ctrl_channelprog_get(struct pvr2_ctrl *cptr,int *vp)
282 {
283         *vp = cptr->hdw->freqProgSlot;
284         return 0;
285 }
286
287 static int ctrl_channelprog_set(struct pvr2_ctrl *cptr,int m,int v)
288 {
289         struct pvr2_hdw *hdw = cptr->hdw;
290         if ((v >= 0) && (v <= FREQTABLE_SIZE)) {
291                 hdw->freqProgSlot = v;
292         }
293         return 0;
294 }
295
296 static int ctrl_channel_get(struct pvr2_ctrl *cptr,int *vp)
297 {
298         struct pvr2_hdw *hdw = cptr->hdw;
299         *vp = hdw->freqSelector ? hdw->freqSlotRadio : hdw->freqSlotTelevision;
300         return 0;
301 }
302
303 static int ctrl_channel_set(struct pvr2_ctrl *cptr,int m,int slotId)
304 {
305         unsigned freq = 0;
306         struct pvr2_hdw *hdw = cptr->hdw;
307         if ((slotId < 0) || (slotId > FREQTABLE_SIZE)) return 0;
308         if (slotId > 0) {
309                 freq = hdw->freqTable[slotId-1];
310                 if (!freq) return 0;
311                 pvr2_hdw_set_cur_freq(hdw,freq);
312         }
313         if (hdw->freqSelector) {
314                 hdw->freqSlotRadio = slotId;
315         } else {
316                 hdw->freqSlotTelevision = slotId;
317         }
318         return 0;
319 }
320
321 static int ctrl_freq_get(struct pvr2_ctrl *cptr,int *vp)
322 {
323         *vp = pvr2_hdw_get_cur_freq(cptr->hdw);
324         return 0;
325 }
326
327 static int ctrl_freq_is_dirty(struct pvr2_ctrl *cptr)
328 {
329         return cptr->hdw->freqDirty != 0;
330 }
331
332 static void ctrl_freq_clear_dirty(struct pvr2_ctrl *cptr)
333 {
334         cptr->hdw->freqDirty = 0;
335 }
336
337 static int ctrl_freq_set(struct pvr2_ctrl *cptr,int m,int v)
338 {
339         pvr2_hdw_set_cur_freq(cptr->hdw,v);
340         return 0;
341 }
342
343 static int ctrl_vres_max_get(struct pvr2_ctrl *cptr,int *vp)
344 {
345         /* Actual maximum depends on the video standard in effect. */
346         if (cptr->hdw->std_mask_cur & V4L2_STD_525_60) {
347                 *vp = 480;
348         } else {
349                 *vp = 576;
350         }
351         return 0;
352 }
353
354 static int ctrl_vres_min_get(struct pvr2_ctrl *cptr,int *vp)
355 {
356         /* Actual minimum depends on device digitizer type. */
357         if (cptr->hdw->hdw_desc->flag_has_cx25840) {
358                 *vp = 75;
359         } else {
360                 *vp = 17;
361         }
362         return 0;
363 }
364
365 static int ctrl_get_input(struct pvr2_ctrl *cptr,int *vp)
366 {
367         *vp = cptr->hdw->input_val;
368         return 0;
369 }
370
371 static int ctrl_set_input(struct pvr2_ctrl *cptr,int m,int v)
372 {
373         struct pvr2_hdw *hdw = cptr->hdw;
374
375         if (hdw->input_val != v) {
376                 hdw->input_val = v;
377                 hdw->input_dirty = !0;
378         }
379
380         /* Handle side effects - if we switch to a mode that needs the RF
381            tuner, then select the right frequency choice as well and mark
382            it dirty. */
383         if (hdw->input_val == PVR2_CVAL_INPUT_RADIO) {
384                 hdw->freqSelector = 0;
385                 hdw->freqDirty = !0;
386         } else if (hdw->input_val == PVR2_CVAL_INPUT_TV) {
387                 hdw->freqSelector = 1;
388                 hdw->freqDirty = !0;
389         }
390         return 0;
391 }
392
393 static int ctrl_isdirty_input(struct pvr2_ctrl *cptr)
394 {
395         return cptr->hdw->input_dirty != 0;
396 }
397
398 static void ctrl_cleardirty_input(struct pvr2_ctrl *cptr)
399 {
400         cptr->hdw->input_dirty = 0;
401 }
402
403
404 static int ctrl_freq_max_get(struct pvr2_ctrl *cptr, int *vp)
405 {
406         unsigned long fv;
407         struct pvr2_hdw *hdw = cptr->hdw;
408         if (hdw->tuner_signal_stale) {
409                 pvr2_i2c_core_status_poll(hdw);
410         }
411         fv = hdw->tuner_signal_info.rangehigh;
412         if (!fv) {
413                 /* Safety fallback */
414                 *vp = TV_MAX_FREQ;
415                 return 0;
416         }
417         if (hdw->tuner_signal_info.capability & V4L2_TUNER_CAP_LOW) {
418                 fv = (fv * 125) / 2;
419         } else {
420                 fv = fv * 62500;
421         }
422         *vp = fv;
423         return 0;
424 }
425
426 static int ctrl_freq_min_get(struct pvr2_ctrl *cptr, int *vp)
427 {
428         unsigned long fv;
429         struct pvr2_hdw *hdw = cptr->hdw;
430         if (hdw->tuner_signal_stale) {
431                 pvr2_i2c_core_status_poll(hdw);
432         }
433         fv = hdw->tuner_signal_info.rangelow;
434         if (!fv) {
435                 /* Safety fallback */
436                 *vp = TV_MIN_FREQ;
437                 return 0;
438         }
439         if (hdw->tuner_signal_info.capability & V4L2_TUNER_CAP_LOW) {
440                 fv = (fv * 125) / 2;
441         } else {
442                 fv = fv * 62500;
443         }
444         *vp = fv;
445         return 0;
446 }
447
448 static int ctrl_cx2341x_is_dirty(struct pvr2_ctrl *cptr)
449 {
450         return cptr->hdw->enc_stale != 0;
451 }
452
453 static void ctrl_cx2341x_clear_dirty(struct pvr2_ctrl *cptr)
454 {
455         cptr->hdw->enc_stale = 0;
456         cptr->hdw->enc_unsafe_stale = 0;
457 }
458
459 static int ctrl_cx2341x_get(struct pvr2_ctrl *cptr,int *vp)
460 {
461         int ret;
462         struct v4l2_ext_controls cs;
463         struct v4l2_ext_control c1;
464         memset(&cs,0,sizeof(cs));
465         memset(&c1,0,sizeof(c1));
466         cs.controls = &c1;
467         cs.count = 1;
468         c1.id = cptr->info->v4l_id;
469         ret = cx2341x_ext_ctrls(&cptr->hdw->enc_ctl_state, 0, &cs,
470                                 VIDIOC_G_EXT_CTRLS);
471         if (ret) return ret;
472         *vp = c1.value;
473         return 0;
474 }
475
476 static int ctrl_cx2341x_set(struct pvr2_ctrl *cptr,int m,int v)
477 {
478         int ret;
479         struct pvr2_hdw *hdw = cptr->hdw;
480         struct v4l2_ext_controls cs;
481         struct v4l2_ext_control c1;
482         memset(&cs,0,sizeof(cs));
483         memset(&c1,0,sizeof(c1));
484         cs.controls = &c1;
485         cs.count = 1;
486         c1.id = cptr->info->v4l_id;
487         c1.value = v;
488         ret = cx2341x_ext_ctrls(&hdw->enc_ctl_state,
489                                 hdw->state_encoder_run, &cs,
490                                 VIDIOC_S_EXT_CTRLS);
491         if (ret == -EBUSY) {
492                 /* Oops.  cx2341x is telling us it's not safe to change
493                    this control while we're capturing.  Make a note of this
494                    fact so that the pipeline will be stopped the next time
495                    controls are committed.  Then go on ahead and store this
496                    change anyway. */
497                 ret = cx2341x_ext_ctrls(&hdw->enc_ctl_state,
498                                         0, &cs,
499                                         VIDIOC_S_EXT_CTRLS);
500                 if (!ret) hdw->enc_unsafe_stale = !0;
501         }
502         if (ret) return ret;
503         hdw->enc_stale = !0;
504         return 0;
505 }
506
507 static unsigned int ctrl_cx2341x_getv4lflags(struct pvr2_ctrl *cptr)
508 {
509         struct v4l2_queryctrl qctrl;
510         struct pvr2_ctl_info *info;
511         qctrl.id = cptr->info->v4l_id;
512         cx2341x_ctrl_query(&cptr->hdw->enc_ctl_state,&qctrl);
513         /* Strip out the const so we can adjust a function pointer.  It's
514            OK to do this here because we know this is a dynamically created
515            control, so the underlying storage for the info pointer is (a)
516            private to us, and (b) not in read-only storage.  Either we do
517            this or we significantly complicate the underlying control
518            implementation. */
519         info = (struct pvr2_ctl_info *)(cptr->info);
520         if (qctrl.flags & V4L2_CTRL_FLAG_READ_ONLY) {
521                 if (info->set_value) {
522                         info->set_value = NULL;
523                 }
524         } else {
525                 if (!(info->set_value)) {
526                         info->set_value = ctrl_cx2341x_set;
527                 }
528         }
529         return qctrl.flags;
530 }
531
532 static int ctrl_streamingenabled_get(struct pvr2_ctrl *cptr,int *vp)
533 {
534         *vp = cptr->hdw->state_pipeline_req;
535         return 0;
536 }
537
538 static int ctrl_masterstate_get(struct pvr2_ctrl *cptr,int *vp)
539 {
540         *vp = cptr->hdw->master_state;
541         return 0;
542 }
543
544 static int ctrl_hsm_get(struct pvr2_ctrl *cptr,int *vp)
545 {
546         int result = pvr2_hdw_is_hsm(cptr->hdw);
547         *vp = PVR2_CVAL_HSM_FULL;
548         if (result < 0) *vp = PVR2_CVAL_HSM_FAIL;
549         if (result) *vp = PVR2_CVAL_HSM_HIGH;
550         return 0;
551 }
552
553 static int ctrl_stdavail_get(struct pvr2_ctrl *cptr,int *vp)
554 {
555         *vp = cptr->hdw->std_mask_avail;
556         return 0;
557 }
558
559 static int ctrl_stdavail_set(struct pvr2_ctrl *cptr,int m,int v)
560 {
561         struct pvr2_hdw *hdw = cptr->hdw;
562         v4l2_std_id ns;
563         ns = hdw->std_mask_avail;
564         ns = (ns & ~m) | (v & m);
565         if (ns == hdw->std_mask_avail) return 0;
566         hdw->std_mask_avail = ns;
567         pvr2_hdw_internal_set_std_avail(hdw);
568         pvr2_hdw_internal_find_stdenum(hdw);
569         return 0;
570 }
571
572 static int ctrl_std_val_to_sym(struct pvr2_ctrl *cptr,int msk,int val,
573                                char *bufPtr,unsigned int bufSize,
574                                unsigned int *len)
575 {
576         *len = pvr2_std_id_to_str(bufPtr,bufSize,msk & val);
577         return 0;
578 }
579
580 static int ctrl_std_sym_to_val(struct pvr2_ctrl *cptr,
581                                const char *bufPtr,unsigned int bufSize,
582                                int *mskp,int *valp)
583 {
584         int ret;
585         v4l2_std_id id;
586         ret = pvr2_std_str_to_id(&id,bufPtr,bufSize);
587         if (ret < 0) return ret;
588         if (mskp) *mskp = id;
589         if (valp) *valp = id;
590         return 0;
591 }
592
593 static int ctrl_stdcur_get(struct pvr2_ctrl *cptr,int *vp)
594 {
595         *vp = cptr->hdw->std_mask_cur;
596         return 0;
597 }
598
599 static int ctrl_stdcur_set(struct pvr2_ctrl *cptr,int m,int v)
600 {
601         struct pvr2_hdw *hdw = cptr->hdw;
602         v4l2_std_id ns;
603         ns = hdw->std_mask_cur;
604         ns = (ns & ~m) | (v & m);
605         if (ns == hdw->std_mask_cur) return 0;
606         hdw->std_mask_cur = ns;
607         hdw->std_dirty = !0;
608         pvr2_hdw_internal_find_stdenum(hdw);
609         return 0;
610 }
611
612 static int ctrl_stdcur_is_dirty(struct pvr2_ctrl *cptr)
613 {
614         return cptr->hdw->std_dirty != 0;
615 }
616
617 static void ctrl_stdcur_clear_dirty(struct pvr2_ctrl *cptr)
618 {
619         cptr->hdw->std_dirty = 0;
620 }
621
622 static int ctrl_signal_get(struct pvr2_ctrl *cptr,int *vp)
623 {
624         struct pvr2_hdw *hdw = cptr->hdw;
625         pvr2_i2c_core_status_poll(hdw);
626         *vp = hdw->tuner_signal_info.signal;
627         return 0;
628 }
629
630 static int ctrl_audio_modes_present_get(struct pvr2_ctrl *cptr,int *vp)
631 {
632         int val = 0;
633         unsigned int subchan;
634         struct pvr2_hdw *hdw = cptr->hdw;
635         pvr2_i2c_core_status_poll(hdw);
636         subchan = hdw->tuner_signal_info.rxsubchans;
637         if (subchan & V4L2_TUNER_SUB_MONO) {
638                 val |= (1 << V4L2_TUNER_MODE_MONO);
639         }
640         if (subchan & V4L2_TUNER_SUB_STEREO) {
641                 val |= (1 << V4L2_TUNER_MODE_STEREO);
642         }
643         if (subchan & V4L2_TUNER_SUB_LANG1) {
644                 val |= (1 << V4L2_TUNER_MODE_LANG1);
645         }
646         if (subchan & V4L2_TUNER_SUB_LANG2) {
647                 val |= (1 << V4L2_TUNER_MODE_LANG2);
648         }
649         *vp = val;
650         return 0;
651 }
652
653
654 static int ctrl_stdenumcur_set(struct pvr2_ctrl *cptr,int m,int v)
655 {
656         struct pvr2_hdw *hdw = cptr->hdw;
657         if (v < 0) return -EINVAL;
658         if (v > hdw->std_enum_cnt) return -EINVAL;
659         hdw->std_enum_cur = v;
660         if (!v) return 0;
661         v--;
662         if (hdw->std_mask_cur == hdw->std_defs[v].id) return 0;
663         hdw->std_mask_cur = hdw->std_defs[v].id;
664         hdw->std_dirty = !0;
665         return 0;
666 }
667
668
669 static int ctrl_stdenumcur_get(struct pvr2_ctrl *cptr,int *vp)
670 {
671         *vp = cptr->hdw->std_enum_cur;
672         return 0;
673 }
674
675
676 static int ctrl_stdenumcur_is_dirty(struct pvr2_ctrl *cptr)
677 {
678         return cptr->hdw->std_dirty != 0;
679 }
680
681
682 static void ctrl_stdenumcur_clear_dirty(struct pvr2_ctrl *cptr)
683 {
684         cptr->hdw->std_dirty = 0;
685 }
686
687
688 #define DEFINT(vmin,vmax) \
689         .type = pvr2_ctl_int, \
690         .def.type_int.min_value = vmin, \
691         .def.type_int.max_value = vmax
692
693 #define DEFENUM(tab) \
694         .type = pvr2_ctl_enum, \
695         .def.type_enum.count = ARRAY_SIZE(tab), \
696         .def.type_enum.value_names = tab
697
698 #define DEFBOOL \
699         .type = pvr2_ctl_bool
700
701 #define DEFMASK(msk,tab) \
702         .type = pvr2_ctl_bitmask, \
703         .def.type_bitmask.valid_bits = msk, \
704         .def.type_bitmask.bit_names = tab
705
706 #define DEFREF(vname) \
707         .set_value = ctrl_set_##vname, \
708         .get_value = ctrl_get_##vname, \
709         .is_dirty = ctrl_isdirty_##vname, \
710         .clear_dirty = ctrl_cleardirty_##vname
711
712
713 #define VCREATE_FUNCS(vname) \
714 static int ctrl_get_##vname(struct pvr2_ctrl *cptr,int *vp) \
715 {*vp = cptr->hdw->vname##_val; return 0;} \
716 static int ctrl_set_##vname(struct pvr2_ctrl *cptr,int m,int v) \
717 {cptr->hdw->vname##_val = v; cptr->hdw->vname##_dirty = !0; return 0;} \
718 static int ctrl_isdirty_##vname(struct pvr2_ctrl *cptr) \
719 {return cptr->hdw->vname##_dirty != 0;} \
720 static void ctrl_cleardirty_##vname(struct pvr2_ctrl *cptr) \
721 {cptr->hdw->vname##_dirty = 0;}
722
723 VCREATE_FUNCS(brightness)
724 VCREATE_FUNCS(contrast)
725 VCREATE_FUNCS(saturation)
726 VCREATE_FUNCS(hue)
727 VCREATE_FUNCS(volume)
728 VCREATE_FUNCS(balance)
729 VCREATE_FUNCS(bass)
730 VCREATE_FUNCS(treble)
731 VCREATE_FUNCS(mute)
732 VCREATE_FUNCS(audiomode)
733 VCREATE_FUNCS(res_hor)
734 VCREATE_FUNCS(res_ver)
735 VCREATE_FUNCS(srate)
736
737 /* Table definition of all controls which can be manipulated */
738 static const struct pvr2_ctl_info control_defs[] = {
739         {
740                 .v4l_id = V4L2_CID_BRIGHTNESS,
741                 .desc = "Brightness",
742                 .name = "brightness",
743                 .default_value = 128,
744                 DEFREF(brightness),
745                 DEFINT(0,255),
746         },{
747                 .v4l_id = V4L2_CID_CONTRAST,
748                 .desc = "Contrast",
749                 .name = "contrast",
750                 .default_value = 68,
751                 DEFREF(contrast),
752                 DEFINT(0,127),
753         },{
754                 .v4l_id = V4L2_CID_SATURATION,
755                 .desc = "Saturation",
756                 .name = "saturation",
757                 .default_value = 64,
758                 DEFREF(saturation),
759                 DEFINT(0,127),
760         },{
761                 .v4l_id = V4L2_CID_HUE,
762                 .desc = "Hue",
763                 .name = "hue",
764                 .default_value = 0,
765                 DEFREF(hue),
766                 DEFINT(-128,127),
767         },{
768                 .v4l_id = V4L2_CID_AUDIO_VOLUME,
769                 .desc = "Volume",
770                 .name = "volume",
771                 .default_value = 62000,
772                 DEFREF(volume),
773                 DEFINT(0,65535),
774         },{
775                 .v4l_id = V4L2_CID_AUDIO_BALANCE,
776                 .desc = "Balance",
777                 .name = "balance",
778                 .default_value = 0,
779                 DEFREF(balance),
780                 DEFINT(-32768,32767),
781         },{
782                 .v4l_id = V4L2_CID_AUDIO_BASS,
783                 .desc = "Bass",
784                 .name = "bass",
785                 .default_value = 0,
786                 DEFREF(bass),
787                 DEFINT(-32768,32767),
788         },{
789                 .v4l_id = V4L2_CID_AUDIO_TREBLE,
790                 .desc = "Treble",
791                 .name = "treble",
792                 .default_value = 0,
793                 DEFREF(treble),
794                 DEFINT(-32768,32767),
795         },{
796                 .v4l_id = V4L2_CID_AUDIO_MUTE,
797                 .desc = "Mute",
798                 .name = "mute",
799                 .default_value = 0,
800                 DEFREF(mute),
801                 DEFBOOL,
802         },{
803                 .desc = "Video Source",
804                 .name = "input",
805                 .internal_id = PVR2_CID_INPUT,
806                 .default_value = PVR2_CVAL_INPUT_TV,
807                 DEFREF(input),
808                 DEFENUM(control_values_input),
809         },{
810                 .desc = "Audio Mode",
811                 .name = "audio_mode",
812                 .internal_id = PVR2_CID_AUDIOMODE,
813                 .default_value = V4L2_TUNER_MODE_STEREO,
814                 DEFREF(audiomode),
815                 DEFENUM(control_values_audiomode),
816         },{
817                 .desc = "Horizontal capture resolution",
818                 .name = "resolution_hor",
819                 .internal_id = PVR2_CID_HRES,
820                 .default_value = 720,
821                 DEFREF(res_hor),
822                 DEFINT(19,720),
823         },{
824                 .desc = "Vertical capture resolution",
825                 .name = "resolution_ver",
826                 .internal_id = PVR2_CID_VRES,
827                 .default_value = 480,
828                 DEFREF(res_ver),
829                 DEFINT(17,576),
830                 /* Hook in check for video standard and adjust maximum
831                    depending on the standard. */
832                 .get_max_value = ctrl_vres_max_get,
833                 .get_min_value = ctrl_vres_min_get,
834         },{
835                 .v4l_id = V4L2_CID_MPEG_AUDIO_SAMPLING_FREQ,
836                 .default_value = V4L2_MPEG_AUDIO_SAMPLING_FREQ_48000,
837                 .desc = "Audio Sampling Frequency",
838                 .name = "srate",
839                 DEFREF(srate),
840                 DEFENUM(control_values_srate),
841         },{
842                 .desc = "Tuner Frequency (Hz)",
843                 .name = "frequency",
844                 .internal_id = PVR2_CID_FREQUENCY,
845                 .default_value = 0,
846                 .set_value = ctrl_freq_set,
847                 .get_value = ctrl_freq_get,
848                 .is_dirty = ctrl_freq_is_dirty,
849                 .clear_dirty = ctrl_freq_clear_dirty,
850                 DEFINT(0,0),
851                 /* Hook in check for input value (tv/radio) and adjust
852                    max/min values accordingly */
853                 .get_max_value = ctrl_freq_max_get,
854                 .get_min_value = ctrl_freq_min_get,
855         },{
856                 .desc = "Channel",
857                 .name = "channel",
858                 .set_value = ctrl_channel_set,
859                 .get_value = ctrl_channel_get,
860                 DEFINT(0,FREQTABLE_SIZE),
861         },{
862                 .desc = "Channel Program Frequency",
863                 .name = "freq_table_value",
864                 .set_value = ctrl_channelfreq_set,
865                 .get_value = ctrl_channelfreq_get,
866                 DEFINT(0,0),
867                 /* Hook in check for input value (tv/radio) and adjust
868                    max/min values accordingly */
869                 .get_max_value = ctrl_freq_max_get,
870                 .get_min_value = ctrl_freq_min_get,
871         },{
872                 .desc = "Channel Program ID",
873                 .name = "freq_table_channel",
874                 .set_value = ctrl_channelprog_set,
875                 .get_value = ctrl_channelprog_get,
876                 DEFINT(0,FREQTABLE_SIZE),
877         },{
878                 .desc = "Streaming Enabled",
879                 .name = "streaming_enabled",
880                 .get_value = ctrl_streamingenabled_get,
881                 DEFBOOL,
882         },{
883                 .desc = "USB Speed",
884                 .name = "usb_speed",
885                 .get_value = ctrl_hsm_get,
886                 DEFENUM(control_values_hsm),
887         },{
888                 .desc = "Master State",
889                 .name = "master_state",
890                 .get_value = ctrl_masterstate_get,
891                 DEFENUM(pvr2_state_names),
892         },{
893                 .desc = "Signal Present",
894                 .name = "signal_present",
895                 .get_value = ctrl_signal_get,
896                 DEFINT(0,65535),
897         },{
898                 .desc = "Audio Modes Present",
899                 .name = "audio_modes_present",
900                 .get_value = ctrl_audio_modes_present_get,
901                 /* For this type we "borrow" the V4L2_TUNER_MODE enum from
902                    v4l.  Nothing outside of this module cares about this,
903                    but I reuse it in order to also reuse the
904                    control_values_audiomode string table. */
905                 DEFMASK(((1 << V4L2_TUNER_MODE_MONO)|
906                          (1 << V4L2_TUNER_MODE_STEREO)|
907                          (1 << V4L2_TUNER_MODE_LANG1)|
908                          (1 << V4L2_TUNER_MODE_LANG2)),
909                         control_values_audiomode),
910         },{
911                 .desc = "Video Standards Available Mask",
912                 .name = "video_standard_mask_available",
913                 .internal_id = PVR2_CID_STDAVAIL,
914                 .skip_init = !0,
915                 .get_value = ctrl_stdavail_get,
916                 .set_value = ctrl_stdavail_set,
917                 .val_to_sym = ctrl_std_val_to_sym,
918                 .sym_to_val = ctrl_std_sym_to_val,
919                 .type = pvr2_ctl_bitmask,
920         },{
921                 .desc = "Video Standards In Use Mask",
922                 .name = "video_standard_mask_active",
923                 .internal_id = PVR2_CID_STDCUR,
924                 .skip_init = !0,
925                 .get_value = ctrl_stdcur_get,
926                 .set_value = ctrl_stdcur_set,
927                 .is_dirty = ctrl_stdcur_is_dirty,
928                 .clear_dirty = ctrl_stdcur_clear_dirty,
929                 .val_to_sym = ctrl_std_val_to_sym,
930                 .sym_to_val = ctrl_std_sym_to_val,
931                 .type = pvr2_ctl_bitmask,
932         },{
933                 .desc = "Video Standard Name",
934                 .name = "video_standard",
935                 .internal_id = PVR2_CID_STDENUM,
936                 .skip_init = !0,
937                 .get_value = ctrl_stdenumcur_get,
938                 .set_value = ctrl_stdenumcur_set,
939                 .is_dirty = ctrl_stdenumcur_is_dirty,
940                 .clear_dirty = ctrl_stdenumcur_clear_dirty,
941                 .type = pvr2_ctl_enum,
942         }
943 };
944
945 #define CTRLDEF_COUNT ARRAY_SIZE(control_defs)
946
947
948 const char *pvr2_config_get_name(enum pvr2_config cfg)
949 {
950         switch (cfg) {
951         case pvr2_config_empty: return "empty";
952         case pvr2_config_mpeg: return "mpeg";
953         case pvr2_config_vbi: return "vbi";
954         case pvr2_config_pcm: return "pcm";
955         case pvr2_config_rawvideo: return "raw video";
956         }
957         return "<unknown>";
958 }
959
960
961 struct usb_device *pvr2_hdw_get_dev(struct pvr2_hdw *hdw)
962 {
963         return hdw->usb_dev;
964 }
965
966
967 unsigned long pvr2_hdw_get_sn(struct pvr2_hdw *hdw)
968 {
969         return hdw->serial_number;
970 }
971
972
973 const char *pvr2_hdw_get_bus_info(struct pvr2_hdw *hdw)
974 {
975         return hdw->bus_info;
976 }
977
978
979 unsigned long pvr2_hdw_get_cur_freq(struct pvr2_hdw *hdw)
980 {
981         return hdw->freqSelector ? hdw->freqValTelevision : hdw->freqValRadio;
982 }
983
984 /* Set the currently tuned frequency and account for all possible
985    driver-core side effects of this action. */
986 void pvr2_hdw_set_cur_freq(struct pvr2_hdw *hdw,unsigned long val)
987 {
988         if (hdw->input_val == PVR2_CVAL_INPUT_RADIO) {
989                 if (hdw->freqSelector) {
990                         /* Swing over to radio frequency selection */
991                         hdw->freqSelector = 0;
992                         hdw->freqDirty = !0;
993                 }
994                 if (hdw->freqValRadio != val) {
995                         hdw->freqValRadio = val;
996                         hdw->freqSlotRadio = 0;
997                         hdw->freqDirty = !0;
998                 }
999         } else {
1000                 if (!(hdw->freqSelector)) {
1001                         /* Swing over to television frequency selection */
1002                         hdw->freqSelector = 1;
1003                         hdw->freqDirty = !0;
1004                 }
1005                 if (hdw->freqValTelevision != val) {
1006                         hdw->freqValTelevision = val;
1007                         hdw->freqSlotTelevision = 0;
1008                         hdw->freqDirty = !0;
1009                 }
1010         }
1011 }
1012
1013 int pvr2_hdw_get_unit_number(struct pvr2_hdw *hdw)
1014 {
1015         return hdw->unit_number;
1016 }
1017
1018
1019 /* Attempt to locate one of the given set of files.  Messages are logged
1020    appropriate to what has been found.  The return value will be 0 or
1021    greater on success (it will be the index of the file name found) and
1022    fw_entry will be filled in.  Otherwise a negative error is returned on
1023    failure.  If the return value is -ENOENT then no viable firmware file
1024    could be located. */
1025 static int pvr2_locate_firmware(struct pvr2_hdw *hdw,
1026                                 const struct firmware **fw_entry,
1027                                 const char *fwtypename,
1028                                 unsigned int fwcount,
1029                                 const char *fwnames[])
1030 {
1031         unsigned int idx;
1032         int ret = -EINVAL;
1033         for (idx = 0; idx < fwcount; idx++) {
1034                 ret = request_firmware(fw_entry,
1035                                        fwnames[idx],
1036                                        &hdw->usb_dev->dev);
1037                 if (!ret) {
1038                         trace_firmware("Located %s firmware: %s;"
1039                                        " uploading...",
1040                                        fwtypename,
1041                                        fwnames[idx]);
1042                         return idx;
1043                 }
1044                 if (ret == -ENOENT) continue;
1045                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1046                            "request_firmware fatal error with code=%d",ret);
1047                 return ret;
1048         }
1049         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1050                    "***WARNING***"
1051                    " Device %s firmware"
1052                    " seems to be missing.",
1053                    fwtypename);
1054         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1055                    "Did you install the pvrusb2 firmware files"
1056                    " in their proper location?");
1057         if (fwcount == 1) {
1058                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1059                            "request_firmware unable to locate %s file %s",
1060                            fwtypename,fwnames[0]);
1061         } else {
1062                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1063                            "request_firmware unable to locate"
1064                            " one of the following %s files:",
1065                            fwtypename);
1066                 for (idx = 0; idx < fwcount; idx++) {
1067                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1068                                    "request_firmware: Failed to find %s",
1069                                    fwnames[idx]);
1070                 }
1071         }
1072         return ret;
1073 }
1074
1075
1076 /*
1077  * pvr2_upload_firmware1().
1078  *
1079  * Send the 8051 firmware to the device.  After the upload, arrange for
1080  * device to re-enumerate.
1081  *
1082  * NOTE : the pointer to the firmware data given by request_firmware()
1083  * is not suitable for an usb transaction.
1084  *
1085  */
1086 static int pvr2_upload_firmware1(struct pvr2_hdw *hdw)
1087 {
1088         const struct firmware *fw_entry = NULL;
1089         void  *fw_ptr;
1090         unsigned int pipe;
1091         int ret;
1092         u16 address;
1093
1094         if (!hdw->hdw_desc->fx2_firmware.cnt) {
1095                 hdw->fw1_state = FW1_STATE_OK;
1096                 return 0;
1097         }
1098
1099         hdw->fw1_state = FW1_STATE_FAILED; // default result
1100
1101         trace_firmware("pvr2_upload_firmware1");
1102
1103         ret = pvr2_locate_firmware(hdw,&fw_entry,"fx2 controller",
1104                                    hdw->hdw_desc->fx2_firmware.cnt,
1105                                    hdw->hdw_desc->fx2_firmware.lst);
1106         if (ret < 0) {
1107                 if (ret == -ENOENT) hdw->fw1_state = FW1_STATE_MISSING;
1108                 return ret;
1109         }
1110
1111         usb_settoggle(hdw->usb_dev, 0 & 0xf, !(0 & USB_DIR_IN), 0);
1112         usb_clear_halt(hdw->usb_dev, usb_sndbulkpipe(hdw->usb_dev, 0 & 0x7f));
1113
1114         pipe = usb_sndctrlpipe(hdw->usb_dev, 0);
1115
1116         if (fw_entry->size != 0x2000){
1117                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,"wrong fx2 firmware size");
1118                 release_firmware(fw_entry);
1119                 return -ENOMEM;
1120         }
1121
1122         fw_ptr = kmalloc(0x800, GFP_KERNEL);
1123         if (fw_ptr == NULL){
1124                 release_firmware(fw_entry);
1125                 return -ENOMEM;
1126         }
1127
1128         /* We have to hold the CPU during firmware upload. */
1129         pvr2_hdw_cpureset_assert(hdw,1);
1130
1131         /* upload the firmware to address 0000-1fff in 2048 (=0x800) bytes
1132            chunk. */
1133
1134         ret = 0;
1135         for(address = 0; address < fw_entry->size; address += 0x800) {
1136                 memcpy(fw_ptr, fw_entry->data + address, 0x800);
1137                 ret += usb_control_msg(hdw->usb_dev, pipe, 0xa0, 0x40, address,
1138                                        0, fw_ptr, 0x800, HZ);
1139         }
1140
1141         trace_firmware("Upload done, releasing device's CPU");
1142
1143         /* Now release the CPU.  It will disconnect and reconnect later. */
1144         pvr2_hdw_cpureset_assert(hdw,0);
1145
1146         kfree(fw_ptr);
1147         release_firmware(fw_entry);
1148
1149         trace_firmware("Upload done (%d bytes sent)",ret);
1150
1151         /* We should have written 8192 bytes */
1152         if (ret == 8192) {
1153                 hdw->fw1_state = FW1_STATE_RELOAD;
1154                 return 0;
1155         }
1156
1157         return -EIO;
1158 }
1159
1160
1161 /*
1162  * pvr2_upload_firmware2()
1163  *
1164  * This uploads encoder firmware on endpoint 2.
1165  *
1166  */
1167
1168 int pvr2_upload_firmware2(struct pvr2_hdw *hdw)
1169 {
1170         const struct firmware *fw_entry = NULL;
1171         void  *fw_ptr;
1172         unsigned int pipe, fw_len, fw_done, bcnt, icnt;
1173         int actual_length;
1174         int ret = 0;
1175         int fwidx;
1176         static const char *fw_files[] = {
1177                 CX2341X_FIRM_ENC_FILENAME,
1178         };
1179
1180         if (hdw->hdw_desc->flag_skip_cx23416_firmware) {
1181                 return 0;
1182         }
1183
1184         trace_firmware("pvr2_upload_firmware2");
1185
1186         ret = pvr2_locate_firmware(hdw,&fw_entry,"encoder",
1187                                    ARRAY_SIZE(fw_files), fw_files);
1188         if (ret < 0) return ret;
1189         fwidx = ret;
1190         ret = 0;
1191         /* Since we're about to completely reinitialize the encoder,
1192            invalidate our cached copy of its configuration state.  Next
1193            time we configure the encoder, then we'll fully configure it. */
1194         hdw->enc_cur_valid = 0;
1195
1196         /* First prepare firmware loading */
1197         ret |= pvr2_write_register(hdw, 0x0048, 0xffffffff); /*interrupt mask*/
1198         ret |= pvr2_hdw_gpio_chg_dir(hdw,0xffffffff,0x00000088); /*gpio dir*/
1199         ret |= pvr2_hdw_gpio_chg_out(hdw,0xffffffff,0x00000008); /*gpio output state*/
1200         ret |= pvr2_hdw_cmd_deep_reset(hdw);
1201         ret |= pvr2_write_register(hdw, 0xa064, 0x00000000); /*APU command*/
1202         ret |= pvr2_hdw_gpio_chg_dir(hdw,0xffffffff,0x00000408); /*gpio dir*/
1203         ret |= pvr2_hdw_gpio_chg_out(hdw,0xffffffff,0x00000008); /*gpio output state*/
1204         ret |= pvr2_write_register(hdw, 0x9058, 0xffffffed); /*VPU ctrl*/
1205         ret |= pvr2_write_register(hdw, 0x9054, 0xfffffffd); /*reset hw blocks*/
1206         ret |= pvr2_write_register(hdw, 0x07f8, 0x80000800); /*encoder SDRAM refresh*/
1207         ret |= pvr2_write_register(hdw, 0x07fc, 0x0000001a); /*encoder SDRAM pre-charge*/
1208         ret |= pvr2_write_register(hdw, 0x0700, 0x00000000); /*I2C clock*/
1209         ret |= pvr2_write_register(hdw, 0xaa00, 0x00000000); /*unknown*/
1210         ret |= pvr2_write_register(hdw, 0xaa04, 0x00057810); /*unknown*/
1211         ret |= pvr2_write_register(hdw, 0xaa10, 0x00148500); /*unknown*/
1212         ret |= pvr2_write_register(hdw, 0xaa18, 0x00840000); /*unknown*/
1213         LOCK_TAKE(hdw->ctl_lock); do {
1214                 hdw->cmd_buffer[0] = FX2CMD_FWPOST1;
1215                 ret |= pvr2_send_request(hdw,hdw->cmd_buffer,1,NULL,0);
1216                 hdw->cmd_buffer[0] = FX2CMD_MEMSEL;
1217                 hdw->cmd_buffer[1] = 0;
1218                 ret |= pvr2_send_request(hdw,hdw->cmd_buffer,2,NULL,0);
1219         } while (0); LOCK_GIVE(hdw->ctl_lock);
1220
1221         if (ret) {
1222                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1223                            "firmware2 upload prep failed, ret=%d",ret);
1224                 release_firmware(fw_entry);
1225                 return ret;
1226         }
1227
1228         /* Now send firmware */
1229
1230         fw_len = fw_entry->size;
1231
1232         if (fw_len % sizeof(u32)) {
1233                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1234                            "size of %s firmware"
1235                            " must be a multiple of %zu bytes",
1236                            fw_files[fwidx],sizeof(u32));
1237                 release_firmware(fw_entry);
1238                 return -1;
1239         }
1240
1241         fw_ptr = kmalloc(FIRMWARE_CHUNK_SIZE, GFP_KERNEL);
1242         if (fw_ptr == NULL){
1243                 release_firmware(fw_entry);
1244                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1245                            "failed to allocate memory for firmware2 upload");
1246                 return -ENOMEM;
1247         }
1248
1249         pipe = usb_sndbulkpipe(hdw->usb_dev, PVR2_FIRMWARE_ENDPOINT);
1250
1251         fw_done = 0;
1252         for (fw_done = 0; fw_done < fw_len;) {
1253                 bcnt = fw_len - fw_done;
1254                 if (bcnt > FIRMWARE_CHUNK_SIZE) bcnt = FIRMWARE_CHUNK_SIZE;
1255                 memcpy(fw_ptr, fw_entry->data + fw_done, bcnt);
1256                 /* Usbsnoop log shows that we must swap bytes... */
1257                 for (icnt = 0; icnt < bcnt/4 ; icnt++)
1258                         ((u32 *)fw_ptr)[icnt] =
1259                                 ___swab32(((u32 *)fw_ptr)[icnt]);
1260
1261                 ret |= usb_bulk_msg(hdw->usb_dev, pipe, fw_ptr,bcnt,
1262                                     &actual_length, HZ);
1263                 ret |= (actual_length != bcnt);
1264                 if (ret) break;
1265                 fw_done += bcnt;
1266         }
1267
1268         trace_firmware("upload of %s : %i / %i ",
1269                        fw_files[fwidx],fw_done,fw_len);
1270
1271         kfree(fw_ptr);
1272         release_firmware(fw_entry);
1273
1274         if (ret) {
1275                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1276                            "firmware2 upload transfer failure");
1277                 return ret;
1278         }
1279
1280         /* Finish upload */
1281
1282         ret |= pvr2_write_register(hdw, 0x9054, 0xffffffff); /*reset hw blocks*/
1283         ret |= pvr2_write_register(hdw, 0x9058, 0xffffffe8); /*VPU ctrl*/
1284         LOCK_TAKE(hdw->ctl_lock); do {
1285                 hdw->cmd_buffer[0] = FX2CMD_MEMSEL;
1286                 hdw->cmd_buffer[1] = 0;
1287                 ret |= pvr2_send_request(hdw,hdw->cmd_buffer,2,NULL,0);
1288         } while (0); LOCK_GIVE(hdw->ctl_lock);
1289
1290         if (ret) {
1291                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1292                            "firmware2 upload post-proc failure");
1293         }
1294         return ret;
1295 }
1296
1297
1298 static const char *pvr2_get_state_name(unsigned int st)
1299 {
1300         if (st < ARRAY_SIZE(pvr2_state_names)) {
1301                 return pvr2_state_names[st];
1302         }
1303         return "???";
1304 }
1305
1306 static int pvr2_decoder_enable(struct pvr2_hdw *hdw,int enablefl)
1307 {
1308         if (!hdw->decoder_ctrl) {
1309                 if (!hdw->flag_decoder_missed) {
1310                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1311                                    "WARNING: No decoder present");
1312                         hdw->flag_decoder_missed = !0;
1313                         trace_stbit("flag_decoder_missed",
1314                                     hdw->flag_decoder_missed);
1315                 }
1316                 return -EIO;
1317         }
1318         hdw->decoder_ctrl->enable(hdw->decoder_ctrl->ctxt,enablefl);
1319         return 0;
1320 }
1321
1322
1323 void pvr2_hdw_set_decoder(struct pvr2_hdw *hdw,struct pvr2_decoder_ctrl *ptr)
1324 {
1325         if (hdw->decoder_ctrl == ptr) return;
1326         hdw->decoder_ctrl = ptr;
1327         if (hdw->decoder_ctrl && hdw->flag_decoder_missed) {
1328                 hdw->flag_decoder_missed = 0;
1329                 trace_stbit("flag_decoder_missed",
1330                             hdw->flag_decoder_missed);
1331                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1332                            "Decoder has appeared");
1333                 pvr2_hdw_state_sched(hdw);
1334         }
1335 }
1336
1337
1338 int pvr2_hdw_get_state(struct pvr2_hdw *hdw)
1339 {
1340         return hdw->master_state;
1341 }
1342
1343
1344 static int pvr2_hdw_untrip_unlocked(struct pvr2_hdw *hdw)
1345 {
1346         if (!hdw->flag_tripped) return 0;
1347         hdw->flag_tripped = 0;
1348         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1349                    "Clearing driver error statuss");
1350         return !0;
1351 }
1352
1353
1354 int pvr2_hdw_untrip(struct pvr2_hdw *hdw)
1355 {
1356         int fl;
1357         LOCK_TAKE(hdw->big_lock); do {
1358                 fl = pvr2_hdw_untrip_unlocked(hdw);
1359         } while (0); LOCK_GIVE(hdw->big_lock);
1360         if (fl) pvr2_hdw_state_sched(hdw);
1361         return 0;
1362 }
1363
1364
1365 const char *pvr2_hdw_get_state_name(unsigned int id)
1366 {
1367         if (id >= ARRAY_SIZE(pvr2_state_names)) return NULL;
1368         return pvr2_state_names[id];
1369 }
1370
1371
1372 int pvr2_hdw_get_streaming(struct pvr2_hdw *hdw)
1373 {
1374         return hdw->state_pipeline_req != 0;
1375 }
1376
1377
1378 int pvr2_hdw_set_streaming(struct pvr2_hdw *hdw,int enable_flag)
1379 {
1380         int ret,st;
1381         LOCK_TAKE(hdw->big_lock); do {
1382                 pvr2_hdw_untrip_unlocked(hdw);
1383                 if ((!enable_flag) != !(hdw->state_pipeline_req)) {
1384                         hdw->state_pipeline_req = enable_flag != 0;
1385                         pvr2_trace(PVR2_TRACE_START_STOP,
1386                                    "/*--TRACE_STREAM--*/ %s",
1387                                    enable_flag ? "enable" : "disable");
1388                 }
1389                 pvr2_hdw_state_sched(hdw);
1390         } while (0); LOCK_GIVE(hdw->big_lock);
1391         if ((ret = pvr2_hdw_wait(hdw,0)) < 0) return ret;
1392         if (enable_flag) {
1393                 while ((st = hdw->master_state) != PVR2_STATE_RUN) {
1394                         if (st != PVR2_STATE_READY) return -EIO;
1395                         if ((ret = pvr2_hdw_wait(hdw,st)) < 0) return ret;
1396                 }
1397         }
1398         return 0;
1399 }
1400
1401
1402 int pvr2_hdw_set_stream_type(struct pvr2_hdw *hdw,enum pvr2_config config)
1403 {
1404         int fl;
1405         LOCK_TAKE(hdw->big_lock);
1406         if ((fl = (hdw->desired_stream_type != config)) != 0) {
1407                 hdw->desired_stream_type = config;
1408                 hdw->state_pipeline_config = 0;
1409                 trace_stbit("state_pipeline_config",
1410                             hdw->state_pipeline_config);
1411                 pvr2_hdw_state_sched(hdw);
1412         }
1413         LOCK_GIVE(hdw->big_lock);
1414         if (fl) return 0;
1415         return pvr2_hdw_wait(hdw,0);
1416 }
1417
1418
1419 static int get_default_tuner_type(struct pvr2_hdw *hdw)
1420 {
1421         int unit_number = hdw->unit_number;
1422         int tp = -1;
1423         if ((unit_number >= 0) && (unit_number < PVR_NUM)) {
1424                 tp = tuner[unit_number];
1425         }
1426         if (tp < 0) return -EINVAL;
1427         hdw->tuner_type = tp;
1428         return 0;
1429 }
1430
1431
1432 static v4l2_std_id get_default_standard(struct pvr2_hdw *hdw)
1433 {
1434         int unit_number = hdw->unit_number;
1435         int tp = 0;
1436         if ((unit_number >= 0) && (unit_number < PVR_NUM)) {
1437                 tp = video_std[unit_number];
1438         }
1439         return tp;
1440 }
1441
1442
1443 static unsigned int get_default_error_tolerance(struct pvr2_hdw *hdw)
1444 {
1445         int unit_number = hdw->unit_number;
1446         int tp = 0;
1447         if ((unit_number >= 0) && (unit_number < PVR_NUM)) {
1448                 tp = tolerance[unit_number];
1449         }
1450         return tp;
1451 }
1452
1453
1454 static int pvr2_hdw_check_firmware(struct pvr2_hdw *hdw)
1455 {
1456         /* Try a harmless request to fetch the eeprom's address over
1457            endpoint 1.  See what happens.  Only the full FX2 image can
1458            respond to this.  If this probe fails then likely the FX2
1459            firmware needs be loaded. */
1460         int result;
1461         LOCK_TAKE(hdw->ctl_lock); do {
1462                 hdw->cmd_buffer[0] = FX2CMD_GET_EEPROM_ADDR;
1463                 result = pvr2_send_request_ex(hdw,HZ*1,!0,
1464                                            hdw->cmd_buffer,1,
1465                                            hdw->cmd_buffer,1);
1466                 if (result < 0) break;
1467         } while(0); LOCK_GIVE(hdw->ctl_lock);
1468         if (result) {
1469                 pvr2_trace(PVR2_TRACE_INIT,
1470                            "Probe of device endpoint 1 result status %d",
1471                            result);
1472         } else {
1473                 pvr2_trace(PVR2_TRACE_INIT,
1474                            "Probe of device endpoint 1 succeeded");
1475         }
1476         return result == 0;
1477 }
1478
1479 struct pvr2_std_hack {
1480         v4l2_std_id pat;  /* Pattern to match */
1481         v4l2_std_id msk;  /* Which bits we care about */
1482         v4l2_std_id std;  /* What additional standards or default to set */
1483 };
1484
1485 /* This data structure labels specific combinations of standards from
1486    tveeprom that we'll try to recognize.  If we recognize one, then assume
1487    a specified default standard to use.  This is here because tveeprom only
1488    tells us about available standards not the intended default standard (if
1489    any) for the device in question.  We guess the default based on what has
1490    been reported as available.  Note that this is only for guessing a
1491    default - which can always be overridden explicitly - and if the user
1492    has otherwise named a default then that default will always be used in
1493    place of this table. */
1494 const static struct pvr2_std_hack std_eeprom_maps[] = {
1495         {       /* PAL(B/G) */
1496                 .pat = V4L2_STD_B|V4L2_STD_GH,
1497                 .std = V4L2_STD_PAL_B|V4L2_STD_PAL_B1|V4L2_STD_PAL_G,
1498         },
1499         {       /* NTSC(M) */
1500                 .pat = V4L2_STD_MN,
1501                 .std = V4L2_STD_NTSC_M,
1502         },
1503         {       /* PAL(I) */
1504                 .pat = V4L2_STD_PAL_I,
1505                 .std = V4L2_STD_PAL_I,
1506         },
1507         {       /* SECAM(L/L') */
1508                 .pat = V4L2_STD_SECAM_L|V4L2_STD_SECAM_LC,
1509                 .std = V4L2_STD_SECAM_L|V4L2_STD_SECAM_LC,
1510         },
1511         {       /* PAL(D/D1/K) */
1512                 .pat = V4L2_STD_DK,
1513                 .std = V4L2_STD_PAL_D/V4L2_STD_PAL_D1|V4L2_STD_PAL_K,
1514         },
1515 };
1516
1517 static void pvr2_hdw_setup_std(struct pvr2_hdw *hdw)
1518 {
1519         char buf[40];
1520         unsigned int bcnt;
1521         v4l2_std_id std1,std2;
1522
1523         std1 = get_default_standard(hdw);
1524
1525         bcnt = pvr2_std_id_to_str(buf,sizeof(buf),hdw->std_mask_eeprom);
1526         pvr2_trace(PVR2_TRACE_STD,
1527                    "Supported video standard(s) reported by eeprom: %.*s",
1528                    bcnt,buf);
1529
1530         hdw->std_mask_avail = hdw->std_mask_eeprom;
1531
1532         std2 = std1 & ~hdw->std_mask_avail;
1533         if (std2) {
1534                 bcnt = pvr2_std_id_to_str(buf,sizeof(buf),std2);
1535                 pvr2_trace(PVR2_TRACE_STD,
1536                            "Expanding supported video standards"
1537                            " to include: %.*s",
1538                            bcnt,buf);
1539                 hdw->std_mask_avail |= std2;
1540         }
1541
1542         pvr2_hdw_internal_set_std_avail(hdw);
1543
1544         if (std1) {
1545                 bcnt = pvr2_std_id_to_str(buf,sizeof(buf),std1);
1546                 pvr2_trace(PVR2_TRACE_STD,
1547                            "Initial video standard forced to %.*s",
1548                            bcnt,buf);
1549                 hdw->std_mask_cur = std1;
1550                 hdw->std_dirty = !0;
1551                 pvr2_hdw_internal_find_stdenum(hdw);
1552                 return;
1553         }
1554
1555         {
1556                 unsigned int idx;
1557                 for (idx = 0; idx < ARRAY_SIZE(std_eeprom_maps); idx++) {
1558                         if (std_eeprom_maps[idx].msk ?
1559                             ((std_eeprom_maps[idx].pat ^
1560                              hdw->std_mask_eeprom) &
1561                              std_eeprom_maps[idx].msk) :
1562                             (std_eeprom_maps[idx].pat !=
1563                              hdw->std_mask_eeprom)) continue;
1564                         bcnt = pvr2_std_id_to_str(buf,sizeof(buf),
1565                                                   std_eeprom_maps[idx].std);
1566                         pvr2_trace(PVR2_TRACE_STD,
1567                                    "Initial video standard guessed as %.*s",
1568                                    bcnt,buf);
1569                         hdw->std_mask_cur = std_eeprom_maps[idx].std;
1570                         hdw->std_dirty = !0;
1571                         pvr2_hdw_internal_find_stdenum(hdw);
1572                         return;
1573                 }
1574         }
1575
1576         if (hdw->std_enum_cnt > 1) {
1577                 // Autoselect the first listed standard
1578                 hdw->std_enum_cur = 1;
1579                 hdw->std_mask_cur = hdw->std_defs[hdw->std_enum_cur-1].id;
1580                 hdw->std_dirty = !0;
1581                 pvr2_trace(PVR2_TRACE_STD,
1582                            "Initial video standard auto-selected to %s",
1583                            hdw->std_defs[hdw->std_enum_cur-1].name);
1584                 return;
1585         }
1586
1587         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1588                    "Unable to select a viable initial video standard");
1589 }
1590
1591
1592 static void pvr2_hdw_setup_low(struct pvr2_hdw *hdw)
1593 {
1594         int ret;
1595         unsigned int idx;
1596         struct pvr2_ctrl *cptr;
1597         int reloadFl = 0;
1598         if (hdw->hdw_desc->fx2_firmware.cnt) {
1599                 if (!reloadFl) {
1600                         reloadFl =
1601                                 (hdw->usb_intf->cur_altsetting->desc.bNumEndpoints
1602                                  == 0);
1603                         if (reloadFl) {
1604                                 pvr2_trace(PVR2_TRACE_INIT,
1605                                            "USB endpoint config looks strange"
1606                                            "; possibly firmware needs to be"
1607                                            " loaded");
1608                         }
1609                 }
1610                 if (!reloadFl) {
1611                         reloadFl = !pvr2_hdw_check_firmware(hdw);
1612                         if (reloadFl) {
1613                                 pvr2_trace(PVR2_TRACE_INIT,
1614                                            "Check for FX2 firmware failed"
1615                                            "; possibly firmware needs to be"
1616                                            " loaded");
1617                         }
1618                 }
1619                 if (reloadFl) {
1620                         if (pvr2_upload_firmware1(hdw) != 0) {
1621                                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1622                                            "Failure uploading firmware1");
1623                         }
1624                         return;
1625                 }
1626         }
1627         hdw->fw1_state = FW1_STATE_OK;
1628
1629         if (initusbreset) {
1630                 pvr2_hdw_device_reset(hdw);
1631         }
1632         if (!pvr2_hdw_dev_ok(hdw)) return;
1633
1634         for (idx = 0; idx < hdw->hdw_desc->client_modules.cnt; idx++) {
1635                 request_module(hdw->hdw_desc->client_modules.lst[idx]);
1636         }
1637
1638         if (!hdw->hdw_desc->flag_no_powerup) {
1639                 pvr2_hdw_cmd_powerup(hdw);
1640                 if (!pvr2_hdw_dev_ok(hdw)) return;
1641         }
1642
1643         // This step MUST happen after the earlier powerup step.
1644         pvr2_i2c_core_init(hdw);
1645         if (!pvr2_hdw_dev_ok(hdw)) return;
1646
1647         for (idx = 0; idx < CTRLDEF_COUNT; idx++) {
1648                 cptr = hdw->controls + idx;
1649                 if (cptr->info->skip_init) continue;
1650                 if (!cptr->info->set_value) continue;
1651                 cptr->info->set_value(cptr,~0,cptr->info->default_value);
1652         }
1653
1654         /* Set up special default values for the television and radio
1655            frequencies here.  It's not really important what these defaults
1656            are, but I set them to something usable in the Chicago area just
1657            to make driver testing a little easier. */
1658
1659         /* US Broadcast channel 7 (175.25 MHz) */
1660         hdw->freqValTelevision = 175250000L;
1661         /* 104.3 MHz, a usable FM station for my area */
1662         hdw->freqValRadio = 104300000L;
1663
1664         // Do not use pvr2_reset_ctl_endpoints() here.  It is not
1665         // thread-safe against the normal pvr2_send_request() mechanism.
1666         // (We should make it thread safe).
1667
1668         ret = pvr2_hdw_get_eeprom_addr(hdw);
1669         if (!pvr2_hdw_dev_ok(hdw)) return;
1670         if (ret < 0) {
1671                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1672                            "Unable to determine location of eeprom, skipping");
1673         } else {
1674                 hdw->eeprom_addr = ret;
1675                 pvr2_eeprom_analyze(hdw);
1676                 if (!pvr2_hdw_dev_ok(hdw)) return;
1677         }
1678
1679         pvr2_hdw_setup_std(hdw);
1680
1681         if (!get_default_tuner_type(hdw)) {
1682                 pvr2_trace(PVR2_TRACE_INIT,
1683                            "pvr2_hdw_setup: Tuner type overridden to %d",
1684                            hdw->tuner_type);
1685         }
1686
1687         hdw->tuner_updated = !0;
1688         pvr2_i2c_core_check_stale(hdw);
1689         hdw->tuner_updated = 0;
1690
1691         if (!pvr2_hdw_dev_ok(hdw)) return;
1692
1693         pvr2_hdw_commit_setup(hdw);
1694
1695         hdw->vid_stream = pvr2_stream_create();
1696         if (!pvr2_hdw_dev_ok(hdw)) return;
1697         pvr2_trace(PVR2_TRACE_INIT,
1698                    "pvr2_hdw_setup: video stream is %p",hdw->vid_stream);
1699         if (hdw->vid_stream) {
1700                 idx = get_default_error_tolerance(hdw);
1701                 if (idx) {
1702                         pvr2_trace(PVR2_TRACE_INIT,
1703                                    "pvr2_hdw_setup: video stream %p"
1704                                    " setting tolerance %u",
1705                                    hdw->vid_stream,idx);
1706                 }
1707                 pvr2_stream_setup(hdw->vid_stream,hdw->usb_dev,
1708                                   PVR2_VID_ENDPOINT,idx);
1709         }
1710
1711         if (!pvr2_hdw_dev_ok(hdw)) return;
1712
1713         hdw->flag_init_ok = !0;
1714
1715         pvr2_hdw_state_sched(hdw);
1716 }
1717
1718
1719 /* Set up the structure and attempt to put the device into a usable state.
1720    This can be a time-consuming operation, which is why it is not done
1721    internally as part of the create() step. */
1722 static void pvr2_hdw_setup(struct pvr2_hdw *hdw)
1723 {
1724         pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_setup(hdw=%p) begin",hdw);
1725         do {
1726                 pvr2_hdw_setup_low(hdw);
1727                 pvr2_trace(PVR2_TRACE_INIT,
1728                            "pvr2_hdw_setup(hdw=%p) done, ok=%d init_ok=%d",
1729                            hdw,pvr2_hdw_dev_ok(hdw),hdw->flag_init_ok);
1730                 if (pvr2_hdw_dev_ok(hdw)) {
1731                         if (hdw->flag_init_ok) {
1732                                 pvr2_trace(
1733                                         PVR2_TRACE_INFO,
1734                                         "Device initialization"
1735                                         " completed successfully.");
1736                                 break;
1737                         }
1738                         if (hdw->fw1_state == FW1_STATE_RELOAD) {
1739                                 pvr2_trace(
1740                                         PVR2_TRACE_INFO,
1741                                         "Device microcontroller firmware"
1742                                         " (re)loaded; it should now reset"
1743                                         " and reconnect.");
1744                                 break;
1745                         }
1746                         pvr2_trace(
1747                                 PVR2_TRACE_ERROR_LEGS,
1748                                 "Device initialization was not successful.");
1749                         if (hdw->fw1_state == FW1_STATE_MISSING) {
1750                                 pvr2_trace(
1751                                         PVR2_TRACE_ERROR_LEGS,
1752                                         "Giving up since device"
1753                                         " microcontroller firmware"
1754                                         " appears to be missing.");
1755                                 break;
1756                         }
1757                 }
1758                 if (procreload) {
1759                         pvr2_trace(
1760                                 PVR2_TRACE_ERROR_LEGS,
1761                                 "Attempting pvrusb2 recovery by reloading"
1762                                 " primary firmware.");
1763                         pvr2_trace(
1764                                 PVR2_TRACE_ERROR_LEGS,
1765                                 "If this works, device should disconnect"
1766                                 " and reconnect in a sane state.");
1767                         hdw->fw1_state = FW1_STATE_UNKNOWN;
1768                         pvr2_upload_firmware1(hdw);
1769                 } else {
1770                         pvr2_trace(
1771                                 PVR2_TRACE_ERROR_LEGS,
1772                                 "***WARNING*** pvrusb2 device hardware"
1773                                 " appears to be jammed"
1774                                 " and I can't clear it.");
1775                         pvr2_trace(
1776                                 PVR2_TRACE_ERROR_LEGS,
1777                                 "You might need to power cycle"
1778                                 " the pvrusb2 device"
1779                                 " in order to recover.");
1780                 }
1781         } while (0);
1782         pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_setup(hdw=%p) end",hdw);
1783 }
1784
1785
1786 /* Create and return a structure for interacting with the underlying
1787    hardware */
1788 struct pvr2_hdw *pvr2_hdw_create(struct usb_interface *intf,
1789                                  const struct usb_device_id *devid)
1790 {
1791         unsigned int idx,cnt1,cnt2;
1792         struct pvr2_hdw *hdw;
1793         unsigned int hdw_type;
1794         int valid_std_mask;
1795         struct pvr2_ctrl *cptr;
1796         const struct pvr2_device_desc *hdw_desc;
1797         __u8 ifnum;
1798         struct v4l2_queryctrl qctrl;
1799         struct pvr2_ctl_info *ciptr;
1800
1801         hdw_type = devid - pvr2_device_table;
1802         if (hdw_type >= pvr2_device_count) {
1803                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1804                            "Bogus device type of %u reported",hdw_type);
1805                 return NULL;
1806         }
1807         hdw_desc = pvr2_device_descriptions + hdw_type;
1808
1809         hdw = kzalloc(sizeof(*hdw),GFP_KERNEL);
1810         pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_create: hdw=%p, type \"%s\"",
1811                    hdw,hdw_desc->description);
1812         if (!hdw) goto fail;
1813
1814         init_timer(&hdw->quiescent_timer);
1815         hdw->quiescent_timer.data = (unsigned long)hdw;
1816         hdw->quiescent_timer.function = pvr2_hdw_quiescent_timeout;
1817
1818         init_timer(&hdw->encoder_wait_timer);
1819         hdw->encoder_wait_timer.data = (unsigned long)hdw;
1820         hdw->encoder_wait_timer.function = pvr2_hdw_encoder_wait_timeout;
1821
1822         hdw->master_state = PVR2_STATE_DEAD;
1823
1824         init_waitqueue_head(&hdw->state_wait_data);
1825
1826         hdw->tuner_signal_stale = !0;
1827         cx2341x_fill_defaults(&hdw->enc_ctl_state);
1828
1829         hdw->control_cnt = CTRLDEF_COUNT;
1830         hdw->control_cnt += MPEGDEF_COUNT;
1831         hdw->controls = kzalloc(sizeof(struct pvr2_ctrl) * hdw->control_cnt,
1832                                 GFP_KERNEL);
1833         if (!hdw->controls) goto fail;
1834         hdw->hdw_desc = hdw_desc;
1835         for (idx = 0; idx < hdw->control_cnt; idx++) {
1836                 cptr = hdw->controls + idx;
1837                 cptr->hdw = hdw;
1838         }
1839         for (idx = 0; idx < 32; idx++) {
1840                 hdw->std_mask_ptrs[idx] = hdw->std_mask_names[idx];
1841         }
1842         for (idx = 0; idx < CTRLDEF_COUNT; idx++) {
1843                 cptr = hdw->controls + idx;
1844                 cptr->info = control_defs+idx;
1845         }
1846         /* Define and configure additional controls from cx2341x module. */
1847         hdw->mpeg_ctrl_info = kzalloc(
1848                 sizeof(*(hdw->mpeg_ctrl_info)) * MPEGDEF_COUNT, GFP_KERNEL);
1849         if (!hdw->mpeg_ctrl_info) goto fail;
1850         for (idx = 0; idx < MPEGDEF_COUNT; idx++) {
1851                 cptr = hdw->controls + idx + CTRLDEF_COUNT;
1852                 ciptr = &(hdw->mpeg_ctrl_info[idx].info);
1853                 ciptr->desc = hdw->mpeg_ctrl_info[idx].desc;
1854                 ciptr->name = mpeg_ids[idx].strid;
1855                 ciptr->v4l_id = mpeg_ids[idx].id;
1856                 ciptr->skip_init = !0;
1857                 ciptr->get_value = ctrl_cx2341x_get;
1858                 ciptr->get_v4lflags = ctrl_cx2341x_getv4lflags;
1859                 ciptr->is_dirty = ctrl_cx2341x_is_dirty;
1860                 if (!idx) ciptr->clear_dirty = ctrl_cx2341x_clear_dirty;
1861                 qctrl.id = ciptr->v4l_id;
1862                 cx2341x_ctrl_query(&hdw->enc_ctl_state,&qctrl);
1863                 if (!(qctrl.flags & V4L2_CTRL_FLAG_READ_ONLY)) {
1864                         ciptr->set_value = ctrl_cx2341x_set;
1865                 }
1866                 strncpy(hdw->mpeg_ctrl_info[idx].desc,qctrl.name,
1867                         PVR2_CTLD_INFO_DESC_SIZE);
1868                 hdw->mpeg_ctrl_info[idx].desc[PVR2_CTLD_INFO_DESC_SIZE-1] = 0;
1869                 ciptr->default_value = qctrl.default_value;
1870                 switch (qctrl.type) {
1871                 default:
1872                 case V4L2_CTRL_TYPE_INTEGER:
1873                         ciptr->type = pvr2_ctl_int;
1874                         ciptr->def.type_int.min_value = qctrl.minimum;
1875                         ciptr->def.type_int.max_value = qctrl.maximum;
1876                         break;
1877                 case V4L2_CTRL_TYPE_BOOLEAN:
1878                         ciptr->type = pvr2_ctl_bool;
1879                         break;
1880                 case V4L2_CTRL_TYPE_MENU:
1881                         ciptr->type = pvr2_ctl_enum;
1882                         ciptr->def.type_enum.value_names =
1883                                 cx2341x_ctrl_get_menu(ciptr->v4l_id);
1884                         for (cnt1 = 0;
1885                              ciptr->def.type_enum.value_names[cnt1] != NULL;
1886                              cnt1++) { }
1887                         ciptr->def.type_enum.count = cnt1;
1888                         break;
1889                 }
1890                 cptr->info = ciptr;
1891         }
1892
1893         // Initialize video standard enum dynamic control
1894         cptr = pvr2_hdw_get_ctrl_by_id(hdw,PVR2_CID_STDENUM);
1895         if (cptr) {
1896                 memcpy(&hdw->std_info_enum,cptr->info,
1897                        sizeof(hdw->std_info_enum));
1898                 cptr->info = &hdw->std_info_enum;
1899
1900         }
1901         // Initialize control data regarding video standard masks
1902         valid_std_mask = pvr2_std_get_usable();
1903         for (idx = 0; idx < 32; idx++) {
1904                 if (!(valid_std_mask & (1 << idx))) continue;
1905                 cnt1 = pvr2_std_id_to_str(
1906                         hdw->std_mask_names[idx],
1907                         sizeof(hdw->std_mask_names[idx])-1,
1908                         1 << idx);
1909                 hdw->std_mask_names[idx][cnt1] = 0;
1910         }
1911         cptr = pvr2_hdw_get_ctrl_by_id(hdw,PVR2_CID_STDAVAIL);
1912         if (cptr) {
1913                 memcpy(&hdw->std_info_avail,cptr->info,
1914                        sizeof(hdw->std_info_avail));
1915                 cptr->info = &hdw->std_info_avail;
1916                 hdw->std_info_avail.def.type_bitmask.bit_names =
1917                         hdw->std_mask_ptrs;
1918                 hdw->std_info_avail.def.type_bitmask.valid_bits =
1919                         valid_std_mask;
1920         }
1921         cptr = pvr2_hdw_get_ctrl_by_id(hdw,PVR2_CID_STDCUR);
1922         if (cptr) {
1923                 memcpy(&hdw->std_info_cur,cptr->info,
1924                        sizeof(hdw->std_info_cur));
1925                 cptr->info = &hdw->std_info_cur;
1926                 hdw->std_info_cur.def.type_bitmask.bit_names =
1927                         hdw->std_mask_ptrs;
1928                 hdw->std_info_avail.def.type_bitmask.valid_bits =
1929                         valid_std_mask;
1930         }
1931
1932         hdw->eeprom_addr = -1;
1933         hdw->unit_number = -1;
1934         hdw->v4l_minor_number_video = -1;
1935         hdw->v4l_minor_number_vbi = -1;
1936         hdw->v4l_minor_number_radio = -1;
1937         hdw->ctl_write_buffer = kmalloc(PVR2_CTL_BUFFSIZE,GFP_KERNEL);
1938         if (!hdw->ctl_write_buffer) goto fail;
1939         hdw->ctl_read_buffer = kmalloc(PVR2_CTL_BUFFSIZE,GFP_KERNEL);
1940         if (!hdw->ctl_read_buffer) goto fail;
1941         hdw->ctl_write_urb = usb_alloc_urb(0,GFP_KERNEL);
1942         if (!hdw->ctl_write_urb) goto fail;
1943         hdw->ctl_read_urb = usb_alloc_urb(0,GFP_KERNEL);
1944         if (!hdw->ctl_read_urb) goto fail;
1945
1946         mutex_lock(&pvr2_unit_mtx); do {
1947                 for (idx = 0; idx < PVR_NUM; idx++) {
1948                         if (unit_pointers[idx]) continue;
1949                         hdw->unit_number = idx;
1950                         unit_pointers[idx] = hdw;
1951                         break;
1952                 }
1953         } while (0); mutex_unlock(&pvr2_unit_mtx);
1954
1955         cnt1 = 0;
1956         cnt2 = scnprintf(hdw->name+cnt1,sizeof(hdw->name)-cnt1,"pvrusb2");
1957         cnt1 += cnt2;
1958         if (hdw->unit_number >= 0) {
1959                 cnt2 = scnprintf(hdw->name+cnt1,sizeof(hdw->name)-cnt1,"_%c",
1960                                  ('a' + hdw->unit_number));
1961                 cnt1 += cnt2;
1962         }
1963         if (cnt1 >= sizeof(hdw->name)) cnt1 = sizeof(hdw->name)-1;
1964         hdw->name[cnt1] = 0;
1965
1966         hdw->workqueue = create_singlethread_workqueue(hdw->name);
1967         INIT_WORK(&hdw->workpoll,pvr2_hdw_worker_poll);
1968         INIT_WORK(&hdw->worki2csync,pvr2_hdw_worker_i2c);
1969         INIT_WORK(&hdw->workinit,pvr2_hdw_worker_init);
1970
1971         pvr2_trace(PVR2_TRACE_INIT,"Driver unit number is %d, name is %s",
1972                    hdw->unit_number,hdw->name);
1973
1974         hdw->tuner_type = -1;
1975         hdw->flag_ok = !0;
1976
1977         hdw->usb_intf = intf;
1978         hdw->usb_dev = interface_to_usbdev(intf);
1979
1980         scnprintf(hdw->bus_info,sizeof(hdw->bus_info),
1981                   "usb %s address %d",
1982                   hdw->usb_dev->dev.bus_id,
1983                   hdw->usb_dev->devnum);
1984
1985         ifnum = hdw->usb_intf->cur_altsetting->desc.bInterfaceNumber;
1986         usb_set_interface(hdw->usb_dev,ifnum,0);
1987
1988         mutex_init(&hdw->ctl_lock_mutex);
1989         mutex_init(&hdw->big_lock_mutex);
1990
1991         queue_work(hdw->workqueue,&hdw->workinit);
1992         return hdw;
1993  fail:
1994         if (hdw) {
1995                 del_timer_sync(&hdw->quiescent_timer);
1996                 del_timer_sync(&hdw->encoder_wait_timer);
1997                 if (hdw->workqueue) {
1998                         flush_workqueue(hdw->workqueue);
1999                         destroy_workqueue(hdw->workqueue);
2000                         hdw->workqueue = NULL;
2001                 }
2002                 usb_free_urb(hdw->ctl_read_urb);
2003                 usb_free_urb(hdw->ctl_write_urb);
2004                 kfree(hdw->ctl_read_buffer);
2005                 kfree(hdw->ctl_write_buffer);
2006                 kfree(hdw->controls);
2007                 kfree(hdw->mpeg_ctrl_info);
2008                 kfree(hdw->std_defs);
2009                 kfree(hdw->std_enum_names);
2010                 kfree(hdw);
2011         }
2012         return NULL;
2013 }
2014
2015
2016 /* Remove _all_ associations between this driver and the underlying USB
2017    layer. */
2018 static void pvr2_hdw_remove_usb_stuff(struct pvr2_hdw *hdw)
2019 {
2020         if (hdw->flag_disconnected) return;
2021         pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_remove_usb_stuff: hdw=%p",hdw);
2022         if (hdw->ctl_read_urb) {
2023                 usb_kill_urb(hdw->ctl_read_urb);
2024                 usb_free_urb(hdw->ctl_read_urb);
2025                 hdw->ctl_read_urb = NULL;
2026         }
2027         if (hdw->ctl_write_urb) {
2028                 usb_kill_urb(hdw->ctl_write_urb);
2029                 usb_free_urb(hdw->ctl_write_urb);
2030                 hdw->ctl_write_urb = NULL;
2031         }
2032         if (hdw->ctl_read_buffer) {
2033                 kfree(hdw->ctl_read_buffer);
2034                 hdw->ctl_read_buffer = NULL;
2035         }
2036         if (hdw->ctl_write_buffer) {
2037                 kfree(hdw->ctl_write_buffer);
2038                 hdw->ctl_write_buffer = NULL;
2039         }
2040         hdw->flag_disconnected = !0;
2041         hdw->usb_dev = NULL;
2042         hdw->usb_intf = NULL;
2043         pvr2_hdw_render_useless(hdw);
2044 }
2045
2046
2047 /* Destroy hardware interaction structure */
2048 void pvr2_hdw_destroy(struct pvr2_hdw *hdw)
2049 {
2050         if (!hdw) return;
2051         pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_destroy: hdw=%p",hdw);
2052         del_timer_sync(&hdw->quiescent_timer);
2053         del_timer_sync(&hdw->encoder_wait_timer);
2054         if (hdw->workqueue) {
2055                 flush_workqueue(hdw->workqueue);
2056                 destroy_workqueue(hdw->workqueue);
2057                 hdw->workqueue = NULL;
2058         }
2059         if (hdw->fw_buffer) {
2060                 kfree(hdw->fw_buffer);
2061                 hdw->fw_buffer = NULL;
2062         }
2063         if (hdw->vid_stream) {
2064                 pvr2_stream_destroy(hdw->vid_stream);
2065                 hdw->vid_stream = NULL;
2066         }
2067         if (hdw->decoder_ctrl) {
2068                 hdw->decoder_ctrl->detach(hdw->decoder_ctrl->ctxt);
2069         }
2070         pvr2_i2c_core_done(hdw);
2071         pvr2_hdw_remove_usb_stuff(hdw);
2072         mutex_lock(&pvr2_unit_mtx); do {
2073                 if ((hdw->unit_number >= 0) &&
2074                     (hdw->unit_number < PVR_NUM) &&
2075                     (unit_pointers[hdw->unit_number] == hdw)) {
2076                         unit_pointers[hdw->unit_number] = NULL;
2077                 }
2078         } while (0); mutex_unlock(&pvr2_unit_mtx);
2079         kfree(hdw->controls);
2080         kfree(hdw->mpeg_ctrl_info);
2081         kfree(hdw->std_defs);
2082         kfree(hdw->std_enum_names);
2083         kfree(hdw);
2084 }
2085
2086
2087 int pvr2_hdw_dev_ok(struct pvr2_hdw *hdw)
2088 {
2089         return (hdw && hdw->flag_ok);
2090 }
2091
2092
2093 /* Called when hardware has been unplugged */
2094 void pvr2_hdw_disconnect(struct pvr2_hdw *hdw)
2095 {
2096         pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_disconnect(hdw=%p)",hdw);
2097         LOCK_TAKE(hdw->big_lock);
2098         LOCK_TAKE(hdw->ctl_lock);
2099         pvr2_hdw_remove_usb_stuff(hdw);
2100         LOCK_GIVE(hdw->ctl_lock);
2101         LOCK_GIVE(hdw->big_lock);
2102 }
2103
2104
2105 // Attempt to autoselect an appropriate value for std_enum_cur given
2106 // whatever is currently in std_mask_cur
2107 static void pvr2_hdw_internal_find_stdenum(struct pvr2_hdw *hdw)
2108 {
2109         unsigned int idx;
2110         for (idx = 1; idx < hdw->std_enum_cnt; idx++) {
2111                 if (hdw->std_defs[idx-1].id == hdw->std_mask_cur) {
2112                         hdw->std_enum_cur = idx;
2113                         return;
2114                 }
2115         }
2116         hdw->std_enum_cur = 0;
2117 }
2118
2119
2120 // Calculate correct set of enumerated standards based on currently known
2121 // set of available standards bits.
2122 static void pvr2_hdw_internal_set_std_avail(struct pvr2_hdw *hdw)
2123 {
2124         struct v4l2_standard *newstd;
2125         unsigned int std_cnt;
2126         unsigned int idx;
2127
2128         newstd = pvr2_std_create_enum(&std_cnt,hdw->std_mask_avail);
2129
2130         if (hdw->std_defs) {
2131                 kfree(hdw->std_defs);
2132                 hdw->std_defs = NULL;
2133         }
2134         hdw->std_enum_cnt = 0;
2135         if (hdw->std_enum_names) {
2136                 kfree(hdw->std_enum_names);
2137                 hdw->std_enum_names = NULL;
2138         }
2139
2140         if (!std_cnt) {
2141                 pvr2_trace(
2142                         PVR2_TRACE_ERROR_LEGS,
2143                         "WARNING: Failed to identify any viable standards");
2144         }
2145         hdw->std_enum_names = kmalloc(sizeof(char *)*(std_cnt+1),GFP_KERNEL);
2146         hdw->std_enum_names[0] = "none";
2147         for (idx = 0; idx < std_cnt; idx++) {
2148                 hdw->std_enum_names[idx+1] =
2149                         newstd[idx].name;
2150         }
2151         // Set up the dynamic control for this standard
2152         hdw->std_info_enum.def.type_enum.value_names = hdw->std_enum_names;
2153         hdw->std_info_enum.def.type_enum.count = std_cnt+1;
2154         hdw->std_defs = newstd;
2155         hdw->std_enum_cnt = std_cnt+1;
2156         hdw->std_enum_cur = 0;
2157         hdw->std_info_cur.def.type_bitmask.valid_bits = hdw->std_mask_avail;
2158 }
2159
2160
2161 int pvr2_hdw_get_stdenum_value(struct pvr2_hdw *hdw,
2162                                struct v4l2_standard *std,
2163                                unsigned int idx)
2164 {
2165         int ret = -EINVAL;
2166         if (!idx) return ret;
2167         LOCK_TAKE(hdw->big_lock); do {
2168                 if (idx >= hdw->std_enum_cnt) break;
2169                 idx--;
2170                 memcpy(std,hdw->std_defs+idx,sizeof(*std));
2171                 ret = 0;
2172         } while (0); LOCK_GIVE(hdw->big_lock);
2173         return ret;
2174 }
2175
2176
2177 /* Get the number of defined controls */
2178 unsigned int pvr2_hdw_get_ctrl_count(struct pvr2_hdw *hdw)
2179 {
2180         return hdw->control_cnt;
2181 }
2182
2183
2184 /* Retrieve a control handle given its index (0..count-1) */
2185 struct pvr2_ctrl *pvr2_hdw_get_ctrl_by_index(struct pvr2_hdw *hdw,
2186                                              unsigned int idx)
2187 {
2188         if (idx >= hdw->control_cnt) return NULL;
2189         return hdw->controls + idx;
2190 }
2191
2192
2193 /* Retrieve a control handle given its index (0..count-1) */
2194 struct pvr2_ctrl *pvr2_hdw_get_ctrl_by_id(struct pvr2_hdw *hdw,
2195                                           unsigned int ctl_id)
2196 {
2197         struct pvr2_ctrl *cptr;
2198         unsigned int idx;
2199         int i;
2200
2201         /* This could be made a lot more efficient, but for now... */
2202         for (idx = 0; idx < hdw->control_cnt; idx++) {
2203                 cptr = hdw->controls + idx;
2204                 i = cptr->info->internal_id;
2205                 if (i && (i == ctl_id)) return cptr;
2206         }
2207         return NULL;
2208 }
2209
2210
2211 /* Given a V4L ID, retrieve the control structure associated with it. */
2212 struct pvr2_ctrl *pvr2_hdw_get_ctrl_v4l(struct pvr2_hdw *hdw,unsigned int ctl_id)
2213 {
2214         struct pvr2_ctrl *cptr;
2215         unsigned int idx;
2216         int i;
2217
2218         /* This could be made a lot more efficient, but for now... */
2219         for (idx = 0; idx < hdw->control_cnt; idx++) {
2220                 cptr = hdw->controls + idx;
2221                 i = cptr->info->v4l_id;
2222                 if (i && (i == ctl_id)) return cptr;
2223         }
2224         return NULL;
2225 }
2226
2227
2228 /* Given a V4L ID for its immediate predecessor, retrieve the control
2229    structure associated with it. */
2230 struct pvr2_ctrl *pvr2_hdw_get_ctrl_nextv4l(struct pvr2_hdw *hdw,
2231                                             unsigned int ctl_id)
2232 {
2233         struct pvr2_ctrl *cptr,*cp2;
2234         unsigned int idx;
2235         int i;
2236
2237         /* This could be made a lot more efficient, but for now... */
2238         cp2 = NULL;
2239         for (idx = 0; idx < hdw->control_cnt; idx++) {
2240                 cptr = hdw->controls + idx;
2241                 i = cptr->info->v4l_id;
2242                 if (!i) continue;
2243                 if (i <= ctl_id) continue;
2244                 if (cp2 && (cp2->info->v4l_id < i)) continue;
2245                 cp2 = cptr;
2246         }
2247         return cp2;
2248         return NULL;
2249 }
2250
2251
2252 static const char *get_ctrl_typename(enum pvr2_ctl_type tp)
2253 {
2254         switch (tp) {
2255         case pvr2_ctl_int: return "integer";
2256         case pvr2_ctl_enum: return "enum";
2257         case pvr2_ctl_bool: return "boolean";
2258         case pvr2_ctl_bitmask: return "bitmask";
2259         }
2260         return "";
2261 }
2262
2263
2264 /* Figure out if we need to commit control changes.  If so, mark internal
2265    state flags to indicate this fact and return true.  Otherwise do nothing
2266    else and return false. */
2267 static int pvr2_hdw_commit_setup(struct pvr2_hdw *hdw)
2268 {
2269         unsigned int idx;
2270         struct pvr2_ctrl *cptr;
2271         int value;
2272         int commit_flag = 0;
2273         char buf[100];
2274         unsigned int bcnt,ccnt;
2275
2276         for (idx = 0; idx < hdw->control_cnt; idx++) {
2277                 cptr = hdw->controls + idx;
2278                 if (cptr->info->is_dirty == 0) continue;
2279                 if (!cptr->info->is_dirty(cptr)) continue;
2280                 commit_flag = !0;
2281
2282                 if (!(pvrusb2_debug & PVR2_TRACE_CTL)) continue;
2283                 bcnt = scnprintf(buf,sizeof(buf),"\"%s\" <-- ",
2284                                  cptr->info->name);
2285                 value = 0;
2286                 cptr->info->get_value(cptr,&value);
2287                 pvr2_ctrl_value_to_sym_internal(cptr,~0,value,
2288                                                 buf+bcnt,
2289                                                 sizeof(buf)-bcnt,&ccnt);
2290                 bcnt += ccnt;
2291                 bcnt += scnprintf(buf+bcnt,sizeof(buf)-bcnt," <%s>",
2292                                   get_ctrl_typename(cptr->info->type));
2293                 pvr2_trace(PVR2_TRACE_CTL,
2294                            "/*--TRACE_COMMIT--*/ %.*s",
2295                            bcnt,buf);
2296         }
2297
2298         if (!commit_flag) {
2299                 /* Nothing has changed */
2300                 return 0;
2301         }
2302
2303         hdw->state_pipeline_config = 0;
2304         trace_stbit("state_pipeline_config",hdw->state_pipeline_config);
2305         pvr2_hdw_state_sched(hdw);
2306
2307         return !0;
2308 }
2309
2310
2311 /* Perform all operations needed to commit all control changes.  This must
2312    be performed in synchronization with the pipeline state and is thus
2313    expected to be called as part of the driver's worker thread.  Return
2314    true if commit successful, otherwise return false to indicate that
2315    commit isn't possible at this time. */
2316 static int pvr2_hdw_commit_execute(struct pvr2_hdw *hdw)
2317 {
2318         unsigned int idx;
2319         struct pvr2_ctrl *cptr;
2320         int disruptive_change;
2321
2322         /* When video standard changes, reset the hres and vres values -
2323            but if the user has pending changes there, then let the changes
2324            take priority. */
2325         if (hdw->std_dirty) {
2326                 /* Rewrite the vertical resolution to be appropriate to the
2327                    video standard that has been selected. */
2328                 int nvres;
2329                 if (hdw->std_mask_cur & V4L2_STD_525_60) {
2330                         nvres = 480;
2331                 } else {
2332                         nvres = 576;
2333                 }
2334                 if (nvres != hdw->res_ver_val) {
2335                         hdw->res_ver_val = nvres;
2336                         hdw->res_ver_dirty = !0;
2337                 }
2338         }
2339
2340         /* If any of the below has changed, then we can't do the update
2341            while the pipeline is running.  Pipeline must be paused first
2342            and decoder -> encoder connection be made quiescent before we
2343            can proceed. */
2344         disruptive_change =
2345                 (hdw->std_dirty ||
2346                  hdw->enc_unsafe_stale ||
2347                  hdw->srate_dirty ||
2348                  hdw->res_ver_dirty ||
2349                  hdw->res_hor_dirty ||
2350                  hdw->input_dirty ||
2351                  (hdw->active_stream_type != hdw->desired_stream_type));
2352         if (disruptive_change && !hdw->state_pipeline_idle) {
2353                 /* Pipeline is not idle; we can't proceed.  Arrange to
2354                    cause pipeline to stop so that we can try this again
2355                    later.... */
2356                 hdw->state_pipeline_pause = !0;
2357                 return 0;
2358         }
2359
2360         if (hdw->srate_dirty) {
2361                 /* Write new sample rate into control structure since
2362                  * the master copy is stale.  We must track srate
2363                  * separate from the mpeg control structure because
2364                  * other logic also uses this value. */
2365                 struct v4l2_ext_controls cs;
2366                 struct v4l2_ext_control c1;
2367                 memset(&cs,0,sizeof(cs));
2368                 memset(&c1,0,sizeof(c1));
2369                 cs.controls = &c1;
2370                 cs.count = 1;
2371                 c1.id = V4L2_CID_MPEG_AUDIO_SAMPLING_FREQ;
2372                 c1.value = hdw->srate_val;
2373                 cx2341x_ext_ctrls(&hdw->enc_ctl_state, 0, &cs,VIDIOC_S_EXT_CTRLS);
2374         }
2375
2376         /* Scan i2c core at this point - before we clear all the dirty
2377            bits.  Various parts of the i2c core will notice dirty bits as
2378            appropriate and arrange to broadcast or directly send updates to
2379            the client drivers in order to keep everything in sync */
2380         pvr2_i2c_core_check_stale(hdw);
2381
2382         for (idx = 0; idx < hdw->control_cnt; idx++) {
2383                 cptr = hdw->controls + idx;
2384                 if (!cptr->info->clear_dirty) continue;
2385                 cptr->info->clear_dirty(cptr);
2386         }
2387
2388         if (hdw->active_stream_type != hdw->desired_stream_type) {
2389                 /* Handle any side effects of stream config here */
2390                 hdw->active_stream_type = hdw->desired_stream_type;
2391         }
2392
2393         /* Now execute i2c core update */
2394         pvr2_i2c_core_sync(hdw);
2395
2396         if (hdw->state_encoder_run) {
2397                 /* If encoder isn't running, then this will get worked out
2398                    later when we start the encoder. */
2399                 if (pvr2_encoder_adjust(hdw) < 0) return !0;
2400         }
2401
2402         hdw->state_pipeline_config = !0;
2403         trace_stbit("state_pipeline_config",hdw->state_pipeline_config);
2404         return !0;
2405 }
2406
2407
2408 int pvr2_hdw_commit_ctl(struct pvr2_hdw *hdw)
2409 {
2410         int fl;
2411         LOCK_TAKE(hdw->big_lock);
2412         fl = pvr2_hdw_commit_setup(hdw);
2413         LOCK_GIVE(hdw->big_lock);
2414         if (!fl) return 0;
2415         return pvr2_hdw_wait(hdw,0);
2416 }
2417
2418
2419 static void pvr2_hdw_worker_i2c(struct work_struct *work)
2420 {
2421         struct pvr2_hdw *hdw = container_of(work,struct pvr2_hdw,worki2csync);
2422         LOCK_TAKE(hdw->big_lock); do {
2423                 pvr2_i2c_core_sync(hdw);
2424         } while (0); LOCK_GIVE(hdw->big_lock);
2425 }
2426
2427
2428 static void pvr2_hdw_worker_poll(struct work_struct *work)
2429 {
2430         int fl = 0;
2431         struct pvr2_hdw *hdw = container_of(work,struct pvr2_hdw,workpoll);
2432         LOCK_TAKE(hdw->big_lock); do {
2433                 fl = pvr2_hdw_state_eval(hdw);
2434         } while (0); LOCK_GIVE(hdw->big_lock);
2435         if (fl && hdw->state_func) {
2436                 hdw->state_func(hdw->state_data);
2437         }
2438 }
2439
2440
2441 static void pvr2_hdw_worker_init(struct work_struct *work)
2442 {
2443         struct pvr2_hdw *hdw = container_of(work,struct pvr2_hdw,workinit);
2444         LOCK_TAKE(hdw->big_lock); do {
2445                 pvr2_hdw_setup(hdw);
2446         } while (0); LOCK_GIVE(hdw->big_lock);
2447 }
2448
2449
2450 static int pvr2_hdw_wait(struct pvr2_hdw *hdw,int state)
2451 {
2452         return wait_event_interruptible(
2453                 hdw->state_wait_data,
2454                 (hdw->state_stale == 0) &&
2455                 (!state || (hdw->master_state != state)));
2456 }
2457
2458
2459 void pvr2_hdw_set_state_callback(struct pvr2_hdw *hdw,
2460                                  void (*callback_func)(void *),
2461                                  void *callback_data)
2462 {
2463         LOCK_TAKE(hdw->big_lock); do {
2464                 hdw->state_data = callback_data;
2465                 hdw->state_func = callback_func;
2466         } while (0); LOCK_GIVE(hdw->big_lock);
2467 }
2468
2469
2470 /* Return name for this driver instance */
2471 const char *pvr2_hdw_get_driver_name(struct pvr2_hdw *hdw)
2472 {
2473         return hdw->name;
2474 }
2475
2476
2477 const char *pvr2_hdw_get_desc(struct pvr2_hdw *hdw)
2478 {
2479         return hdw->hdw_desc->description;
2480 }
2481
2482
2483 const char *pvr2_hdw_get_type(struct pvr2_hdw *hdw)
2484 {
2485         return hdw->hdw_desc->shortname;
2486 }
2487
2488
2489 int pvr2_hdw_is_hsm(struct pvr2_hdw *hdw)
2490 {
2491         int result;
2492         LOCK_TAKE(hdw->ctl_lock); do {
2493                 hdw->cmd_buffer[0] = FX2CMD_GET_USB_SPEED;
2494                 result = pvr2_send_request(hdw,
2495                                            hdw->cmd_buffer,1,
2496                                            hdw->cmd_buffer,1);
2497                 if (result < 0) break;
2498                 result = (hdw->cmd_buffer[0] != 0);
2499         } while(0); LOCK_GIVE(hdw->ctl_lock);
2500         return result;
2501 }
2502
2503
2504 /* Execute poll of tuner status */
2505 void pvr2_hdw_execute_tuner_poll(struct pvr2_hdw *hdw)
2506 {
2507         LOCK_TAKE(hdw->big_lock); do {
2508                 pvr2_i2c_core_status_poll(hdw);
2509         } while (0); LOCK_GIVE(hdw->big_lock);
2510 }
2511
2512
2513 /* Return information about the tuner */
2514 int pvr2_hdw_get_tuner_status(struct pvr2_hdw *hdw,struct v4l2_tuner *vtp)
2515 {
2516         LOCK_TAKE(hdw->big_lock); do {
2517                 if (hdw->tuner_signal_stale) {
2518                         pvr2_i2c_core_status_poll(hdw);
2519                 }
2520                 memcpy(vtp,&hdw->tuner_signal_info,sizeof(struct v4l2_tuner));
2521         } while (0); LOCK_GIVE(hdw->big_lock);
2522         return 0;
2523 }
2524
2525
2526 /* Get handle to video output stream */
2527 struct pvr2_stream *pvr2_hdw_get_video_stream(struct pvr2_hdw *hp)
2528 {
2529         return hp->vid_stream;
2530 }
2531
2532
2533 void pvr2_hdw_trigger_module_log(struct pvr2_hdw *hdw)
2534 {
2535         int nr = pvr2_hdw_get_unit_number(hdw);
2536         LOCK_TAKE(hdw->big_lock); do {
2537                 hdw->log_requested = !0;
2538                 printk(KERN_INFO "pvrusb2: =================  START STATUS CARD #%d  =================\n", nr);
2539                 pvr2_i2c_core_check_stale(hdw);
2540                 hdw->log_requested = 0;
2541                 pvr2_i2c_core_sync(hdw);
2542                 pvr2_trace(PVR2_TRACE_INFO,"cx2341x config:");
2543                 cx2341x_log_status(&hdw->enc_ctl_state, "pvrusb2");
2544                 pvr2_hdw_state_log_state(hdw);
2545                 printk(KERN_INFO "pvrusb2: ==================  END STATUS CARD #%d  ==================\n", nr);
2546         } while (0); LOCK_GIVE(hdw->big_lock);
2547 }
2548
2549
2550 /* Grab EEPROM contents, needed for direct method. */
2551 #define EEPROM_SIZE 8192
2552 #define trace_eeprom(...) pvr2_trace(PVR2_TRACE_EEPROM,__VA_ARGS__)
2553 static u8 *pvr2_full_eeprom_fetch(struct pvr2_hdw *hdw)
2554 {
2555         struct i2c_msg msg[2];
2556         u8 *eeprom;
2557         u8 iadd[2];
2558         u8 addr;
2559         u16 eepromSize;
2560         unsigned int offs;
2561         int ret;
2562         int mode16 = 0;
2563         unsigned pcnt,tcnt;
2564         eeprom = kmalloc(EEPROM_SIZE,GFP_KERNEL);
2565         if (!eeprom) {
2566                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2567                            "Failed to allocate memory"
2568                            " required to read eeprom");
2569                 return NULL;
2570         }
2571
2572         trace_eeprom("Value for eeprom addr from controller was 0x%x",
2573                      hdw->eeprom_addr);
2574         addr = hdw->eeprom_addr;
2575         /* Seems that if the high bit is set, then the *real* eeprom
2576            address is shifted right now bit position (noticed this in
2577            newer PVR USB2 hardware) */
2578         if (addr & 0x80) addr >>= 1;
2579
2580         /* FX2 documentation states that a 16bit-addressed eeprom is
2581            expected if the I2C address is an odd number (yeah, this is
2582            strange but it's what they do) */
2583         mode16 = (addr & 1);
2584         eepromSize = (mode16 ? EEPROM_SIZE : 256);
2585         trace_eeprom("Examining %d byte eeprom at location 0x%x"
2586                      " using %d bit addressing",eepromSize,addr,
2587                      mode16 ? 16 : 8);
2588
2589         msg[0].addr = addr;
2590         msg[0].flags = 0;
2591         msg[0].len = mode16 ? 2 : 1;
2592         msg[0].buf = iadd;
2593         msg[1].addr = addr;
2594         msg[1].flags = I2C_M_RD;
2595
2596         /* We have to do the actual eeprom data fetch ourselves, because
2597            (1) we're only fetching part of the eeprom, and (2) if we were
2598            getting the whole thing our I2C driver can't grab it in one
2599            pass - which is what tveeprom is otherwise going to attempt */
2600         memset(eeprom,0,EEPROM_SIZE);
2601         for (tcnt = 0; tcnt < EEPROM_SIZE; tcnt += pcnt) {
2602                 pcnt = 16;
2603                 if (pcnt + tcnt > EEPROM_SIZE) pcnt = EEPROM_SIZE-tcnt;
2604                 offs = tcnt + (eepromSize - EEPROM_SIZE);
2605                 if (mode16) {
2606                         iadd[0] = offs >> 8;
2607                         iadd[1] = offs;
2608                 } else {
2609                         iadd[0] = offs;
2610                 }
2611                 msg[1].len = pcnt;
2612                 msg[1].buf = eeprom+tcnt;
2613                 if ((ret = i2c_transfer(&hdw->i2c_adap,
2614                                         msg,ARRAY_SIZE(msg))) != 2) {
2615                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2616                                    "eeprom fetch set offs err=%d",ret);
2617                         kfree(eeprom);
2618                         return NULL;
2619                 }
2620         }
2621         return eeprom;
2622 }
2623
2624
2625 void pvr2_hdw_cpufw_set_enabled(struct pvr2_hdw *hdw,
2626                                 int prom_flag,
2627                                 int enable_flag)
2628 {
2629         int ret;
2630         u16 address;
2631         unsigned int pipe;
2632         LOCK_TAKE(hdw->big_lock); do {
2633                 if ((hdw->fw_buffer == 0) == !enable_flag) break;
2634
2635                 if (!enable_flag) {
2636                         pvr2_trace(PVR2_TRACE_FIRMWARE,
2637                                    "Cleaning up after CPU firmware fetch");
2638                         kfree(hdw->fw_buffer);
2639                         hdw->fw_buffer = NULL;
2640                         hdw->fw_size = 0;
2641                         if (hdw->fw_cpu_flag) {
2642                                 /* Now release the CPU.  It will disconnect
2643                                    and reconnect later. */
2644                                 pvr2_hdw_cpureset_assert(hdw,0);
2645                         }
2646                         break;
2647                 }
2648
2649                 hdw->fw_cpu_flag = (prom_flag == 0);
2650                 if (hdw->fw_cpu_flag) {
2651                         pvr2_trace(PVR2_TRACE_FIRMWARE,
2652                                    "Preparing to suck out CPU firmware");
2653                         hdw->fw_size = 0x2000;
2654                         hdw->fw_buffer = kzalloc(hdw->fw_size,GFP_KERNEL);
2655                         if (!hdw->fw_buffer) {
2656                                 hdw->fw_size = 0;
2657                                 break;
2658                         }
2659
2660                         /* We have to hold the CPU during firmware upload. */
2661                         pvr2_hdw_cpureset_assert(hdw,1);
2662
2663                         /* download the firmware from address 0000-1fff in 2048
2664                            (=0x800) bytes chunk. */
2665
2666                         pvr2_trace(PVR2_TRACE_FIRMWARE,
2667                                    "Grabbing CPU firmware");
2668                         pipe = usb_rcvctrlpipe(hdw->usb_dev, 0);
2669                         for(address = 0; address < hdw->fw_size;
2670                             address += 0x800) {
2671                                 ret = usb_control_msg(hdw->usb_dev,pipe,
2672                                                       0xa0,0xc0,
2673                                                       address,0,
2674                                                       hdw->fw_buffer+address,
2675                                                       0x800,HZ);
2676                                 if (ret < 0) break;
2677                         }
2678
2679                         pvr2_trace(PVR2_TRACE_FIRMWARE,
2680                                    "Done grabbing CPU firmware");
2681                 } else {
2682                         pvr2_trace(PVR2_TRACE_FIRMWARE,
2683                                    "Sucking down EEPROM contents");
2684                         hdw->fw_buffer = pvr2_full_eeprom_fetch(hdw);
2685                         if (!hdw->fw_buffer) {
2686                                 pvr2_trace(PVR2_TRACE_FIRMWARE,
2687                                            "EEPROM content suck failed.");
2688                                 break;
2689                         }
2690                         hdw->fw_size = EEPROM_SIZE;
2691                         pvr2_trace(PVR2_TRACE_FIRMWARE,
2692                                    "Done sucking down EEPROM contents");
2693                 }
2694
2695         } while (0); LOCK_GIVE(hdw->big_lock);
2696 }
2697
2698
2699 /* Return true if we're in a mode for retrieval CPU firmware */
2700 int pvr2_hdw_cpufw_get_enabled(struct pvr2_hdw *hdw)
2701 {
2702         return hdw->fw_buffer != 0;
2703 }
2704
2705
2706 int pvr2_hdw_cpufw_get(struct pvr2_hdw *hdw,unsigned int offs,
2707                        char *buf,unsigned int cnt)
2708 {
2709         int ret = -EINVAL;
2710         LOCK_TAKE(hdw->big_lock); do {
2711                 if (!buf) break;
2712                 if (!cnt) break;
2713
2714                 if (!hdw->fw_buffer) {
2715                         ret = -EIO;
2716                         break;
2717                 }
2718
2719                 if (offs >= hdw->fw_size) {
2720                         pvr2_trace(PVR2_TRACE_FIRMWARE,
2721                                    "Read firmware data offs=%d EOF",
2722                                    offs);
2723                         ret = 0;
2724                         break;
2725                 }
2726
2727                 if (offs + cnt > hdw->fw_size) cnt = hdw->fw_size - offs;
2728
2729                 memcpy(buf,hdw->fw_buffer+offs,cnt);
2730
2731                 pvr2_trace(PVR2_TRACE_FIRMWARE,
2732                            "Read firmware data offs=%d cnt=%d",
2733                            offs,cnt);
2734                 ret = cnt;
2735         } while (0); LOCK_GIVE(hdw->big_lock);
2736
2737         return ret;
2738 }
2739
2740
2741 int pvr2_hdw_v4l_get_minor_number(struct pvr2_hdw *hdw,
2742                                   enum pvr2_v4l_type index)
2743 {
2744         switch (index) {
2745         case pvr2_v4l_type_video: return hdw->v4l_minor_number_video;
2746         case pvr2_v4l_type_vbi: return hdw->v4l_minor_number_vbi;
2747         case pvr2_v4l_type_radio: return hdw->v4l_minor_number_radio;
2748         default: return -1;
2749         }
2750 }
2751
2752
2753 /* Store a v4l minor device number */
2754 void pvr2_hdw_v4l_store_minor_number(struct pvr2_hdw *hdw,
2755                                      enum pvr2_v4l_type index,int v)
2756 {
2757         switch (index) {
2758         case pvr2_v4l_type_video: hdw->v4l_minor_number_video = v;
2759         case pvr2_v4l_type_vbi: hdw->v4l_minor_number_vbi = v;
2760         case pvr2_v4l_type_radio: hdw->v4l_minor_number_radio = v;
2761         default: break;
2762         }
2763 }
2764
2765
2766 static void pvr2_ctl_write_complete(struct urb *urb)
2767 {
2768         struct pvr2_hdw *hdw = urb->context;
2769         hdw->ctl_write_pend_flag = 0;
2770         if (hdw->ctl_read_pend_flag) return;
2771         complete(&hdw->ctl_done);
2772 }
2773
2774
2775 static void pvr2_ctl_read_complete(struct urb *urb)
2776 {
2777         struct pvr2_hdw *hdw = urb->context;
2778         hdw->ctl_read_pend_flag = 0;
2779         if (hdw->ctl_write_pend_flag) return;
2780         complete(&hdw->ctl_done);
2781 }
2782
2783
2784 static void pvr2_ctl_timeout(unsigned long data)
2785 {
2786         struct pvr2_hdw *hdw = (struct pvr2_hdw *)data;
2787         if (hdw->ctl_write_pend_flag || hdw->ctl_read_pend_flag) {
2788                 hdw->ctl_timeout_flag = !0;
2789                 if (hdw->ctl_write_pend_flag)
2790                         usb_unlink_urb(hdw->ctl_write_urb);
2791                 if (hdw->ctl_read_pend_flag)
2792                         usb_unlink_urb(hdw->ctl_read_urb);
2793         }
2794 }
2795
2796
2797 /* Issue a command and get a response from the device.  This extended
2798    version includes a probe flag (which if set means that device errors
2799    should not be logged or treated as fatal) and a timeout in jiffies.
2800    This can be used to non-lethally probe the health of endpoint 1. */
2801 static int pvr2_send_request_ex(struct pvr2_hdw *hdw,
2802                                 unsigned int timeout,int probe_fl,
2803                                 void *write_data,unsigned int write_len,
2804                                 void *read_data,unsigned int read_len)
2805 {
2806         unsigned int idx;
2807         int status = 0;
2808         struct timer_list timer;
2809         if (!hdw->ctl_lock_held) {
2810                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2811                            "Attempted to execute control transfer"
2812                            " without lock!!");
2813                 return -EDEADLK;
2814         }
2815         if (!hdw->flag_ok && !probe_fl) {
2816                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2817                            "Attempted to execute control transfer"
2818                            " when device not ok");
2819                 return -EIO;
2820         }
2821         if (!(hdw->ctl_read_urb && hdw->ctl_write_urb)) {
2822                 if (!probe_fl) {
2823                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2824                                    "Attempted to execute control transfer"
2825                                    " when USB is disconnected");
2826                 }
2827                 return -ENOTTY;
2828         }
2829
2830         /* Ensure that we have sane parameters */
2831         if (!write_data) write_len = 0;
2832         if (!read_data) read_len = 0;
2833         if (write_len > PVR2_CTL_BUFFSIZE) {
2834                 pvr2_trace(
2835                         PVR2_TRACE_ERROR_LEGS,
2836                         "Attempted to execute %d byte"
2837                         " control-write transfer (limit=%d)",
2838                         write_len,PVR2_CTL_BUFFSIZE);
2839                 return -EINVAL;
2840         }
2841         if (read_len > PVR2_CTL_BUFFSIZE) {
2842                 pvr2_trace(
2843                         PVR2_TRACE_ERROR_LEGS,
2844                         "Attempted to execute %d byte"
2845                         " control-read transfer (limit=%d)",
2846                         write_len,PVR2_CTL_BUFFSIZE);
2847                 return -EINVAL;
2848         }
2849         if ((!write_len) && (!read_len)) {
2850                 pvr2_trace(
2851                         PVR2_TRACE_ERROR_LEGS,
2852                         "Attempted to execute null control transfer?");
2853                 return -EINVAL;
2854         }
2855
2856
2857         hdw->cmd_debug_state = 1;
2858         if (write_len) {
2859                 hdw->cmd_debug_code = ((unsigned char *)write_data)[0];
2860         } else {
2861                 hdw->cmd_debug_code = 0;
2862         }
2863         hdw->cmd_debug_write_len = write_len;
2864         hdw->cmd_debug_read_len = read_len;
2865
2866         /* Initialize common stuff */
2867         init_completion(&hdw->ctl_done);
2868         hdw->ctl_timeout_flag = 0;
2869         hdw->ctl_write_pend_flag = 0;
2870         hdw->ctl_read_pend_flag = 0;
2871         init_timer(&timer);
2872         timer.expires = jiffies + timeout;
2873         timer.data = (unsigned long)hdw;
2874         timer.function = pvr2_ctl_timeout;
2875
2876         if (write_len) {
2877                 hdw->cmd_debug_state = 2;
2878                 /* Transfer write data to internal buffer */
2879                 for (idx = 0; idx < write_len; idx++) {
2880                         hdw->ctl_write_buffer[idx] =
2881                                 ((unsigned char *)write_data)[idx];
2882                 }
2883                 /* Initiate a write request */
2884                 usb_fill_bulk_urb(hdw->ctl_write_urb,
2885                                   hdw->usb_dev,
2886                                   usb_sndbulkpipe(hdw->usb_dev,
2887                                                   PVR2_CTL_WRITE_ENDPOINT),
2888                                   hdw->ctl_write_buffer,
2889                                   write_len,
2890                                   pvr2_ctl_write_complete,
2891                                   hdw);
2892                 hdw->ctl_write_urb->actual_length = 0;
2893                 hdw->ctl_write_pend_flag = !0;
2894                 status = usb_submit_urb(hdw->ctl_write_urb,GFP_KERNEL);
2895                 if (status < 0) {
2896                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2897                                    "Failed to submit write-control"
2898                                    " URB status=%d",status);
2899                         hdw->ctl_write_pend_flag = 0;
2900                         goto done;
2901                 }
2902         }
2903
2904         if (read_len) {
2905                 hdw->cmd_debug_state = 3;
2906                 memset(hdw->ctl_read_buffer,0x43,read_len);
2907                 /* Initiate a read request */
2908                 usb_fill_bulk_urb(hdw->ctl_read_urb,
2909                                   hdw->usb_dev,
2910                                   usb_rcvbulkpipe(hdw->usb_dev,
2911                                                   PVR2_CTL_READ_ENDPOINT),
2912                                   hdw->ctl_read_buffer,
2913                                   read_len,
2914                                   pvr2_ctl_read_complete,
2915                                   hdw);
2916                 hdw->ctl_read_urb->actual_length = 0;
2917                 hdw->ctl_read_pend_flag = !0;
2918                 status = usb_submit_urb(hdw->ctl_read_urb,GFP_KERNEL);
2919                 if (status < 0) {
2920                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2921                                    "Failed to submit read-control"
2922                                    " URB status=%d",status);
2923                         hdw->ctl_read_pend_flag = 0;
2924                         goto done;
2925                 }
2926         }
2927
2928         /* Start timer */
2929         add_timer(&timer);
2930
2931         /* Now wait for all I/O to complete */
2932         hdw->cmd_debug_state = 4;
2933         while (hdw->ctl_write_pend_flag || hdw->ctl_read_pend_flag) {
2934                 wait_for_completion(&hdw->ctl_done);
2935         }
2936         hdw->cmd_debug_state = 5;
2937
2938         /* Stop timer */
2939         del_timer_sync(&timer);
2940
2941         hdw->cmd_debug_state = 6;
2942         status = 0;
2943
2944         if (hdw->ctl_timeout_flag) {
2945                 status = -ETIMEDOUT;
2946                 if (!probe_fl) {
2947                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2948                                    "Timed out control-write");
2949                 }
2950                 goto done;
2951         }
2952
2953         if (write_len) {
2954                 /* Validate results of write request */
2955                 if ((hdw->ctl_write_urb->status != 0) &&
2956                     (hdw->ctl_write_urb->status != -ENOENT) &&
2957                     (hdw->ctl_write_urb->status != -ESHUTDOWN) &&
2958                     (hdw->ctl_write_urb->status != -ECONNRESET)) {
2959                         /* USB subsystem is reporting some kind of failure
2960                            on the write */
2961                         status = hdw->ctl_write_urb->status;
2962                         if (!probe_fl) {
2963                                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2964                                            "control-write URB failure,"
2965                                            " status=%d",
2966                                            status);
2967                         }
2968                         goto done;
2969                 }
2970                 if (hdw->ctl_write_urb->actual_length < write_len) {
2971                         /* Failed to write enough data */
2972                         status = -EIO;
2973                         if (!probe_fl) {
2974                                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2975                                            "control-write URB short,"
2976                                            " expected=%d got=%d",
2977                                            write_len,
2978                                            hdw->ctl_write_urb->actual_length);
2979                         }
2980                         goto done;
2981                 }
2982         }
2983         if (read_len) {
2984                 /* Validate results of read request */
2985                 if ((hdw->ctl_read_urb->status != 0) &&
2986                     (hdw->ctl_read_urb->status != -ENOENT) &&
2987                     (hdw->ctl_read_urb->status != -ESHUTDOWN) &&
2988                     (hdw->ctl_read_urb->status != -ECONNRESET)) {
2989                         /* USB subsystem is reporting some kind of failure
2990                            on the read */
2991                         status = hdw->ctl_read_urb->status;
2992                         if (!probe_fl) {
2993                                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2994                                            "control-read URB failure,"
2995                                            " status=%d",
2996                                            status);
2997                         }
2998                         goto done;
2999                 }
3000                 if (hdw->ctl_read_urb->actual_length < read_len) {
3001                         /* Failed to read enough data */
3002                         status = -EIO;
3003                         if (!probe_fl) {
3004                                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3005                                            "control-read URB short,"
3006                                            " expected=%d got=%d",
3007                                            read_len,
3008                                            hdw->ctl_read_urb->actual_length);
3009                         }
3010                         goto done;
3011                 }
3012                 /* Transfer retrieved data out from internal buffer */
3013                 for (idx = 0; idx < read_len; idx++) {
3014                         ((unsigned char *)read_data)[idx] =
3015                                 hdw->ctl_read_buffer[idx];
3016                 }
3017         }
3018
3019  done:
3020
3021         hdw->cmd_debug_state = 0;
3022         if ((status < 0) && (!probe_fl)) {
3023                 pvr2_hdw_render_useless(hdw);
3024         }
3025         return status;
3026 }
3027
3028
3029 int pvr2_send_request(struct pvr2_hdw *hdw,
3030                       void *write_data,unsigned int write_len,
3031                       void *read_data,unsigned int read_len)
3032 {
3033         return pvr2_send_request_ex(hdw,HZ*4,0,
3034                                     write_data,write_len,
3035                                     read_data,read_len);
3036 }
3037
3038 int pvr2_write_register(struct pvr2_hdw *hdw, u16 reg, u32 data)
3039 {
3040         int ret;
3041
3042         LOCK_TAKE(hdw->ctl_lock);
3043
3044         hdw->cmd_buffer[0] = FX2CMD_REG_WRITE;  /* write register prefix */
3045         PVR2_DECOMPOSE_LE(hdw->cmd_buffer,1,data);
3046         hdw->cmd_buffer[5] = 0;
3047         hdw->cmd_buffer[6] = (reg >> 8) & 0xff;
3048         hdw->cmd_buffer[7] = reg & 0xff;
3049
3050
3051         ret = pvr2_send_request(hdw, hdw->cmd_buffer, 8, hdw->cmd_buffer, 0);
3052
3053         LOCK_GIVE(hdw->ctl_lock);
3054
3055         return ret;
3056 }
3057
3058
3059 static int pvr2_read_register(struct pvr2_hdw *hdw, u16 reg, u32 *data)
3060 {
3061         int ret = 0;
3062
3063         LOCK_TAKE(hdw->ctl_lock);
3064
3065         hdw->cmd_buffer[0] = FX2CMD_REG_READ;  /* read register prefix */
3066         hdw->cmd_buffer[1] = 0;
3067         hdw->cmd_buffer[2] = 0;
3068         hdw->cmd_buffer[3] = 0;
3069         hdw->cmd_buffer[4] = 0;
3070         hdw->cmd_buffer[5] = 0;
3071         hdw->cmd_buffer[6] = (reg >> 8) & 0xff;
3072         hdw->cmd_buffer[7] = reg & 0xff;
3073
3074         ret |= pvr2_send_request(hdw, hdw->cmd_buffer, 8, hdw->cmd_buffer, 4);
3075         *data = PVR2_COMPOSE_LE(hdw->cmd_buffer,0);
3076
3077         LOCK_GIVE(hdw->ctl_lock);
3078
3079         return ret;
3080 }
3081
3082
3083 void pvr2_hdw_render_useless(struct pvr2_hdw *hdw)
3084 {
3085         if (!hdw->flag_ok) return;
3086         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3087                    "Device being rendered inoperable");
3088         if (hdw->vid_stream) {
3089                 pvr2_stream_setup(hdw->vid_stream,NULL,0,0);
3090         }
3091         hdw->flag_ok = 0;
3092         trace_stbit("flag_ok",hdw->flag_ok);
3093         pvr2_hdw_state_sched(hdw);
3094 }
3095
3096
3097 void pvr2_hdw_device_reset(struct pvr2_hdw *hdw)
3098 {
3099         int ret;
3100         pvr2_trace(PVR2_TRACE_INIT,"Performing a device reset...");
3101         ret = usb_lock_device_for_reset(hdw->usb_dev,NULL);
3102         if (ret == 1) {
3103                 ret = usb_reset_device(hdw->usb_dev);
3104                 usb_unlock_device(hdw->usb_dev);
3105         } else {
3106                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3107                            "Failed to lock USB device ret=%d",ret);
3108         }
3109         if (init_pause_msec) {
3110                 pvr2_trace(PVR2_TRACE_INFO,
3111                            "Waiting %u msec for hardware to settle",
3112                            init_pause_msec);
3113                 msleep(init_pause_msec);
3114         }
3115
3116 }
3117
3118
3119 void pvr2_hdw_cpureset_assert(struct pvr2_hdw *hdw,int val)
3120 {
3121         char da[1];
3122         unsigned int pipe;
3123         int ret;
3124
3125         if (!hdw->usb_dev) return;
3126
3127         pvr2_trace(PVR2_TRACE_INIT,"cpureset_assert(%d)",val);
3128
3129         da[0] = val ? 0x01 : 0x00;
3130
3131         /* Write the CPUCS register on the 8051.  The lsb of the register
3132            is the reset bit; a 1 asserts reset while a 0 clears it. */
3133         pipe = usb_sndctrlpipe(hdw->usb_dev, 0);
3134         ret = usb_control_msg(hdw->usb_dev,pipe,0xa0,0x40,0xe600,0,da,1,HZ);
3135         if (ret < 0) {
3136                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3137                            "cpureset_assert(%d) error=%d",val,ret);
3138                 pvr2_hdw_render_useless(hdw);
3139         }
3140 }
3141
3142
3143 int pvr2_hdw_cmd_deep_reset(struct pvr2_hdw *hdw)
3144 {
3145         int status;
3146         LOCK_TAKE(hdw->ctl_lock); do {
3147                 pvr2_trace(PVR2_TRACE_INIT,"Requesting uproc hard reset");
3148                 hdw->cmd_buffer[0] = FX2CMD_DEEP_RESET;
3149                 status = pvr2_send_request(hdw,hdw->cmd_buffer,1,NULL,0);
3150         } while (0); LOCK_GIVE(hdw->ctl_lock);
3151         return status;
3152 }
3153
3154
3155 int pvr2_hdw_cmd_powerup(struct pvr2_hdw *hdw)
3156 {
3157         int status;
3158         LOCK_TAKE(hdw->ctl_lock); do {
3159                 pvr2_trace(PVR2_TRACE_INIT,"Requesting powerup");
3160                 hdw->cmd_buffer[0] = FX2CMD_POWER_ON;
3161                 status = pvr2_send_request(hdw,hdw->cmd_buffer,1,NULL,0);
3162         } while (0); LOCK_GIVE(hdw->ctl_lock);
3163         return status;
3164 }
3165
3166
3167 int pvr2_hdw_cmd_decoder_reset(struct pvr2_hdw *hdw)
3168 {
3169         if (!hdw->decoder_ctrl) {
3170                 pvr2_trace(PVR2_TRACE_INIT,
3171                            "Unable to reset decoder: nothing attached");
3172                 return -ENOTTY;
3173         }
3174
3175         if (!hdw->decoder_ctrl->force_reset) {
3176                 pvr2_trace(PVR2_TRACE_INIT,
3177                            "Unable to reset decoder: not implemented");
3178                 return -ENOTTY;
3179         }
3180
3181         pvr2_trace(PVR2_TRACE_INIT,
3182                    "Requesting decoder reset");
3183         hdw->decoder_ctrl->force_reset(hdw->decoder_ctrl->ctxt);
3184         return 0;
3185 }
3186
3187
3188 /* Stop / start video stream transport */
3189 static int pvr2_hdw_cmd_usbstream(struct pvr2_hdw *hdw,int runFl)
3190 {
3191         int status;
3192         LOCK_TAKE(hdw->ctl_lock); do {
3193                 hdw->cmd_buffer[0] =
3194                         (runFl ? FX2CMD_STREAMING_ON : FX2CMD_STREAMING_OFF);
3195                 status = pvr2_send_request(hdw,hdw->cmd_buffer,1,NULL,0);
3196         } while (0); LOCK_GIVE(hdw->ctl_lock);
3197         return status;
3198 }
3199
3200
3201 /* Evaluate whether or not state_encoder_ok can change */
3202 static int state_eval_encoder_ok(struct pvr2_hdw *hdw)
3203 {
3204         if (hdw->state_encoder_ok) return 0;
3205         if (hdw->flag_tripped) return 0;
3206         if (hdw->state_encoder_run) return 0;
3207         if (hdw->state_encoder_config) return 0;
3208         if (hdw->state_decoder_run) return 0;
3209         if (hdw->state_usbstream_run) return 0;
3210         if (pvr2_upload_firmware2(hdw) < 0) {
3211                 hdw->flag_tripped = !0;
3212                 trace_stbit("flag_tripped",hdw->flag_tripped);
3213                 return !0;
3214         }
3215         hdw->state_encoder_ok = !0;
3216         trace_stbit("state_encoder_ok",hdw->state_encoder_ok);
3217         return !0;
3218 }
3219
3220
3221 /* Evaluate whether or not state_encoder_config can change */
3222 static int state_eval_encoder_config(struct pvr2_hdw *hdw)
3223 {
3224         if (hdw->state_encoder_config) {
3225                 if (hdw->state_encoder_ok) {
3226                         if (hdw->state_pipeline_req &&
3227                             !hdw->state_pipeline_pause) return 0;
3228                 }
3229                 hdw->state_encoder_config = 0;
3230                 hdw->state_encoder_waitok = 0;
3231                 trace_stbit("state_encoder_waitok",hdw->state_encoder_waitok);
3232                 /* paranoia - solve race if timer just completed */
3233                 del_timer_sync(&hdw->encoder_wait_timer);
3234         } else {
3235                 if (!hdw->state_encoder_ok ||
3236                     !hdw->state_pipeline_idle ||
3237                     hdw->state_pipeline_pause ||
3238                     !hdw->state_pipeline_req ||
3239                     !hdw->state_pipeline_config) {
3240                         /* We must reset the enforced wait interval if
3241                            anything has happened that might have disturbed
3242                            the encoder.  This should be a rare case. */
3243                         if (timer_pending(&hdw->encoder_wait_timer)) {
3244                                 del_timer_sync(&hdw->encoder_wait_timer);
3245                         }
3246                         if (hdw->state_encoder_waitok) {
3247                                 /* Must clear the state - therefore we did
3248                                    something to a state bit and must also
3249                                    return true. */
3250                                 hdw->state_encoder_waitok = 0;
3251                                 trace_stbit("state_encoder_waitok",
3252                                             hdw->state_encoder_waitok);
3253                                 return !0;
3254                         }
3255                         return 0;
3256                 }
3257                 if (!hdw->state_encoder_waitok) {
3258                         if (!timer_pending(&hdw->encoder_wait_timer)) {
3259                                 /* waitok flag wasn't set and timer isn't
3260                                    running.  Check flag once more to avoid
3261                                    a race then start the timer.  This is
3262                                    the point when we measure out a minimal
3263                                    quiet interval before doing something to
3264                                    the encoder. */
3265                                 if (!hdw->state_encoder_waitok) {
3266                                         hdw->encoder_wait_timer.expires =
3267                                                 jiffies + (HZ*50/1000);
3268                                         add_timer(&hdw->encoder_wait_timer);
3269                                 }
3270                         }
3271                         /* We can't continue until we know we have been
3272                            quiet for the interval measured by this
3273                            timer. */
3274                         return 0;
3275                 }
3276                 pvr2_encoder_configure(hdw);
3277                 if (hdw->state_encoder_ok) hdw->state_encoder_config = !0;
3278         }
3279         trace_stbit("state_encoder_config",hdw->state_encoder_config);
3280         return !0;
3281 }
3282
3283
3284 /* Evaluate whether or not state_encoder_run can change */
3285 static int state_eval_encoder_run(struct pvr2_hdw *hdw)
3286 {
3287         if (hdw->state_encoder_run) {
3288                 if (hdw->state_encoder_ok) {
3289                         if (hdw->state_decoder_run) return 0;
3290                         if (pvr2_encoder_stop(hdw) < 0) return !0;
3291                 }
3292                 hdw->state_encoder_run = 0;
3293         } else {
3294                 if (!hdw->state_encoder_ok) return 0;
3295                 if (!hdw->state_decoder_run) return 0;
3296                 if (pvr2_encoder_start(hdw) < 0) return !0;
3297                 hdw->state_encoder_run = !0;
3298         }
3299         trace_stbit("state_encoder_run",hdw->state_encoder_run);
3300         return !0;
3301 }
3302
3303
3304 /* Timeout function for quiescent timer. */
3305 static void pvr2_hdw_quiescent_timeout(unsigned long data)
3306 {
3307         struct pvr2_hdw *hdw = (struct pvr2_hdw *)data;
3308         hdw->state_decoder_quiescent = !0;
3309         trace_stbit("state_decoder_quiescent",hdw->state_decoder_quiescent);
3310         hdw->state_stale = !0;
3311         queue_work(hdw->workqueue,&hdw->workpoll);
3312 }
3313
3314
3315 /* Timeout function for encoder wait timer. */
3316 static void pvr2_hdw_encoder_wait_timeout(unsigned long data)
3317 {
3318         struct pvr2_hdw *hdw = (struct pvr2_hdw *)data;
3319         hdw->state_encoder_waitok = !0;
3320         trace_stbit("state_encoder_waitok",hdw->state_encoder_waitok);
3321         hdw->state_stale = !0;
3322         queue_work(hdw->workqueue,&hdw->workpoll);
3323 }
3324
3325
3326 /* Evaluate whether or not state_decoder_run can change */
3327 static int state_eval_decoder_run(struct pvr2_hdw *hdw)
3328 {
3329         if (hdw->state_decoder_run) {
3330                 if (hdw->state_encoder_ok) {
3331                         if (hdw->state_pipeline_req &&
3332                             !hdw->state_pipeline_pause) return 0;
3333                 }
3334                 if (!hdw->flag_decoder_missed) {
3335                         pvr2_decoder_enable(hdw,0);
3336                 }
3337                 hdw->state_decoder_quiescent = 0;
3338                 hdw->state_decoder_run = 0;
3339                 /* paranoia - solve race if timer just completed */
3340                 del_timer_sync(&hdw->quiescent_timer);
3341         } else {
3342                 if (!hdw->state_decoder_quiescent) {
3343                         if (!timer_pending(&hdw->quiescent_timer)) {
3344                                 /* We don't do something about the
3345                                    quiescent timer until right here because
3346                                    we also want to catch cases where the
3347                                    decoder was already not running (like
3348                                    after initialization) as opposed to
3349                                    knowing that we had just stopped it.
3350                                    The second flag check is here to cover a
3351                                    race - the timer could have run and set
3352                                    this flag just after the previous check
3353                                    but before we did the pending check. */
3354                                 if (!hdw->state_decoder_quiescent) {
3355                                         hdw->quiescent_timer.expires =
3356                                                 jiffies + (HZ*50/1000);
3357                                         add_timer(&hdw->quiescent_timer);
3358                                 }
3359                         }
3360                         /* Don't allow decoder to start again until it has
3361                            been quiesced first.  This little detail should
3362                            hopefully further stabilize the encoder. */
3363                         return 0;
3364                 }
3365                 if (!hdw->state_pipeline_req ||
3366                     hdw->state_pipeline_pause ||
3367                     !hdw->state_pipeline_config ||
3368                     !hdw->state_encoder_config ||
3369                     !hdw->state_encoder_ok) return 0;
3370                 del_timer_sync(&hdw->quiescent_timer);
3371                 if (hdw->flag_decoder_missed) return 0;
3372                 if (pvr2_decoder_enable(hdw,!0) < 0) return 0;
3373                 hdw->state_decoder_quiescent = 0;
3374                 hdw->state_decoder_run = !0;
3375         }
3376         trace_stbit("state_decoder_quiescent",hdw->state_decoder_quiescent);
3377         trace_stbit("state_decoder_run",hdw->state_decoder_run);
3378         return !0;
3379 }
3380
3381
3382 /* Evaluate whether or not state_usbstream_run can change */
3383 static int state_eval_usbstream_run(struct pvr2_hdw *hdw)
3384 {
3385         if (hdw->state_usbstream_run) {
3386                 if (hdw->state_encoder_ok) {
3387                         if (hdw->state_encoder_run) return 0;
3388                 }
3389                 pvr2_hdw_cmd_usbstream(hdw,0);
3390                 hdw->state_usbstream_run = 0;
3391         } else {
3392                 if (!hdw->state_encoder_ok ||
3393                     !hdw->state_encoder_run ||
3394                     !hdw->state_pipeline_req ||
3395                     hdw->state_pipeline_pause) return 0;
3396                 if (pvr2_hdw_cmd_usbstream(hdw,!0) < 0) return 0;
3397                 hdw->state_usbstream_run = !0;
3398         }
3399         trace_stbit("state_usbstream_run",hdw->state_usbstream_run);
3400         return !0;
3401 }
3402
3403
3404 /* Attempt to configure pipeline, if needed */
3405 static int state_eval_pipeline_config(struct pvr2_hdw *hdw)
3406 {
3407         if (hdw->state_pipeline_config ||
3408             hdw->state_pipeline_pause) return 0;
3409         pvr2_hdw_commit_execute(hdw);
3410         return !0;
3411 }
3412
3413
3414 /* Update pipeline idle and pipeline pause tracking states based on other
3415    inputs.  This must be called whenever the other relevant inputs have
3416    changed. */
3417 static int state_update_pipeline_state(struct pvr2_hdw *hdw)
3418 {
3419         unsigned int st;
3420         int updatedFl = 0;
3421         /* Update pipeline state */
3422         st = !(hdw->state_encoder_run ||
3423                hdw->state_decoder_run ||
3424                hdw->state_usbstream_run ||
3425                (!hdw->state_decoder_quiescent));
3426         if (!st != !hdw->state_pipeline_idle) {
3427                 hdw->state_pipeline_idle = st;
3428                 updatedFl = !0;
3429         }
3430         if (hdw->state_pipeline_idle && hdw->state_pipeline_pause) {
3431                 hdw->state_pipeline_pause = 0;
3432                 updatedFl = !0;
3433         }
3434         return updatedFl;
3435 }
3436
3437
3438 typedef int (*state_eval_func)(struct pvr2_hdw *);
3439
3440 /* Set of functions to be run to evaluate various states in the driver. */
3441 const static state_eval_func eval_funcs[] = {
3442         state_eval_pipeline_config,
3443         state_eval_encoder_ok,
3444         state_eval_encoder_config,
3445         state_eval_decoder_run,
3446         state_eval_encoder_run,
3447         state_eval_usbstream_run,
3448 };
3449
3450
3451 /* Process various states and return true if we did anything interesting. */
3452 static int pvr2_hdw_state_update(struct pvr2_hdw *hdw)
3453 {
3454         unsigned int i;
3455         int state_updated = 0;
3456         int check_flag;
3457
3458         if (!hdw->state_stale) return 0;
3459         if ((hdw->fw1_state != FW1_STATE_OK) ||
3460             !hdw->flag_ok) {
3461                 hdw->state_stale = 0;
3462                 return !0;
3463         }
3464         /* This loop is the heart of the entire driver.  It keeps trying to
3465            evaluate various bits of driver state until nothing changes for
3466            one full iteration.  Each "bit of state" tracks some global
3467            aspect of the driver, e.g. whether decoder should run, if
3468            pipeline is configured, usb streaming is on, etc.  We separately
3469            evaluate each of those questions based on other driver state to
3470            arrive at the correct running configuration. */
3471         do {
3472                 check_flag = 0;
3473                 state_update_pipeline_state(hdw);
3474                 /* Iterate over each bit of state */
3475                 for (i = 0; (i<ARRAY_SIZE(eval_funcs)) && hdw->flag_ok; i++) {
3476                         if ((*eval_funcs[i])(hdw)) {
3477                                 check_flag = !0;
3478                                 state_updated = !0;
3479                                 state_update_pipeline_state(hdw);
3480                         }
3481                 }
3482         } while (check_flag && hdw->flag_ok);
3483         hdw->state_stale = 0;
3484         trace_stbit("state_stale",hdw->state_stale);
3485         return state_updated;
3486 }
3487
3488
3489 static unsigned int pvr2_hdw_report_unlocked(struct pvr2_hdw *hdw,int which,
3490                                              char *buf,unsigned int acnt)
3491 {
3492         switch (which) {
3493         case 0:
3494                 return scnprintf(
3495                         buf,acnt,
3496                         "driver:%s%s%s%s%s",
3497                         (hdw->flag_ok ? " <ok>" : " <fail>"),
3498                         (hdw->flag_init_ok ? " <init>" : " <uninitialized>"),
3499                         (hdw->flag_disconnected ? " <disconnected>" :
3500                          " <connected>"),
3501                         (hdw->flag_tripped ? " <tripped>" : ""),
3502                         (hdw->flag_decoder_missed ? " <no decoder>" : ""));
3503         case 1:
3504                 return scnprintf(
3505                         buf,acnt,
3506                         "pipeline:%s%s%s%s",
3507                         (hdw->state_pipeline_idle ? " <idle>" : ""),
3508                         (hdw->state_pipeline_config ?
3509                          " <configok>" : " <stale>"),
3510                         (hdw->state_pipeline_req ? " <req>" : ""),
3511                         (hdw->state_pipeline_pause ? " <pause>" : ""));
3512         case 2:
3513                 return scnprintf(
3514                         buf,acnt,
3515                         "worker:%s%s%s%s%s%s",
3516                         (hdw->state_decoder_run ?
3517                          " <decode:run>" :
3518                          (hdw->state_decoder_quiescent ?
3519                           "" : " <decode:stop>")),
3520                         (hdw->state_decoder_quiescent ?
3521                          " <decode:quiescent>" : ""),
3522                         (hdw->state_encoder_ok ?
3523                          "" : " <encode:init>"),
3524                         (hdw->state_encoder_run ?
3525                          " <encode:run>" : " <encode:stop>"),
3526                         (hdw->state_encoder_config ?
3527                          " <encode:configok>" :
3528                          (hdw->state_encoder_waitok ?
3529                           "" : " <encode:wait>")),
3530                         (hdw->state_usbstream_run ?
3531                          " <usb:run>" : " <usb:stop>"));
3532                 break;
3533         case 3:
3534                 return scnprintf(
3535                         buf,acnt,
3536                         "state: %s",
3537                         pvr2_get_state_name(hdw->master_state));
3538                 break;
3539         default: break;
3540         }
3541         return 0;
3542 }
3543
3544
3545 unsigned int pvr2_hdw_state_report(struct pvr2_hdw *hdw,
3546                                    char *buf,unsigned int acnt)
3547 {
3548         unsigned int bcnt,ccnt,idx;
3549         bcnt = 0;
3550         LOCK_TAKE(hdw->big_lock);
3551         for (idx = 0; ; idx++) {
3552                 ccnt = pvr2_hdw_report_unlocked(hdw,idx,buf,acnt);
3553                 if (!ccnt) break;
3554                 bcnt += ccnt; acnt -= ccnt; buf += ccnt;
3555                 if (!acnt) break;
3556                 buf[0] = '\n'; ccnt = 1;
3557                 bcnt += ccnt; acnt -= ccnt; buf += ccnt;
3558         }
3559         LOCK_GIVE(hdw->big_lock);
3560         return bcnt;
3561 }
3562
3563
3564 static void pvr2_hdw_state_log_state(struct pvr2_hdw *hdw)
3565 {
3566         char buf[128];
3567         unsigned int idx,ccnt;
3568
3569         for (idx = 0; ; idx++) {
3570                 ccnt = pvr2_hdw_report_unlocked(hdw,idx,buf,sizeof(buf));
3571                 if (!ccnt) break;
3572                 printk(KERN_INFO "%s %.*s\n",hdw->name,ccnt,buf);
3573         }
3574 }
3575
3576
3577 /* Evaluate and update the driver's current state, taking various actions
3578    as appropriate for the update. */
3579 static int pvr2_hdw_state_eval(struct pvr2_hdw *hdw)
3580 {
3581         unsigned int st;
3582         int state_updated = 0;
3583         int callback_flag = 0;
3584
3585         pvr2_trace(PVR2_TRACE_STBITS,
3586                    "Drive state check START");
3587         if (pvrusb2_debug & PVR2_TRACE_STBITS) {
3588                 pvr2_hdw_state_log_state(hdw);
3589         }
3590
3591         /* Process all state and get back over disposition */
3592         state_updated = pvr2_hdw_state_update(hdw);
3593
3594         /* Update master state based upon all other states. */
3595         if (!hdw->flag_ok) {
3596                 st = PVR2_STATE_DEAD;
3597         } else if (hdw->fw1_state != FW1_STATE_OK) {
3598                 st = PVR2_STATE_COLD;
3599         } else if (!hdw->state_encoder_ok) {
3600                 st = PVR2_STATE_WARM;
3601         } else if (hdw->flag_tripped || hdw->flag_decoder_missed) {
3602                 st = PVR2_STATE_ERROR;
3603         } else if (hdw->state_encoder_run &&
3604                    hdw->state_decoder_run &&
3605                    hdw->state_usbstream_run) {
3606                 st = PVR2_STATE_RUN;
3607         } else {
3608                 st = PVR2_STATE_READY;
3609         }
3610         if (hdw->master_state != st) {
3611                 pvr2_trace(PVR2_TRACE_STATE,
3612                            "Device state change from %s to %s",
3613                            pvr2_get_state_name(hdw->master_state),
3614                            pvr2_get_state_name(st));
3615                 hdw->master_state = st;
3616                 state_updated = !0;
3617                 callback_flag = !0;
3618         }
3619         if (state_updated) {
3620                 /* Trigger anyone waiting on any state changes here. */
3621                 wake_up(&hdw->state_wait_data);
3622         }
3623
3624         if (pvrusb2_debug & PVR2_TRACE_STBITS) {
3625                 pvr2_hdw_state_log_state(hdw);
3626         }
3627         pvr2_trace(PVR2_TRACE_STBITS,
3628                    "Drive state check DONE callback=%d",callback_flag);
3629
3630         return callback_flag;
3631 }
3632
3633
3634 /* Cause kernel thread to check / update driver state */
3635 static void pvr2_hdw_state_sched(struct pvr2_hdw *hdw)
3636 {
3637         if (hdw->state_stale) return;
3638         hdw->state_stale = !0;
3639         trace_stbit("state_stale",hdw->state_stale);
3640         queue_work(hdw->workqueue,&hdw->workpoll);
3641 }
3642
3643
3644 void pvr2_hdw_get_debug_info_unlocked(const struct pvr2_hdw *hdw,
3645                                       struct pvr2_hdw_debug_info *ptr)
3646 {
3647         ptr->big_lock_held = hdw->big_lock_held;
3648         ptr->ctl_lock_held = hdw->ctl_lock_held;
3649         ptr->flag_disconnected = hdw->flag_disconnected;
3650         ptr->flag_init_ok = hdw->flag_init_ok;
3651         ptr->flag_ok = hdw->flag_ok;
3652         ptr->fw1_state = hdw->fw1_state;
3653         ptr->flag_decoder_missed = hdw->flag_decoder_missed;
3654         ptr->flag_tripped = hdw->flag_tripped;
3655         ptr->state_encoder_ok = hdw->state_encoder_ok;
3656         ptr->state_encoder_run = hdw->state_encoder_run;
3657         ptr->state_decoder_run = hdw->state_decoder_run;
3658         ptr->state_usbstream_run = hdw->state_usbstream_run;
3659         ptr->state_decoder_quiescent = hdw->state_decoder_quiescent;
3660         ptr->state_pipeline_config = hdw->state_pipeline_config;
3661         ptr->state_pipeline_req = hdw->state_pipeline_req;
3662         ptr->state_pipeline_pause = hdw->state_pipeline_pause;
3663         ptr->state_pipeline_idle = hdw->state_pipeline_idle;
3664         ptr->cmd_debug_state = hdw->cmd_debug_state;
3665         ptr->cmd_code = hdw->cmd_debug_code;
3666         ptr->cmd_debug_write_len = hdw->cmd_debug_write_len;
3667         ptr->cmd_debug_read_len = hdw->cmd_debug_read_len;
3668         ptr->cmd_debug_timeout = hdw->ctl_timeout_flag;
3669         ptr->cmd_debug_write_pend = hdw->ctl_write_pend_flag;
3670         ptr->cmd_debug_read_pend = hdw->ctl_read_pend_flag;
3671         ptr->cmd_debug_rstatus = hdw->ctl_read_urb->status;
3672         ptr->cmd_debug_wstatus = hdw->ctl_read_urb->status;
3673 }
3674
3675
3676 void pvr2_hdw_get_debug_info_locked(struct pvr2_hdw *hdw,
3677                                     struct pvr2_hdw_debug_info *ptr)
3678 {
3679         LOCK_TAKE(hdw->ctl_lock); do {
3680                 pvr2_hdw_get_debug_info_unlocked(hdw,ptr);
3681         } while(0); LOCK_GIVE(hdw->ctl_lock);
3682 }
3683
3684
3685 int pvr2_hdw_gpio_get_dir(struct pvr2_hdw *hdw,u32 *dp)
3686 {
3687         return pvr2_read_register(hdw,PVR2_GPIO_DIR,dp);
3688 }
3689
3690
3691 int pvr2_hdw_gpio_get_out(struct pvr2_hdw *hdw,u32 *dp)
3692 {
3693         return pvr2_read_register(hdw,PVR2_GPIO_OUT,dp);
3694 }
3695
3696
3697 int pvr2_hdw_gpio_get_in(struct pvr2_hdw *hdw,u32 *dp)
3698 {
3699         return pvr2_read_register(hdw,PVR2_GPIO_IN,dp);
3700 }
3701
3702
3703 int pvr2_hdw_gpio_chg_dir(struct pvr2_hdw *hdw,u32 msk,u32 val)
3704 {
3705         u32 cval,nval;
3706         int ret;
3707         if (~msk) {
3708                 ret = pvr2_read_register(hdw,PVR2_GPIO_DIR,&cval);
3709                 if (ret) return ret;
3710                 nval = (cval & ~msk) | (val & msk);
3711                 pvr2_trace(PVR2_TRACE_GPIO,
3712                            "GPIO direction changing 0x%x:0x%x"
3713                            " from 0x%x to 0x%x",
3714                            msk,val,cval,nval);
3715         } else {
3716                 nval = val;
3717                 pvr2_trace(PVR2_TRACE_GPIO,
3718                            "GPIO direction changing to 0x%x",nval);
3719         }
3720         return pvr2_write_register(hdw,PVR2_GPIO_DIR,nval);
3721 }
3722
3723
3724 int pvr2_hdw_gpio_chg_out(struct pvr2_hdw *hdw,u32 msk,u32 val)
3725 {
3726         u32 cval,nval;
3727         int ret;
3728         if (~msk) {
3729                 ret = pvr2_read_register(hdw,PVR2_GPIO_OUT,&cval);
3730                 if (ret) return ret;
3731                 nval = (cval & ~msk) | (val & msk);
3732                 pvr2_trace(PVR2_TRACE_GPIO,
3733                            "GPIO output changing 0x%x:0x%x from 0x%x to 0x%x",
3734                            msk,val,cval,nval);
3735         } else {
3736                 nval = val;
3737                 pvr2_trace(PVR2_TRACE_GPIO,
3738                            "GPIO output changing to 0x%x",nval);
3739         }
3740         return pvr2_write_register(hdw,PVR2_GPIO_OUT,nval);
3741 }
3742
3743
3744 /* Find I2C address of eeprom */
3745 static int pvr2_hdw_get_eeprom_addr(struct pvr2_hdw *hdw)
3746 {
3747         int result;
3748         LOCK_TAKE(hdw->ctl_lock); do {
3749                 hdw->cmd_buffer[0] = FX2CMD_GET_EEPROM_ADDR;
3750                 result = pvr2_send_request(hdw,
3751                                            hdw->cmd_buffer,1,
3752                                            hdw->cmd_buffer,1);
3753                 if (result < 0) break;
3754                 result = hdw->cmd_buffer[0];
3755         } while(0); LOCK_GIVE(hdw->ctl_lock);
3756         return result;
3757 }
3758
3759
3760 int pvr2_hdw_register_access(struct pvr2_hdw *hdw,
3761                              u32 match_type, u32 match_chip, u64 reg_id,
3762                              int setFl,u64 *val_ptr)
3763 {
3764 #ifdef CONFIG_VIDEO_ADV_DEBUG
3765         struct pvr2_i2c_client *cp;
3766         struct v4l2_register req;
3767         int stat = 0;
3768         int okFl = 0;
3769
3770         if (!capable(CAP_SYS_ADMIN)) return -EPERM;
3771
3772         req.match_type = match_type;
3773         req.match_chip = match_chip;
3774         req.reg = reg_id;
3775         if (setFl) req.val = *val_ptr;
3776         mutex_lock(&hdw->i2c_list_lock); do {
3777                 list_for_each_entry(cp, &hdw->i2c_clients, list) {
3778                         if (!v4l2_chip_match_i2c_client(
3779                                     cp->client,
3780                                     req.match_type, req.match_chip)) {
3781                                 continue;
3782                         }
3783                         stat = pvr2_i2c_client_cmd(
3784                                 cp,(setFl ? VIDIOC_DBG_S_REGISTER :
3785                                     VIDIOC_DBG_G_REGISTER),&req);
3786                         if (!setFl) *val_ptr = req.val;
3787                         okFl = !0;
3788                         break;
3789                 }
3790         } while (0); mutex_unlock(&hdw->i2c_list_lock);
3791         if (okFl) {
3792                 return stat;
3793         }
3794         return -EINVAL;
3795 #else
3796         return -ENOSYS;
3797 #endif
3798 }
3799
3800
3801 /*
3802   Stuff for Emacs to see, in order to encourage consistent editing style:
3803   *** Local Variables: ***
3804   *** mode: c ***
3805   *** fill-column: 75 ***
3806   *** tab-width: 8 ***
3807   *** c-basic-offset: 8 ***
3808   *** End: ***
3809   */