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