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