]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - drivers/media/video/pvrusb2/pvrusb2-hdw.c
V4L/DVB (8893): pvrusb2: Add comment elaborating on direct use of swab32()
[linux-2.6-omap-h63xx.git] / 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                 /* Some background info: The data being swapped here is a
1317                    firmware image destined for the mpeg encoder chip that
1318                    lives at the other end of a USB endpoint.  The encoder
1319                    chip always talks in 32 bit chunks and its storage is
1320                    organized into 32 bit words.  However from the file
1321                    system to the encoder chip everything is purely a byte
1322                    stream.  The firmware file's contents are always 32 bit
1323                    swapped from what the encoder expects.  Thus the need
1324                    always exists to swap the bytes regardless of the endian
1325                    type of the host processor and therefore swab32() makes
1326                    the most sense. */
1327                 for (icnt = 0; icnt < bcnt/4 ; icnt++)
1328                         ((u32 *)fw_ptr)[icnt] = swab32(((u32 *)fw_ptr)[icnt]);
1329
1330                 ret |= usb_bulk_msg(hdw->usb_dev, pipe, fw_ptr,bcnt,
1331                                     &actual_length, HZ);
1332                 ret |= (actual_length != bcnt);
1333                 if (ret) break;
1334                 fw_done += bcnt;
1335         }
1336
1337         trace_firmware("upload of %s : %i / %i ",
1338                        fw_files[fwidx],fw_done,fw_len);
1339
1340         kfree(fw_ptr);
1341         release_firmware(fw_entry);
1342
1343         if (ret) {
1344                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1345                            "firmware2 upload transfer failure");
1346                 goto done;
1347         }
1348
1349         /* Finish upload */
1350
1351         ret |= pvr2_write_register(hdw, 0x9054, 0xffffffff); /*reset hw blocks*/
1352         ret |= pvr2_write_register(hdw, 0x9058, 0xffffffe8); /*VPU ctrl*/
1353         ret |= pvr2_issue_simple_cmd(hdw,FX2CMD_MEMSEL | (1 << 8) | (0 << 16));
1354
1355         if (ret) {
1356                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1357                            "firmware2 upload post-proc failure");
1358         }
1359
1360  done:
1361         if (hdw->hdw_desc->signal_routing_scheme ==
1362             PVR2_ROUTING_SCHEME_GOTVIEW) {
1363                 /* Ensure that GPIO 11 is set to output for GOTVIEW
1364                    hardware. */
1365                 pvr2_hdw_gpio_chg_dir(hdw,(1 << 11),~0);
1366         }
1367         return ret;
1368 }
1369
1370
1371 static const char *pvr2_get_state_name(unsigned int st)
1372 {
1373         if (st < ARRAY_SIZE(pvr2_state_names)) {
1374                 return pvr2_state_names[st];
1375         }
1376         return "???";
1377 }
1378
1379 static int pvr2_decoder_enable(struct pvr2_hdw *hdw,int enablefl)
1380 {
1381         if (!hdw->decoder_ctrl) {
1382                 if (!hdw->flag_decoder_missed) {
1383                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1384                                    "WARNING: No decoder present");
1385                         hdw->flag_decoder_missed = !0;
1386                         trace_stbit("flag_decoder_missed",
1387                                     hdw->flag_decoder_missed);
1388                 }
1389                 return -EIO;
1390         }
1391         hdw->decoder_ctrl->enable(hdw->decoder_ctrl->ctxt,enablefl);
1392         return 0;
1393 }
1394
1395
1396 void pvr2_hdw_set_decoder(struct pvr2_hdw *hdw,struct pvr2_decoder_ctrl *ptr)
1397 {
1398         if (hdw->decoder_ctrl == ptr) return;
1399         hdw->decoder_ctrl = ptr;
1400         if (hdw->decoder_ctrl && hdw->flag_decoder_missed) {
1401                 hdw->flag_decoder_missed = 0;
1402                 trace_stbit("flag_decoder_missed",
1403                             hdw->flag_decoder_missed);
1404                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1405                            "Decoder has appeared");
1406                 pvr2_hdw_state_sched(hdw);
1407         }
1408 }
1409
1410
1411 int pvr2_hdw_get_state(struct pvr2_hdw *hdw)
1412 {
1413         return hdw->master_state;
1414 }
1415
1416
1417 static int pvr2_hdw_untrip_unlocked(struct pvr2_hdw *hdw)
1418 {
1419         if (!hdw->flag_tripped) return 0;
1420         hdw->flag_tripped = 0;
1421         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1422                    "Clearing driver error statuss");
1423         return !0;
1424 }
1425
1426
1427 int pvr2_hdw_untrip(struct pvr2_hdw *hdw)
1428 {
1429         int fl;
1430         LOCK_TAKE(hdw->big_lock); do {
1431                 fl = pvr2_hdw_untrip_unlocked(hdw);
1432         } while (0); LOCK_GIVE(hdw->big_lock);
1433         if (fl) pvr2_hdw_state_sched(hdw);
1434         return 0;
1435 }
1436
1437
1438
1439
1440 int pvr2_hdw_get_streaming(struct pvr2_hdw *hdw)
1441 {
1442         return hdw->state_pipeline_req != 0;
1443 }
1444
1445
1446 int pvr2_hdw_set_streaming(struct pvr2_hdw *hdw,int enable_flag)
1447 {
1448         int ret,st;
1449         LOCK_TAKE(hdw->big_lock); do {
1450                 pvr2_hdw_untrip_unlocked(hdw);
1451                 if ((!enable_flag) != !(hdw->state_pipeline_req)) {
1452                         hdw->state_pipeline_req = enable_flag != 0;
1453                         pvr2_trace(PVR2_TRACE_START_STOP,
1454                                    "/*--TRACE_STREAM--*/ %s",
1455                                    enable_flag ? "enable" : "disable");
1456                 }
1457                 pvr2_hdw_state_sched(hdw);
1458         } while (0); LOCK_GIVE(hdw->big_lock);
1459         if ((ret = pvr2_hdw_wait(hdw,0)) < 0) return ret;
1460         if (enable_flag) {
1461                 while ((st = hdw->master_state) != PVR2_STATE_RUN) {
1462                         if (st != PVR2_STATE_READY) return -EIO;
1463                         if ((ret = pvr2_hdw_wait(hdw,st)) < 0) return ret;
1464                 }
1465         }
1466         return 0;
1467 }
1468
1469
1470 int pvr2_hdw_set_stream_type(struct pvr2_hdw *hdw,enum pvr2_config config)
1471 {
1472         int fl;
1473         LOCK_TAKE(hdw->big_lock);
1474         if ((fl = (hdw->desired_stream_type != config)) != 0) {
1475                 hdw->desired_stream_type = config;
1476                 hdw->state_pipeline_config = 0;
1477                 trace_stbit("state_pipeline_config",
1478                             hdw->state_pipeline_config);
1479                 pvr2_hdw_state_sched(hdw);
1480         }
1481         LOCK_GIVE(hdw->big_lock);
1482         if (fl) return 0;
1483         return pvr2_hdw_wait(hdw,0);
1484 }
1485
1486
1487 static int get_default_tuner_type(struct pvr2_hdw *hdw)
1488 {
1489         int unit_number = hdw->unit_number;
1490         int tp = -1;
1491         if ((unit_number >= 0) && (unit_number < PVR_NUM)) {
1492                 tp = tuner[unit_number];
1493         }
1494         if (tp < 0) return -EINVAL;
1495         hdw->tuner_type = tp;
1496         hdw->tuner_updated = !0;
1497         return 0;
1498 }
1499
1500
1501 static v4l2_std_id get_default_standard(struct pvr2_hdw *hdw)
1502 {
1503         int unit_number = hdw->unit_number;
1504         int tp = 0;
1505         if ((unit_number >= 0) && (unit_number < PVR_NUM)) {
1506                 tp = video_std[unit_number];
1507                 if (tp) return tp;
1508         }
1509         return 0;
1510 }
1511
1512
1513 static unsigned int get_default_error_tolerance(struct pvr2_hdw *hdw)
1514 {
1515         int unit_number = hdw->unit_number;
1516         int tp = 0;
1517         if ((unit_number >= 0) && (unit_number < PVR_NUM)) {
1518                 tp = tolerance[unit_number];
1519         }
1520         return tp;
1521 }
1522
1523
1524 static int pvr2_hdw_check_firmware(struct pvr2_hdw *hdw)
1525 {
1526         /* Try a harmless request to fetch the eeprom's address over
1527            endpoint 1.  See what happens.  Only the full FX2 image can
1528            respond to this.  If this probe fails then likely the FX2
1529            firmware needs be loaded. */
1530         int result;
1531         LOCK_TAKE(hdw->ctl_lock); do {
1532                 hdw->cmd_buffer[0] = FX2CMD_GET_EEPROM_ADDR;
1533                 result = pvr2_send_request_ex(hdw,HZ*1,!0,
1534                                            hdw->cmd_buffer,1,
1535                                            hdw->cmd_buffer,1);
1536                 if (result < 0) break;
1537         } while(0); LOCK_GIVE(hdw->ctl_lock);
1538         if (result) {
1539                 pvr2_trace(PVR2_TRACE_INIT,
1540                            "Probe of device endpoint 1 result status %d",
1541                            result);
1542         } else {
1543                 pvr2_trace(PVR2_TRACE_INIT,
1544                            "Probe of device endpoint 1 succeeded");
1545         }
1546         return result == 0;
1547 }
1548
1549 struct pvr2_std_hack {
1550         v4l2_std_id pat;  /* Pattern to match */
1551         v4l2_std_id msk;  /* Which bits we care about */
1552         v4l2_std_id std;  /* What additional standards or default to set */
1553 };
1554
1555 /* This data structure labels specific combinations of standards from
1556    tveeprom that we'll try to recognize.  If we recognize one, then assume
1557    a specified default standard to use.  This is here because tveeprom only
1558    tells us about available standards not the intended default standard (if
1559    any) for the device in question.  We guess the default based on what has
1560    been reported as available.  Note that this is only for guessing a
1561    default - which can always be overridden explicitly - and if the user
1562    has otherwise named a default then that default will always be used in
1563    place of this table. */
1564 static const struct pvr2_std_hack std_eeprom_maps[] = {
1565         {       /* PAL(B/G) */
1566                 .pat = V4L2_STD_B|V4L2_STD_GH,
1567                 .std = V4L2_STD_PAL_B|V4L2_STD_PAL_B1|V4L2_STD_PAL_G,
1568         },
1569         {       /* NTSC(M) */
1570                 .pat = V4L2_STD_MN,
1571                 .std = V4L2_STD_NTSC_M,
1572         },
1573         {       /* PAL(I) */
1574                 .pat = V4L2_STD_PAL_I,
1575                 .std = V4L2_STD_PAL_I,
1576         },
1577         {       /* SECAM(L/L') */
1578                 .pat = V4L2_STD_SECAM_L|V4L2_STD_SECAM_LC,
1579                 .std = V4L2_STD_SECAM_L|V4L2_STD_SECAM_LC,
1580         },
1581         {       /* PAL(D/D1/K) */
1582                 .pat = V4L2_STD_DK,
1583                 .std = V4L2_STD_PAL_D|V4L2_STD_PAL_D1|V4L2_STD_PAL_K,
1584         },
1585 };
1586
1587 static void pvr2_hdw_setup_std(struct pvr2_hdw *hdw)
1588 {
1589         char buf[40];
1590         unsigned int bcnt;
1591         v4l2_std_id std1,std2,std3;
1592
1593         std1 = get_default_standard(hdw);
1594         std3 = std1 ? 0 : hdw->hdw_desc->default_std_mask;
1595
1596         bcnt = pvr2_std_id_to_str(buf,sizeof(buf),hdw->std_mask_eeprom);
1597         pvr2_trace(PVR2_TRACE_STD,
1598                    "Supported video standard(s) reported available"
1599                    " in hardware: %.*s",
1600                    bcnt,buf);
1601
1602         hdw->std_mask_avail = hdw->std_mask_eeprom;
1603
1604         std2 = (std1|std3) & ~hdw->std_mask_avail;
1605         if (std2) {
1606                 bcnt = pvr2_std_id_to_str(buf,sizeof(buf),std2);
1607                 pvr2_trace(PVR2_TRACE_STD,
1608                            "Expanding supported video standards"
1609                            " to include: %.*s",
1610                            bcnt,buf);
1611                 hdw->std_mask_avail |= std2;
1612         }
1613
1614         pvr2_hdw_internal_set_std_avail(hdw);
1615
1616         if (std1) {
1617                 bcnt = pvr2_std_id_to_str(buf,sizeof(buf),std1);
1618                 pvr2_trace(PVR2_TRACE_STD,
1619                            "Initial video standard forced to %.*s",
1620                            bcnt,buf);
1621                 hdw->std_mask_cur = std1;
1622                 hdw->std_dirty = !0;
1623                 pvr2_hdw_internal_find_stdenum(hdw);
1624                 return;
1625         }
1626         if (std3) {
1627                 bcnt = pvr2_std_id_to_str(buf,sizeof(buf),std3);
1628                 pvr2_trace(PVR2_TRACE_STD,
1629                            "Initial video standard"
1630                            " (determined by device type): %.*s",bcnt,buf);
1631                 hdw->std_mask_cur = std3;
1632                 hdw->std_dirty = !0;
1633                 pvr2_hdw_internal_find_stdenum(hdw);
1634                 return;
1635         }
1636
1637         {
1638                 unsigned int idx;
1639                 for (idx = 0; idx < ARRAY_SIZE(std_eeprom_maps); idx++) {
1640                         if (std_eeprom_maps[idx].msk ?
1641                             ((std_eeprom_maps[idx].pat ^
1642                              hdw->std_mask_eeprom) &
1643                              std_eeprom_maps[idx].msk) :
1644                             (std_eeprom_maps[idx].pat !=
1645                              hdw->std_mask_eeprom)) continue;
1646                         bcnt = pvr2_std_id_to_str(buf,sizeof(buf),
1647                                                   std_eeprom_maps[idx].std);
1648                         pvr2_trace(PVR2_TRACE_STD,
1649                                    "Initial video standard guessed as %.*s",
1650                                    bcnt,buf);
1651                         hdw->std_mask_cur = std_eeprom_maps[idx].std;
1652                         hdw->std_dirty = !0;
1653                         pvr2_hdw_internal_find_stdenum(hdw);
1654                         return;
1655                 }
1656         }
1657
1658         if (hdw->std_enum_cnt > 1) {
1659                 // Autoselect the first listed standard
1660                 hdw->std_enum_cur = 1;
1661                 hdw->std_mask_cur = hdw->std_defs[hdw->std_enum_cur-1].id;
1662                 hdw->std_dirty = !0;
1663                 pvr2_trace(PVR2_TRACE_STD,
1664                            "Initial video standard auto-selected to %s",
1665                            hdw->std_defs[hdw->std_enum_cur-1].name);
1666                 return;
1667         }
1668
1669         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1670                    "Unable to select a viable initial video standard");
1671 }
1672
1673
1674 static void pvr2_hdw_setup_low(struct pvr2_hdw *hdw)
1675 {
1676         int ret;
1677         unsigned int idx;
1678         struct pvr2_ctrl *cptr;
1679         int reloadFl = 0;
1680         if (hdw->hdw_desc->fx2_firmware.cnt) {
1681                 if (!reloadFl) {
1682                         reloadFl =
1683                                 (hdw->usb_intf->cur_altsetting->desc.bNumEndpoints
1684                                  == 0);
1685                         if (reloadFl) {
1686                                 pvr2_trace(PVR2_TRACE_INIT,
1687                                            "USB endpoint config looks strange"
1688                                            "; possibly firmware needs to be"
1689                                            " loaded");
1690                         }
1691                 }
1692                 if (!reloadFl) {
1693                         reloadFl = !pvr2_hdw_check_firmware(hdw);
1694                         if (reloadFl) {
1695                                 pvr2_trace(PVR2_TRACE_INIT,
1696                                            "Check for FX2 firmware failed"
1697                                            "; possibly firmware needs to be"
1698                                            " loaded");
1699                         }
1700                 }
1701                 if (reloadFl) {
1702                         if (pvr2_upload_firmware1(hdw) != 0) {
1703                                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1704                                            "Failure uploading firmware1");
1705                         }
1706                         return;
1707                 }
1708         }
1709         hdw->fw1_state = FW1_STATE_OK;
1710
1711         if (initusbreset) {
1712                 pvr2_hdw_device_reset(hdw);
1713         }
1714         if (!pvr2_hdw_dev_ok(hdw)) return;
1715
1716         for (idx = 0; idx < hdw->hdw_desc->client_modules.cnt; idx++) {
1717                 request_module(hdw->hdw_desc->client_modules.lst[idx]);
1718         }
1719
1720         if (!hdw->hdw_desc->flag_no_powerup) {
1721                 pvr2_hdw_cmd_powerup(hdw);
1722                 if (!pvr2_hdw_dev_ok(hdw)) return;
1723         }
1724
1725         /* Take the IR chip out of reset, if appropriate */
1726         if (hdw->hdw_desc->ir_scheme == PVR2_IR_SCHEME_ZILOG) {
1727                 pvr2_issue_simple_cmd(hdw,
1728                                       FX2CMD_HCW_ZILOG_RESET |
1729                                       (1 << 8) |
1730                                       ((0) << 16));
1731         }
1732
1733         // This step MUST happen after the earlier powerup step.
1734         pvr2_i2c_core_init(hdw);
1735         if (!pvr2_hdw_dev_ok(hdw)) return;
1736
1737         for (idx = 0; idx < CTRLDEF_COUNT; idx++) {
1738                 cptr = hdw->controls + idx;
1739                 if (cptr->info->skip_init) continue;
1740                 if (!cptr->info->set_value) continue;
1741                 cptr->info->set_value(cptr,~0,cptr->info->default_value);
1742         }
1743
1744         /* Set up special default values for the television and radio
1745            frequencies here.  It's not really important what these defaults
1746            are, but I set them to something usable in the Chicago area just
1747            to make driver testing a little easier. */
1748
1749         hdw->freqValTelevision = default_tv_freq;
1750         hdw->freqValRadio = default_radio_freq;
1751
1752         // Do not use pvr2_reset_ctl_endpoints() here.  It is not
1753         // thread-safe against the normal pvr2_send_request() mechanism.
1754         // (We should make it thread safe).
1755
1756         if (hdw->hdw_desc->flag_has_hauppauge_rom) {
1757                 ret = pvr2_hdw_get_eeprom_addr(hdw);
1758                 if (!pvr2_hdw_dev_ok(hdw)) return;
1759                 if (ret < 0) {
1760                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
1761                                    "Unable to determine location of eeprom,"
1762                                    " skipping");
1763                 } else {
1764                         hdw->eeprom_addr = ret;
1765                         pvr2_eeprom_analyze(hdw);
1766                         if (!pvr2_hdw_dev_ok(hdw)) return;
1767                 }
1768         } else {
1769                 hdw->tuner_type = hdw->hdw_desc->default_tuner_type;
1770                 hdw->tuner_updated = !0;
1771                 hdw->std_mask_eeprom = V4L2_STD_ALL;
1772         }
1773
1774         pvr2_hdw_setup_std(hdw);
1775
1776         if (!get_default_tuner_type(hdw)) {
1777                 pvr2_trace(PVR2_TRACE_INIT,
1778                            "pvr2_hdw_setup: Tuner type overridden to %d",
1779                            hdw->tuner_type);
1780         }
1781
1782         pvr2_i2c_core_check_stale(hdw);
1783         hdw->tuner_updated = 0;
1784
1785         if (!pvr2_hdw_dev_ok(hdw)) return;
1786
1787         if (hdw->hdw_desc->signal_routing_scheme ==
1788             PVR2_ROUTING_SCHEME_GOTVIEW) {
1789                 /* Ensure that GPIO 11 is set to output for GOTVIEW
1790                    hardware. */
1791                 pvr2_hdw_gpio_chg_dir(hdw,(1 << 11),~0);
1792         }
1793
1794         pvr2_hdw_commit_setup(hdw);
1795
1796         hdw->vid_stream = pvr2_stream_create();
1797         if (!pvr2_hdw_dev_ok(hdw)) return;
1798         pvr2_trace(PVR2_TRACE_INIT,
1799                    "pvr2_hdw_setup: video stream is %p",hdw->vid_stream);
1800         if (hdw->vid_stream) {
1801                 idx = get_default_error_tolerance(hdw);
1802                 if (idx) {
1803                         pvr2_trace(PVR2_TRACE_INIT,
1804                                    "pvr2_hdw_setup: video stream %p"
1805                                    " setting tolerance %u",
1806                                    hdw->vid_stream,idx);
1807                 }
1808                 pvr2_stream_setup(hdw->vid_stream,hdw->usb_dev,
1809                                   PVR2_VID_ENDPOINT,idx);
1810         }
1811
1812         if (!pvr2_hdw_dev_ok(hdw)) return;
1813
1814         hdw->flag_init_ok = !0;
1815
1816         pvr2_hdw_state_sched(hdw);
1817 }
1818
1819
1820 /* Set up the structure and attempt to put the device into a usable state.
1821    This can be a time-consuming operation, which is why it is not done
1822    internally as part of the create() step. */
1823 static void pvr2_hdw_setup(struct pvr2_hdw *hdw)
1824 {
1825         pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_setup(hdw=%p) begin",hdw);
1826         do {
1827                 pvr2_hdw_setup_low(hdw);
1828                 pvr2_trace(PVR2_TRACE_INIT,
1829                            "pvr2_hdw_setup(hdw=%p) done, ok=%d init_ok=%d",
1830                            hdw,pvr2_hdw_dev_ok(hdw),hdw->flag_init_ok);
1831                 if (pvr2_hdw_dev_ok(hdw)) {
1832                         if (hdw->flag_init_ok) {
1833                                 pvr2_trace(
1834                                         PVR2_TRACE_INFO,
1835                                         "Device initialization"
1836                                         " completed successfully.");
1837                                 break;
1838                         }
1839                         if (hdw->fw1_state == FW1_STATE_RELOAD) {
1840                                 pvr2_trace(
1841                                         PVR2_TRACE_INFO,
1842                                         "Device microcontroller firmware"
1843                                         " (re)loaded; it should now reset"
1844                                         " and reconnect.");
1845                                 break;
1846                         }
1847                         pvr2_trace(
1848                                 PVR2_TRACE_ERROR_LEGS,
1849                                 "Device initialization was not successful.");
1850                         if (hdw->fw1_state == FW1_STATE_MISSING) {
1851                                 pvr2_trace(
1852                                         PVR2_TRACE_ERROR_LEGS,
1853                                         "Giving up since device"
1854                                         " microcontroller firmware"
1855                                         " appears to be missing.");
1856                                 break;
1857                         }
1858                 }
1859                 if (procreload) {
1860                         pvr2_trace(
1861                                 PVR2_TRACE_ERROR_LEGS,
1862                                 "Attempting pvrusb2 recovery by reloading"
1863                                 " primary firmware.");
1864                         pvr2_trace(
1865                                 PVR2_TRACE_ERROR_LEGS,
1866                                 "If this works, device should disconnect"
1867                                 " and reconnect in a sane state.");
1868                         hdw->fw1_state = FW1_STATE_UNKNOWN;
1869                         pvr2_upload_firmware1(hdw);
1870                 } else {
1871                         pvr2_trace(
1872                                 PVR2_TRACE_ERROR_LEGS,
1873                                 "***WARNING*** pvrusb2 device hardware"
1874                                 " appears to be jammed"
1875                                 " and I can't clear it.");
1876                         pvr2_trace(
1877                                 PVR2_TRACE_ERROR_LEGS,
1878                                 "You might need to power cycle"
1879                                 " the pvrusb2 device"
1880                                 " in order to recover.");
1881                 }
1882         } while (0);
1883         pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_setup(hdw=%p) end",hdw);
1884 }
1885
1886
1887 /* Perform second stage initialization.  Set callback pointer first so that
1888    we can avoid a possible initialization race (if the kernel thread runs
1889    before the callback has been set). */
1890 int pvr2_hdw_initialize(struct pvr2_hdw *hdw,
1891                         void (*callback_func)(void *),
1892                         void *callback_data)
1893 {
1894         LOCK_TAKE(hdw->big_lock); do {
1895                 if (hdw->flag_disconnected) {
1896                         /* Handle a race here: If we're already
1897                            disconnected by this point, then give up.  If we
1898                            get past this then we'll remain connected for
1899                            the duration of initialization since the entire
1900                            initialization sequence is now protected by the
1901                            big_lock. */
1902                         break;
1903                 }
1904                 hdw->state_data = callback_data;
1905                 hdw->state_func = callback_func;
1906                 pvr2_hdw_setup(hdw);
1907         } while (0); LOCK_GIVE(hdw->big_lock);
1908         return hdw->flag_init_ok;
1909 }
1910
1911
1912 /* Create, set up, and return a structure for interacting with the
1913    underlying hardware.  */
1914 struct pvr2_hdw *pvr2_hdw_create(struct usb_interface *intf,
1915                                  const struct usb_device_id *devid)
1916 {
1917         unsigned int idx,cnt1,cnt2,m;
1918         struct pvr2_hdw *hdw;
1919         int valid_std_mask;
1920         struct pvr2_ctrl *cptr;
1921         const struct pvr2_device_desc *hdw_desc;
1922         __u8 ifnum;
1923         struct v4l2_queryctrl qctrl;
1924         struct pvr2_ctl_info *ciptr;
1925
1926         hdw_desc = (const struct pvr2_device_desc *)(devid->driver_info);
1927
1928         hdw = kzalloc(sizeof(*hdw),GFP_KERNEL);
1929         pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_create: hdw=%p, type \"%s\"",
1930                    hdw,hdw_desc->description);
1931         if (!hdw) goto fail;
1932
1933         init_timer(&hdw->quiescent_timer);
1934         hdw->quiescent_timer.data = (unsigned long)hdw;
1935         hdw->quiescent_timer.function = pvr2_hdw_quiescent_timeout;
1936
1937         init_timer(&hdw->encoder_wait_timer);
1938         hdw->encoder_wait_timer.data = (unsigned long)hdw;
1939         hdw->encoder_wait_timer.function = pvr2_hdw_encoder_wait_timeout;
1940
1941         init_timer(&hdw->encoder_run_timer);
1942         hdw->encoder_run_timer.data = (unsigned long)hdw;
1943         hdw->encoder_run_timer.function = pvr2_hdw_encoder_run_timeout;
1944
1945         hdw->master_state = PVR2_STATE_DEAD;
1946
1947         init_waitqueue_head(&hdw->state_wait_data);
1948
1949         hdw->tuner_signal_stale = !0;
1950         cx2341x_fill_defaults(&hdw->enc_ctl_state);
1951
1952         /* Calculate which inputs are OK */
1953         m = 0;
1954         if (hdw_desc->flag_has_analogtuner) m |= 1 << PVR2_CVAL_INPUT_TV;
1955         if (hdw_desc->digital_control_scheme != PVR2_DIGITAL_SCHEME_NONE) {
1956                 m |= 1 << PVR2_CVAL_INPUT_DTV;
1957         }
1958         if (hdw_desc->flag_has_svideo) m |= 1 << PVR2_CVAL_INPUT_SVIDEO;
1959         if (hdw_desc->flag_has_composite) m |= 1 << PVR2_CVAL_INPUT_COMPOSITE;
1960         if (hdw_desc->flag_has_fmradio) m |= 1 << PVR2_CVAL_INPUT_RADIO;
1961         hdw->input_avail_mask = m;
1962         hdw->input_allowed_mask = hdw->input_avail_mask;
1963
1964         /* If not a hybrid device, pathway_state never changes.  So
1965            initialize it here to what it should forever be. */
1966         if (!(hdw->input_avail_mask & (1 << PVR2_CVAL_INPUT_DTV))) {
1967                 hdw->pathway_state = PVR2_PATHWAY_ANALOG;
1968         } else if (!(hdw->input_avail_mask & (1 << PVR2_CVAL_INPUT_TV))) {
1969                 hdw->pathway_state = PVR2_PATHWAY_DIGITAL;
1970         }
1971
1972         hdw->control_cnt = CTRLDEF_COUNT;
1973         hdw->control_cnt += MPEGDEF_COUNT;
1974         hdw->controls = kzalloc(sizeof(struct pvr2_ctrl) * hdw->control_cnt,
1975                                 GFP_KERNEL);
1976         if (!hdw->controls) goto fail;
1977         hdw->hdw_desc = hdw_desc;
1978         for (idx = 0; idx < hdw->control_cnt; idx++) {
1979                 cptr = hdw->controls + idx;
1980                 cptr->hdw = hdw;
1981         }
1982         for (idx = 0; idx < 32; idx++) {
1983                 hdw->std_mask_ptrs[idx] = hdw->std_mask_names[idx];
1984         }
1985         for (idx = 0; idx < CTRLDEF_COUNT; idx++) {
1986                 cptr = hdw->controls + idx;
1987                 cptr->info = control_defs+idx;
1988         }
1989
1990         /* Ensure that default input choice is a valid one. */
1991         m = hdw->input_avail_mask;
1992         if (m) for (idx = 0; idx < (sizeof(m) << 3); idx++) {
1993                 if (!((1 << idx) & m)) continue;
1994                 hdw->input_val = idx;
1995                 break;
1996         }
1997
1998         /* Define and configure additional controls from cx2341x module. */
1999         hdw->mpeg_ctrl_info = kzalloc(
2000                 sizeof(*(hdw->mpeg_ctrl_info)) * MPEGDEF_COUNT, GFP_KERNEL);
2001         if (!hdw->mpeg_ctrl_info) goto fail;
2002         for (idx = 0; idx < MPEGDEF_COUNT; idx++) {
2003                 cptr = hdw->controls + idx + CTRLDEF_COUNT;
2004                 ciptr = &(hdw->mpeg_ctrl_info[idx].info);
2005                 ciptr->desc = hdw->mpeg_ctrl_info[idx].desc;
2006                 ciptr->name = mpeg_ids[idx].strid;
2007                 ciptr->v4l_id = mpeg_ids[idx].id;
2008                 ciptr->skip_init = !0;
2009                 ciptr->get_value = ctrl_cx2341x_get;
2010                 ciptr->get_v4lflags = ctrl_cx2341x_getv4lflags;
2011                 ciptr->is_dirty = ctrl_cx2341x_is_dirty;
2012                 if (!idx) ciptr->clear_dirty = ctrl_cx2341x_clear_dirty;
2013                 qctrl.id = ciptr->v4l_id;
2014                 cx2341x_ctrl_query(&hdw->enc_ctl_state,&qctrl);
2015                 if (!(qctrl.flags & V4L2_CTRL_FLAG_READ_ONLY)) {
2016                         ciptr->set_value = ctrl_cx2341x_set;
2017                 }
2018                 strncpy(hdw->mpeg_ctrl_info[idx].desc,qctrl.name,
2019                         PVR2_CTLD_INFO_DESC_SIZE);
2020                 hdw->mpeg_ctrl_info[idx].desc[PVR2_CTLD_INFO_DESC_SIZE-1] = 0;
2021                 ciptr->default_value = qctrl.default_value;
2022                 switch (qctrl.type) {
2023                 default:
2024                 case V4L2_CTRL_TYPE_INTEGER:
2025                         ciptr->type = pvr2_ctl_int;
2026                         ciptr->def.type_int.min_value = qctrl.minimum;
2027                         ciptr->def.type_int.max_value = qctrl.maximum;
2028                         break;
2029                 case V4L2_CTRL_TYPE_BOOLEAN:
2030                         ciptr->type = pvr2_ctl_bool;
2031                         break;
2032                 case V4L2_CTRL_TYPE_MENU:
2033                         ciptr->type = pvr2_ctl_enum;
2034                         ciptr->def.type_enum.value_names =
2035                                 cx2341x_ctrl_get_menu(&hdw->enc_ctl_state,
2036                                                                 ciptr->v4l_id);
2037                         for (cnt1 = 0;
2038                              ciptr->def.type_enum.value_names[cnt1] != NULL;
2039                              cnt1++) { }
2040                         ciptr->def.type_enum.count = cnt1;
2041                         break;
2042                 }
2043                 cptr->info = ciptr;
2044         }
2045
2046         // Initialize video standard enum dynamic control
2047         cptr = pvr2_hdw_get_ctrl_by_id(hdw,PVR2_CID_STDENUM);
2048         if (cptr) {
2049                 memcpy(&hdw->std_info_enum,cptr->info,
2050                        sizeof(hdw->std_info_enum));
2051                 cptr->info = &hdw->std_info_enum;
2052
2053         }
2054         // Initialize control data regarding video standard masks
2055         valid_std_mask = pvr2_std_get_usable();
2056         for (idx = 0; idx < 32; idx++) {
2057                 if (!(valid_std_mask & (1 << idx))) continue;
2058                 cnt1 = pvr2_std_id_to_str(
2059                         hdw->std_mask_names[idx],
2060                         sizeof(hdw->std_mask_names[idx])-1,
2061                         1 << idx);
2062                 hdw->std_mask_names[idx][cnt1] = 0;
2063         }
2064         cptr = pvr2_hdw_get_ctrl_by_id(hdw,PVR2_CID_STDAVAIL);
2065         if (cptr) {
2066                 memcpy(&hdw->std_info_avail,cptr->info,
2067                        sizeof(hdw->std_info_avail));
2068                 cptr->info = &hdw->std_info_avail;
2069                 hdw->std_info_avail.def.type_bitmask.bit_names =
2070                         hdw->std_mask_ptrs;
2071                 hdw->std_info_avail.def.type_bitmask.valid_bits =
2072                         valid_std_mask;
2073         }
2074         cptr = pvr2_hdw_get_ctrl_by_id(hdw,PVR2_CID_STDCUR);
2075         if (cptr) {
2076                 memcpy(&hdw->std_info_cur,cptr->info,
2077                        sizeof(hdw->std_info_cur));
2078                 cptr->info = &hdw->std_info_cur;
2079                 hdw->std_info_cur.def.type_bitmask.bit_names =
2080                         hdw->std_mask_ptrs;
2081                 hdw->std_info_avail.def.type_bitmask.valid_bits =
2082                         valid_std_mask;
2083         }
2084
2085         hdw->eeprom_addr = -1;
2086         hdw->unit_number = -1;
2087         hdw->v4l_minor_number_video = -1;
2088         hdw->v4l_minor_number_vbi = -1;
2089         hdw->v4l_minor_number_radio = -1;
2090         hdw->ctl_write_buffer = kmalloc(PVR2_CTL_BUFFSIZE,GFP_KERNEL);
2091         if (!hdw->ctl_write_buffer) goto fail;
2092         hdw->ctl_read_buffer = kmalloc(PVR2_CTL_BUFFSIZE,GFP_KERNEL);
2093         if (!hdw->ctl_read_buffer) goto fail;
2094         hdw->ctl_write_urb = usb_alloc_urb(0,GFP_KERNEL);
2095         if (!hdw->ctl_write_urb) goto fail;
2096         hdw->ctl_read_urb = usb_alloc_urb(0,GFP_KERNEL);
2097         if (!hdw->ctl_read_urb) goto fail;
2098
2099         mutex_lock(&pvr2_unit_mtx); do {
2100                 for (idx = 0; idx < PVR_NUM; idx++) {
2101                         if (unit_pointers[idx]) continue;
2102                         hdw->unit_number = idx;
2103                         unit_pointers[idx] = hdw;
2104                         break;
2105                 }
2106         } while (0); mutex_unlock(&pvr2_unit_mtx);
2107
2108         cnt1 = 0;
2109         cnt2 = scnprintf(hdw->name+cnt1,sizeof(hdw->name)-cnt1,"pvrusb2");
2110         cnt1 += cnt2;
2111         if (hdw->unit_number >= 0) {
2112                 cnt2 = scnprintf(hdw->name+cnt1,sizeof(hdw->name)-cnt1,"_%c",
2113                                  ('a' + hdw->unit_number));
2114                 cnt1 += cnt2;
2115         }
2116         if (cnt1 >= sizeof(hdw->name)) cnt1 = sizeof(hdw->name)-1;
2117         hdw->name[cnt1] = 0;
2118
2119         hdw->workqueue = create_singlethread_workqueue(hdw->name);
2120         INIT_WORK(&hdw->workpoll,pvr2_hdw_worker_poll);
2121         INIT_WORK(&hdw->worki2csync,pvr2_hdw_worker_i2c);
2122
2123         pvr2_trace(PVR2_TRACE_INIT,"Driver unit number is %d, name is %s",
2124                    hdw->unit_number,hdw->name);
2125
2126         hdw->tuner_type = -1;
2127         hdw->flag_ok = !0;
2128
2129         hdw->usb_intf = intf;
2130         hdw->usb_dev = interface_to_usbdev(intf);
2131
2132         scnprintf(hdw->bus_info,sizeof(hdw->bus_info),
2133                   "usb %s address %d",
2134                   hdw->usb_dev->dev.bus_id,
2135                   hdw->usb_dev->devnum);
2136
2137         ifnum = hdw->usb_intf->cur_altsetting->desc.bInterfaceNumber;
2138         usb_set_interface(hdw->usb_dev,ifnum,0);
2139
2140         mutex_init(&hdw->ctl_lock_mutex);
2141         mutex_init(&hdw->big_lock_mutex);
2142
2143         return hdw;
2144  fail:
2145         if (hdw) {
2146                 del_timer_sync(&hdw->quiescent_timer);
2147                 del_timer_sync(&hdw->encoder_run_timer);
2148                 del_timer_sync(&hdw->encoder_wait_timer);
2149                 if (hdw->workqueue) {
2150                         flush_workqueue(hdw->workqueue);
2151                         destroy_workqueue(hdw->workqueue);
2152                         hdw->workqueue = NULL;
2153                 }
2154                 usb_free_urb(hdw->ctl_read_urb);
2155                 usb_free_urb(hdw->ctl_write_urb);
2156                 kfree(hdw->ctl_read_buffer);
2157                 kfree(hdw->ctl_write_buffer);
2158                 kfree(hdw->controls);
2159                 kfree(hdw->mpeg_ctrl_info);
2160                 kfree(hdw->std_defs);
2161                 kfree(hdw->std_enum_names);
2162                 kfree(hdw);
2163         }
2164         return NULL;
2165 }
2166
2167
2168 /* Remove _all_ associations between this driver and the underlying USB
2169    layer. */
2170 static void pvr2_hdw_remove_usb_stuff(struct pvr2_hdw *hdw)
2171 {
2172         if (hdw->flag_disconnected) return;
2173         pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_remove_usb_stuff: hdw=%p",hdw);
2174         if (hdw->ctl_read_urb) {
2175                 usb_kill_urb(hdw->ctl_read_urb);
2176                 usb_free_urb(hdw->ctl_read_urb);
2177                 hdw->ctl_read_urb = NULL;
2178         }
2179         if (hdw->ctl_write_urb) {
2180                 usb_kill_urb(hdw->ctl_write_urb);
2181                 usb_free_urb(hdw->ctl_write_urb);
2182                 hdw->ctl_write_urb = NULL;
2183         }
2184         if (hdw->ctl_read_buffer) {
2185                 kfree(hdw->ctl_read_buffer);
2186                 hdw->ctl_read_buffer = NULL;
2187         }
2188         if (hdw->ctl_write_buffer) {
2189                 kfree(hdw->ctl_write_buffer);
2190                 hdw->ctl_write_buffer = NULL;
2191         }
2192         hdw->flag_disconnected = !0;
2193         hdw->usb_dev = NULL;
2194         hdw->usb_intf = NULL;
2195         pvr2_hdw_render_useless(hdw);
2196 }
2197
2198
2199 /* Destroy hardware interaction structure */
2200 void pvr2_hdw_destroy(struct pvr2_hdw *hdw)
2201 {
2202         if (!hdw) return;
2203         pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_destroy: hdw=%p",hdw);
2204         if (hdw->workqueue) {
2205                 flush_workqueue(hdw->workqueue);
2206                 destroy_workqueue(hdw->workqueue);
2207                 hdw->workqueue = NULL;
2208         }
2209         del_timer_sync(&hdw->quiescent_timer);
2210         del_timer_sync(&hdw->encoder_run_timer);
2211         del_timer_sync(&hdw->encoder_wait_timer);
2212         if (hdw->fw_buffer) {
2213                 kfree(hdw->fw_buffer);
2214                 hdw->fw_buffer = NULL;
2215         }
2216         if (hdw->vid_stream) {
2217                 pvr2_stream_destroy(hdw->vid_stream);
2218                 hdw->vid_stream = NULL;
2219         }
2220         if (hdw->decoder_ctrl) {
2221                 hdw->decoder_ctrl->detach(hdw->decoder_ctrl->ctxt);
2222         }
2223         pvr2_i2c_core_done(hdw);
2224         pvr2_hdw_remove_usb_stuff(hdw);
2225         mutex_lock(&pvr2_unit_mtx); do {
2226                 if ((hdw->unit_number >= 0) &&
2227                     (hdw->unit_number < PVR_NUM) &&
2228                     (unit_pointers[hdw->unit_number] == hdw)) {
2229                         unit_pointers[hdw->unit_number] = NULL;
2230                 }
2231         } while (0); mutex_unlock(&pvr2_unit_mtx);
2232         kfree(hdw->controls);
2233         kfree(hdw->mpeg_ctrl_info);
2234         kfree(hdw->std_defs);
2235         kfree(hdw->std_enum_names);
2236         kfree(hdw);
2237 }
2238
2239
2240 int pvr2_hdw_dev_ok(struct pvr2_hdw *hdw)
2241 {
2242         return (hdw && hdw->flag_ok);
2243 }
2244
2245
2246 /* Called when hardware has been unplugged */
2247 void pvr2_hdw_disconnect(struct pvr2_hdw *hdw)
2248 {
2249         pvr2_trace(PVR2_TRACE_INIT,"pvr2_hdw_disconnect(hdw=%p)",hdw);
2250         LOCK_TAKE(hdw->big_lock);
2251         LOCK_TAKE(hdw->ctl_lock);
2252         pvr2_hdw_remove_usb_stuff(hdw);
2253         LOCK_GIVE(hdw->ctl_lock);
2254         LOCK_GIVE(hdw->big_lock);
2255 }
2256
2257
2258 // Attempt to autoselect an appropriate value for std_enum_cur given
2259 // whatever is currently in std_mask_cur
2260 static void pvr2_hdw_internal_find_stdenum(struct pvr2_hdw *hdw)
2261 {
2262         unsigned int idx;
2263         for (idx = 1; idx < hdw->std_enum_cnt; idx++) {
2264                 if (hdw->std_defs[idx-1].id == hdw->std_mask_cur) {
2265                         hdw->std_enum_cur = idx;
2266                         return;
2267                 }
2268         }
2269         hdw->std_enum_cur = 0;
2270 }
2271
2272
2273 // Calculate correct set of enumerated standards based on currently known
2274 // set of available standards bits.
2275 static void pvr2_hdw_internal_set_std_avail(struct pvr2_hdw *hdw)
2276 {
2277         struct v4l2_standard *newstd;
2278         unsigned int std_cnt;
2279         unsigned int idx;
2280
2281         newstd = pvr2_std_create_enum(&std_cnt,hdw->std_mask_avail);
2282
2283         if (hdw->std_defs) {
2284                 kfree(hdw->std_defs);
2285                 hdw->std_defs = NULL;
2286         }
2287         hdw->std_enum_cnt = 0;
2288         if (hdw->std_enum_names) {
2289                 kfree(hdw->std_enum_names);
2290                 hdw->std_enum_names = NULL;
2291         }
2292
2293         if (!std_cnt) {
2294                 pvr2_trace(
2295                         PVR2_TRACE_ERROR_LEGS,
2296                         "WARNING: Failed to identify any viable standards");
2297         }
2298         hdw->std_enum_names = kmalloc(sizeof(char *)*(std_cnt+1),GFP_KERNEL);
2299         hdw->std_enum_names[0] = "none";
2300         for (idx = 0; idx < std_cnt; idx++) {
2301                 hdw->std_enum_names[idx+1] =
2302                         newstd[idx].name;
2303         }
2304         // Set up the dynamic control for this standard
2305         hdw->std_info_enum.def.type_enum.value_names = hdw->std_enum_names;
2306         hdw->std_info_enum.def.type_enum.count = std_cnt+1;
2307         hdw->std_defs = newstd;
2308         hdw->std_enum_cnt = std_cnt+1;
2309         hdw->std_enum_cur = 0;
2310         hdw->std_info_cur.def.type_bitmask.valid_bits = hdw->std_mask_avail;
2311 }
2312
2313
2314 int pvr2_hdw_get_stdenum_value(struct pvr2_hdw *hdw,
2315                                struct v4l2_standard *std,
2316                                unsigned int idx)
2317 {
2318         int ret = -EINVAL;
2319         if (!idx) return ret;
2320         LOCK_TAKE(hdw->big_lock); do {
2321                 if (idx >= hdw->std_enum_cnt) break;
2322                 idx--;
2323                 memcpy(std,hdw->std_defs+idx,sizeof(*std));
2324                 ret = 0;
2325         } while (0); LOCK_GIVE(hdw->big_lock);
2326         return ret;
2327 }
2328
2329
2330 /* Get the number of defined controls */
2331 unsigned int pvr2_hdw_get_ctrl_count(struct pvr2_hdw *hdw)
2332 {
2333         return hdw->control_cnt;
2334 }
2335
2336
2337 /* Retrieve a control handle given its index (0..count-1) */
2338 struct pvr2_ctrl *pvr2_hdw_get_ctrl_by_index(struct pvr2_hdw *hdw,
2339                                              unsigned int idx)
2340 {
2341         if (idx >= hdw->control_cnt) return NULL;
2342         return hdw->controls + idx;
2343 }
2344
2345
2346 /* Retrieve a control handle given its index (0..count-1) */
2347 struct pvr2_ctrl *pvr2_hdw_get_ctrl_by_id(struct pvr2_hdw *hdw,
2348                                           unsigned int ctl_id)
2349 {
2350         struct pvr2_ctrl *cptr;
2351         unsigned int idx;
2352         int i;
2353
2354         /* This could be made a lot more efficient, but for now... */
2355         for (idx = 0; idx < hdw->control_cnt; idx++) {
2356                 cptr = hdw->controls + idx;
2357                 i = cptr->info->internal_id;
2358                 if (i && (i == ctl_id)) return cptr;
2359         }
2360         return NULL;
2361 }
2362
2363
2364 /* Given a V4L ID, retrieve the control structure associated with it. */
2365 struct pvr2_ctrl *pvr2_hdw_get_ctrl_v4l(struct pvr2_hdw *hdw,unsigned int ctl_id)
2366 {
2367         struct pvr2_ctrl *cptr;
2368         unsigned int idx;
2369         int i;
2370
2371         /* This could be made a lot more efficient, but for now... */
2372         for (idx = 0; idx < hdw->control_cnt; idx++) {
2373                 cptr = hdw->controls + idx;
2374                 i = cptr->info->v4l_id;
2375                 if (i && (i == ctl_id)) return cptr;
2376         }
2377         return NULL;
2378 }
2379
2380
2381 /* Given a V4L ID for its immediate predecessor, retrieve the control
2382    structure associated with it. */
2383 struct pvr2_ctrl *pvr2_hdw_get_ctrl_nextv4l(struct pvr2_hdw *hdw,
2384                                             unsigned int ctl_id)
2385 {
2386         struct pvr2_ctrl *cptr,*cp2;
2387         unsigned int idx;
2388         int i;
2389
2390         /* This could be made a lot more efficient, but for now... */
2391         cp2 = NULL;
2392         for (idx = 0; idx < hdw->control_cnt; idx++) {
2393                 cptr = hdw->controls + idx;
2394                 i = cptr->info->v4l_id;
2395                 if (!i) continue;
2396                 if (i <= ctl_id) continue;
2397                 if (cp2 && (cp2->info->v4l_id < i)) continue;
2398                 cp2 = cptr;
2399         }
2400         return cp2;
2401         return NULL;
2402 }
2403
2404
2405 static const char *get_ctrl_typename(enum pvr2_ctl_type tp)
2406 {
2407         switch (tp) {
2408         case pvr2_ctl_int: return "integer";
2409         case pvr2_ctl_enum: return "enum";
2410         case pvr2_ctl_bool: return "boolean";
2411         case pvr2_ctl_bitmask: return "bitmask";
2412         }
2413         return "";
2414 }
2415
2416
2417 /* Figure out if we need to commit control changes.  If so, mark internal
2418    state flags to indicate this fact and return true.  Otherwise do nothing
2419    else and return false. */
2420 static int pvr2_hdw_commit_setup(struct pvr2_hdw *hdw)
2421 {
2422         unsigned int idx;
2423         struct pvr2_ctrl *cptr;
2424         int value;
2425         int commit_flag = 0;
2426         char buf[100];
2427         unsigned int bcnt,ccnt;
2428
2429         for (idx = 0; idx < hdw->control_cnt; idx++) {
2430                 cptr = hdw->controls + idx;
2431                 if (!cptr->info->is_dirty) continue;
2432                 if (!cptr->info->is_dirty(cptr)) continue;
2433                 commit_flag = !0;
2434
2435                 if (!(pvrusb2_debug & PVR2_TRACE_CTL)) continue;
2436                 bcnt = scnprintf(buf,sizeof(buf),"\"%s\" <-- ",
2437                                  cptr->info->name);
2438                 value = 0;
2439                 cptr->info->get_value(cptr,&value);
2440                 pvr2_ctrl_value_to_sym_internal(cptr,~0,value,
2441                                                 buf+bcnt,
2442                                                 sizeof(buf)-bcnt,&ccnt);
2443                 bcnt += ccnt;
2444                 bcnt += scnprintf(buf+bcnt,sizeof(buf)-bcnt," <%s>",
2445                                   get_ctrl_typename(cptr->info->type));
2446                 pvr2_trace(PVR2_TRACE_CTL,
2447                            "/*--TRACE_COMMIT--*/ %.*s",
2448                            bcnt,buf);
2449         }
2450
2451         if (!commit_flag) {
2452                 /* Nothing has changed */
2453                 return 0;
2454         }
2455
2456         hdw->state_pipeline_config = 0;
2457         trace_stbit("state_pipeline_config",hdw->state_pipeline_config);
2458         pvr2_hdw_state_sched(hdw);
2459
2460         return !0;
2461 }
2462
2463
2464 /* Perform all operations needed to commit all control changes.  This must
2465    be performed in synchronization with the pipeline state and is thus
2466    expected to be called as part of the driver's worker thread.  Return
2467    true if commit successful, otherwise return false to indicate that
2468    commit isn't possible at this time. */
2469 static int pvr2_hdw_commit_execute(struct pvr2_hdw *hdw)
2470 {
2471         unsigned int idx;
2472         struct pvr2_ctrl *cptr;
2473         int disruptive_change;
2474
2475         /* Handle some required side effects when the video standard is
2476            changed.... */
2477         if (hdw->std_dirty) {
2478                 int nvres;
2479                 int gop_size;
2480                 if (hdw->std_mask_cur & V4L2_STD_525_60) {
2481                         nvres = 480;
2482                         gop_size = 15;
2483                 } else {
2484                         nvres = 576;
2485                         gop_size = 12;
2486                 }
2487                 /* Rewrite the vertical resolution to be appropriate to the
2488                    video standard that has been selected. */
2489                 if (nvres != hdw->res_ver_val) {
2490                         hdw->res_ver_val = nvres;
2491                         hdw->res_ver_dirty = !0;
2492                 }
2493                 /* Rewrite the GOP size to be appropriate to the video
2494                    standard that has been selected. */
2495                 if (gop_size != hdw->enc_ctl_state.video_gop_size) {
2496                         struct v4l2_ext_controls cs;
2497                         struct v4l2_ext_control c1;
2498                         memset(&cs, 0, sizeof(cs));
2499                         memset(&c1, 0, sizeof(c1));
2500                         cs.controls = &c1;
2501                         cs.count = 1;
2502                         c1.id = V4L2_CID_MPEG_VIDEO_GOP_SIZE;
2503                         c1.value = gop_size;
2504                         cx2341x_ext_ctrls(&hdw->enc_ctl_state, 0, &cs,
2505                                           VIDIOC_S_EXT_CTRLS);
2506                 }
2507         }
2508
2509         if (hdw->input_dirty && hdw->state_pathway_ok &&
2510             (((hdw->input_val == PVR2_CVAL_INPUT_DTV) ?
2511               PVR2_PATHWAY_DIGITAL : PVR2_PATHWAY_ANALOG) !=
2512              hdw->pathway_state)) {
2513                 /* Change of mode being asked for... */
2514                 hdw->state_pathway_ok = 0;
2515                 trace_stbit("state_pathway_ok",hdw->state_pathway_ok);
2516         }
2517         if (!hdw->state_pathway_ok) {
2518                 /* Can't commit anything until pathway is ok. */
2519                 return 0;
2520         }
2521         /* If any of the below has changed, then we can't do the update
2522            while the pipeline is running.  Pipeline must be paused first
2523            and decoder -> encoder connection be made quiescent before we
2524            can proceed. */
2525         disruptive_change =
2526                 (hdw->std_dirty ||
2527                  hdw->enc_unsafe_stale ||
2528                  hdw->srate_dirty ||
2529                  hdw->res_ver_dirty ||
2530                  hdw->res_hor_dirty ||
2531                  hdw->input_dirty ||
2532                  (hdw->active_stream_type != hdw->desired_stream_type));
2533         if (disruptive_change && !hdw->state_pipeline_idle) {
2534                 /* Pipeline is not idle; we can't proceed.  Arrange to
2535                    cause pipeline to stop so that we can try this again
2536                    later.... */
2537                 hdw->state_pipeline_pause = !0;
2538                 return 0;
2539         }
2540
2541         if (hdw->srate_dirty) {
2542                 /* Write new sample rate into control structure since
2543                  * the master copy is stale.  We must track srate
2544                  * separate from the mpeg control structure because
2545                  * other logic also uses this value. */
2546                 struct v4l2_ext_controls cs;
2547                 struct v4l2_ext_control c1;
2548                 memset(&cs,0,sizeof(cs));
2549                 memset(&c1,0,sizeof(c1));
2550                 cs.controls = &c1;
2551                 cs.count = 1;
2552                 c1.id = V4L2_CID_MPEG_AUDIO_SAMPLING_FREQ;
2553                 c1.value = hdw->srate_val;
2554                 cx2341x_ext_ctrls(&hdw->enc_ctl_state, 0, &cs,VIDIOC_S_EXT_CTRLS);
2555         }
2556
2557         /* Scan i2c core at this point - before we clear all the dirty
2558            bits.  Various parts of the i2c core will notice dirty bits as
2559            appropriate and arrange to broadcast or directly send updates to
2560            the client drivers in order to keep everything in sync */
2561         pvr2_i2c_core_check_stale(hdw);
2562
2563         for (idx = 0; idx < hdw->control_cnt; idx++) {
2564                 cptr = hdw->controls + idx;
2565                 if (!cptr->info->clear_dirty) continue;
2566                 cptr->info->clear_dirty(cptr);
2567         }
2568
2569         if (hdw->active_stream_type != hdw->desired_stream_type) {
2570                 /* Handle any side effects of stream config here */
2571                 hdw->active_stream_type = hdw->desired_stream_type;
2572         }
2573
2574         if (hdw->hdw_desc->signal_routing_scheme ==
2575             PVR2_ROUTING_SCHEME_GOTVIEW) {
2576                 u32 b;
2577                 /* Handle GOTVIEW audio switching */
2578                 pvr2_hdw_gpio_get_out(hdw,&b);
2579                 if (hdw->input_val == PVR2_CVAL_INPUT_RADIO) {
2580                         /* Set GPIO 11 */
2581                         pvr2_hdw_gpio_chg_out(hdw,(1 << 11),~0);
2582                 } else {
2583                         /* Clear GPIO 11 */
2584                         pvr2_hdw_gpio_chg_out(hdw,(1 << 11),0);
2585                 }
2586         }
2587
2588         /* Now execute i2c core update */
2589         pvr2_i2c_core_sync(hdw);
2590
2591         if ((hdw->pathway_state == PVR2_PATHWAY_ANALOG) &&
2592             hdw->state_encoder_run) {
2593                 /* If encoder isn't running or it can't be touched, then
2594                    this will get worked out later when we start the
2595                    encoder. */
2596                 if (pvr2_encoder_adjust(hdw) < 0) return !0;
2597         }
2598
2599         hdw->state_pipeline_config = !0;
2600         trace_stbit("state_pipeline_config",hdw->state_pipeline_config);
2601         return !0;
2602 }
2603
2604
2605 int pvr2_hdw_commit_ctl(struct pvr2_hdw *hdw)
2606 {
2607         int fl;
2608         LOCK_TAKE(hdw->big_lock);
2609         fl = pvr2_hdw_commit_setup(hdw);
2610         LOCK_GIVE(hdw->big_lock);
2611         if (!fl) return 0;
2612         return pvr2_hdw_wait(hdw,0);
2613 }
2614
2615
2616 static void pvr2_hdw_worker_i2c(struct work_struct *work)
2617 {
2618         struct pvr2_hdw *hdw = container_of(work,struct pvr2_hdw,worki2csync);
2619         LOCK_TAKE(hdw->big_lock); do {
2620                 pvr2_i2c_core_sync(hdw);
2621         } while (0); LOCK_GIVE(hdw->big_lock);
2622 }
2623
2624
2625 static void pvr2_hdw_worker_poll(struct work_struct *work)
2626 {
2627         int fl = 0;
2628         struct pvr2_hdw *hdw = container_of(work,struct pvr2_hdw,workpoll);
2629         LOCK_TAKE(hdw->big_lock); do {
2630                 fl = pvr2_hdw_state_eval(hdw);
2631         } while (0); LOCK_GIVE(hdw->big_lock);
2632         if (fl && hdw->state_func) {
2633                 hdw->state_func(hdw->state_data);
2634         }
2635 }
2636
2637
2638 static int pvr2_hdw_wait(struct pvr2_hdw *hdw,int state)
2639 {
2640         return wait_event_interruptible(
2641                 hdw->state_wait_data,
2642                 (hdw->state_stale == 0) &&
2643                 (!state || (hdw->master_state != state)));
2644 }
2645
2646
2647 /* Return name for this driver instance */
2648 const char *pvr2_hdw_get_driver_name(struct pvr2_hdw *hdw)
2649 {
2650         return hdw->name;
2651 }
2652
2653
2654 const char *pvr2_hdw_get_desc(struct pvr2_hdw *hdw)
2655 {
2656         return hdw->hdw_desc->description;
2657 }
2658
2659
2660 const char *pvr2_hdw_get_type(struct pvr2_hdw *hdw)
2661 {
2662         return hdw->hdw_desc->shortname;
2663 }
2664
2665
2666 int pvr2_hdw_is_hsm(struct pvr2_hdw *hdw)
2667 {
2668         int result;
2669         LOCK_TAKE(hdw->ctl_lock); do {
2670                 hdw->cmd_buffer[0] = FX2CMD_GET_USB_SPEED;
2671                 result = pvr2_send_request(hdw,
2672                                            hdw->cmd_buffer,1,
2673                                            hdw->cmd_buffer,1);
2674                 if (result < 0) break;
2675                 result = (hdw->cmd_buffer[0] != 0);
2676         } while(0); LOCK_GIVE(hdw->ctl_lock);
2677         return result;
2678 }
2679
2680
2681 /* Execute poll of tuner status */
2682 void pvr2_hdw_execute_tuner_poll(struct pvr2_hdw *hdw)
2683 {
2684         LOCK_TAKE(hdw->big_lock); do {
2685                 pvr2_i2c_core_status_poll(hdw);
2686         } while (0); LOCK_GIVE(hdw->big_lock);
2687 }
2688
2689
2690 /* Return information about the tuner */
2691 int pvr2_hdw_get_tuner_status(struct pvr2_hdw *hdw,struct v4l2_tuner *vtp)
2692 {
2693         LOCK_TAKE(hdw->big_lock); do {
2694                 if (hdw->tuner_signal_stale) {
2695                         pvr2_i2c_core_status_poll(hdw);
2696                 }
2697                 memcpy(vtp,&hdw->tuner_signal_info,sizeof(struct v4l2_tuner));
2698         } while (0); LOCK_GIVE(hdw->big_lock);
2699         return 0;
2700 }
2701
2702
2703 /* Get handle to video output stream */
2704 struct pvr2_stream *pvr2_hdw_get_video_stream(struct pvr2_hdw *hp)
2705 {
2706         return hp->vid_stream;
2707 }
2708
2709
2710 void pvr2_hdw_trigger_module_log(struct pvr2_hdw *hdw)
2711 {
2712         int nr = pvr2_hdw_get_unit_number(hdw);
2713         LOCK_TAKE(hdw->big_lock); do {
2714                 hdw->log_requested = !0;
2715                 printk(KERN_INFO "pvrusb2: =================  START STATUS CARD #%d  =================\n", nr);
2716                 pvr2_i2c_core_check_stale(hdw);
2717                 hdw->log_requested = 0;
2718                 pvr2_i2c_core_sync(hdw);
2719                 pvr2_trace(PVR2_TRACE_INFO,"cx2341x config:");
2720                 cx2341x_log_status(&hdw->enc_ctl_state, "pvrusb2");
2721                 pvr2_hdw_state_log_state(hdw);
2722                 printk(KERN_INFO "pvrusb2: ==================  END STATUS CARD #%d  ==================\n", nr);
2723         } while (0); LOCK_GIVE(hdw->big_lock);
2724 }
2725
2726
2727 /* Grab EEPROM contents, needed for direct method. */
2728 #define EEPROM_SIZE 8192
2729 #define trace_eeprom(...) pvr2_trace(PVR2_TRACE_EEPROM,__VA_ARGS__)
2730 static u8 *pvr2_full_eeprom_fetch(struct pvr2_hdw *hdw)
2731 {
2732         struct i2c_msg msg[2];
2733         u8 *eeprom;
2734         u8 iadd[2];
2735         u8 addr;
2736         u16 eepromSize;
2737         unsigned int offs;
2738         int ret;
2739         int mode16 = 0;
2740         unsigned pcnt,tcnt;
2741         eeprom = kmalloc(EEPROM_SIZE,GFP_KERNEL);
2742         if (!eeprom) {
2743                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2744                            "Failed to allocate memory"
2745                            " required to read eeprom");
2746                 return NULL;
2747         }
2748
2749         trace_eeprom("Value for eeprom addr from controller was 0x%x",
2750                      hdw->eeprom_addr);
2751         addr = hdw->eeprom_addr;
2752         /* Seems that if the high bit is set, then the *real* eeprom
2753            address is shifted right now bit position (noticed this in
2754            newer PVR USB2 hardware) */
2755         if (addr & 0x80) addr >>= 1;
2756
2757         /* FX2 documentation states that a 16bit-addressed eeprom is
2758            expected if the I2C address is an odd number (yeah, this is
2759            strange but it's what they do) */
2760         mode16 = (addr & 1);
2761         eepromSize = (mode16 ? EEPROM_SIZE : 256);
2762         trace_eeprom("Examining %d byte eeprom at location 0x%x"
2763                      " using %d bit addressing",eepromSize,addr,
2764                      mode16 ? 16 : 8);
2765
2766         msg[0].addr = addr;
2767         msg[0].flags = 0;
2768         msg[0].len = mode16 ? 2 : 1;
2769         msg[0].buf = iadd;
2770         msg[1].addr = addr;
2771         msg[1].flags = I2C_M_RD;
2772
2773         /* We have to do the actual eeprom data fetch ourselves, because
2774            (1) we're only fetching part of the eeprom, and (2) if we were
2775            getting the whole thing our I2C driver can't grab it in one
2776            pass - which is what tveeprom is otherwise going to attempt */
2777         memset(eeprom,0,EEPROM_SIZE);
2778         for (tcnt = 0; tcnt < EEPROM_SIZE; tcnt += pcnt) {
2779                 pcnt = 16;
2780                 if (pcnt + tcnt > EEPROM_SIZE) pcnt = EEPROM_SIZE-tcnt;
2781                 offs = tcnt + (eepromSize - EEPROM_SIZE);
2782                 if (mode16) {
2783                         iadd[0] = offs >> 8;
2784                         iadd[1] = offs;
2785                 } else {
2786                         iadd[0] = offs;
2787                 }
2788                 msg[1].len = pcnt;
2789                 msg[1].buf = eeprom+tcnt;
2790                 if ((ret = i2c_transfer(&hdw->i2c_adap,
2791                                         msg,ARRAY_SIZE(msg))) != 2) {
2792                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2793                                    "eeprom fetch set offs err=%d",ret);
2794                         kfree(eeprom);
2795                         return NULL;
2796                 }
2797         }
2798         return eeprom;
2799 }
2800
2801
2802 void pvr2_hdw_cpufw_set_enabled(struct pvr2_hdw *hdw,
2803                                 int prom_flag,
2804                                 int enable_flag)
2805 {
2806         int ret;
2807         u16 address;
2808         unsigned int pipe;
2809         LOCK_TAKE(hdw->big_lock); do {
2810                 if ((hdw->fw_buffer == NULL) == !enable_flag) break;
2811
2812                 if (!enable_flag) {
2813                         pvr2_trace(PVR2_TRACE_FIRMWARE,
2814                                    "Cleaning up after CPU firmware fetch");
2815                         kfree(hdw->fw_buffer);
2816                         hdw->fw_buffer = NULL;
2817                         hdw->fw_size = 0;
2818                         if (hdw->fw_cpu_flag) {
2819                                 /* Now release the CPU.  It will disconnect
2820                                    and reconnect later. */
2821                                 pvr2_hdw_cpureset_assert(hdw,0);
2822                         }
2823                         break;
2824                 }
2825
2826                 hdw->fw_cpu_flag = (prom_flag == 0);
2827                 if (hdw->fw_cpu_flag) {
2828                         pvr2_trace(PVR2_TRACE_FIRMWARE,
2829                                    "Preparing to suck out CPU firmware");
2830                         hdw->fw_size = 0x2000;
2831                         hdw->fw_buffer = kzalloc(hdw->fw_size,GFP_KERNEL);
2832                         if (!hdw->fw_buffer) {
2833                                 hdw->fw_size = 0;
2834                                 break;
2835                         }
2836
2837                         /* We have to hold the CPU during firmware upload. */
2838                         pvr2_hdw_cpureset_assert(hdw,1);
2839
2840                         /* download the firmware from address 0000-1fff in 2048
2841                            (=0x800) bytes chunk. */
2842
2843                         pvr2_trace(PVR2_TRACE_FIRMWARE,
2844                                    "Grabbing CPU firmware");
2845                         pipe = usb_rcvctrlpipe(hdw->usb_dev, 0);
2846                         for(address = 0; address < hdw->fw_size;
2847                             address += 0x800) {
2848                                 ret = usb_control_msg(hdw->usb_dev,pipe,
2849                                                       0xa0,0xc0,
2850                                                       address,0,
2851                                                       hdw->fw_buffer+address,
2852                                                       0x800,HZ);
2853                                 if (ret < 0) break;
2854                         }
2855
2856                         pvr2_trace(PVR2_TRACE_FIRMWARE,
2857                                    "Done grabbing CPU firmware");
2858                 } else {
2859                         pvr2_trace(PVR2_TRACE_FIRMWARE,
2860                                    "Sucking down EEPROM contents");
2861                         hdw->fw_buffer = pvr2_full_eeprom_fetch(hdw);
2862                         if (!hdw->fw_buffer) {
2863                                 pvr2_trace(PVR2_TRACE_FIRMWARE,
2864                                            "EEPROM content suck failed.");
2865                                 break;
2866                         }
2867                         hdw->fw_size = EEPROM_SIZE;
2868                         pvr2_trace(PVR2_TRACE_FIRMWARE,
2869                                    "Done sucking down EEPROM contents");
2870                 }
2871
2872         } while (0); LOCK_GIVE(hdw->big_lock);
2873 }
2874
2875
2876 /* Return true if we're in a mode for retrieval CPU firmware */
2877 int pvr2_hdw_cpufw_get_enabled(struct pvr2_hdw *hdw)
2878 {
2879         return hdw->fw_buffer != NULL;
2880 }
2881
2882
2883 int pvr2_hdw_cpufw_get(struct pvr2_hdw *hdw,unsigned int offs,
2884                        char *buf,unsigned int cnt)
2885 {
2886         int ret = -EINVAL;
2887         LOCK_TAKE(hdw->big_lock); do {
2888                 if (!buf) break;
2889                 if (!cnt) break;
2890
2891                 if (!hdw->fw_buffer) {
2892                         ret = -EIO;
2893                         break;
2894                 }
2895
2896                 if (offs >= hdw->fw_size) {
2897                         pvr2_trace(PVR2_TRACE_FIRMWARE,
2898                                    "Read firmware data offs=%d EOF",
2899                                    offs);
2900                         ret = 0;
2901                         break;
2902                 }
2903
2904                 if (offs + cnt > hdw->fw_size) cnt = hdw->fw_size - offs;
2905
2906                 memcpy(buf,hdw->fw_buffer+offs,cnt);
2907
2908                 pvr2_trace(PVR2_TRACE_FIRMWARE,
2909                            "Read firmware data offs=%d cnt=%d",
2910                            offs,cnt);
2911                 ret = cnt;
2912         } while (0); LOCK_GIVE(hdw->big_lock);
2913
2914         return ret;
2915 }
2916
2917
2918 int pvr2_hdw_v4l_get_minor_number(struct pvr2_hdw *hdw,
2919                                   enum pvr2_v4l_type index)
2920 {
2921         switch (index) {
2922         case pvr2_v4l_type_video: return hdw->v4l_minor_number_video;
2923         case pvr2_v4l_type_vbi: return hdw->v4l_minor_number_vbi;
2924         case pvr2_v4l_type_radio: return hdw->v4l_minor_number_radio;
2925         default: return -1;
2926         }
2927 }
2928
2929
2930 /* Store a v4l minor device number */
2931 void pvr2_hdw_v4l_store_minor_number(struct pvr2_hdw *hdw,
2932                                      enum pvr2_v4l_type index,int v)
2933 {
2934         switch (index) {
2935         case pvr2_v4l_type_video: hdw->v4l_minor_number_video = v;
2936         case pvr2_v4l_type_vbi: hdw->v4l_minor_number_vbi = v;
2937         case pvr2_v4l_type_radio: hdw->v4l_minor_number_radio = v;
2938         default: break;
2939         }
2940 }
2941
2942
2943 static void pvr2_ctl_write_complete(struct urb *urb)
2944 {
2945         struct pvr2_hdw *hdw = urb->context;
2946         hdw->ctl_write_pend_flag = 0;
2947         if (hdw->ctl_read_pend_flag) return;
2948         complete(&hdw->ctl_done);
2949 }
2950
2951
2952 static void pvr2_ctl_read_complete(struct urb *urb)
2953 {
2954         struct pvr2_hdw *hdw = urb->context;
2955         hdw->ctl_read_pend_flag = 0;
2956         if (hdw->ctl_write_pend_flag) return;
2957         complete(&hdw->ctl_done);
2958 }
2959
2960
2961 static void pvr2_ctl_timeout(unsigned long data)
2962 {
2963         struct pvr2_hdw *hdw = (struct pvr2_hdw *)data;
2964         if (hdw->ctl_write_pend_flag || hdw->ctl_read_pend_flag) {
2965                 hdw->ctl_timeout_flag = !0;
2966                 if (hdw->ctl_write_pend_flag)
2967                         usb_unlink_urb(hdw->ctl_write_urb);
2968                 if (hdw->ctl_read_pend_flag)
2969                         usb_unlink_urb(hdw->ctl_read_urb);
2970         }
2971 }
2972
2973
2974 /* Issue a command and get a response from the device.  This extended
2975    version includes a probe flag (which if set means that device errors
2976    should not be logged or treated as fatal) and a timeout in jiffies.
2977    This can be used to non-lethally probe the health of endpoint 1. */
2978 static int pvr2_send_request_ex(struct pvr2_hdw *hdw,
2979                                 unsigned int timeout,int probe_fl,
2980                                 void *write_data,unsigned int write_len,
2981                                 void *read_data,unsigned int read_len)
2982 {
2983         unsigned int idx;
2984         int status = 0;
2985         struct timer_list timer;
2986         if (!hdw->ctl_lock_held) {
2987                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2988                            "Attempted to execute control transfer"
2989                            " without lock!!");
2990                 return -EDEADLK;
2991         }
2992         if (!hdw->flag_ok && !probe_fl) {
2993                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
2994                            "Attempted to execute control transfer"
2995                            " when device not ok");
2996                 return -EIO;
2997         }
2998         if (!(hdw->ctl_read_urb && hdw->ctl_write_urb)) {
2999                 if (!probe_fl) {
3000                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3001                                    "Attempted to execute control transfer"
3002                                    " when USB is disconnected");
3003                 }
3004                 return -ENOTTY;
3005         }
3006
3007         /* Ensure that we have sane parameters */
3008         if (!write_data) write_len = 0;
3009         if (!read_data) read_len = 0;
3010         if (write_len > PVR2_CTL_BUFFSIZE) {
3011                 pvr2_trace(
3012                         PVR2_TRACE_ERROR_LEGS,
3013                         "Attempted to execute %d byte"
3014                         " control-write transfer (limit=%d)",
3015                         write_len,PVR2_CTL_BUFFSIZE);
3016                 return -EINVAL;
3017         }
3018         if (read_len > PVR2_CTL_BUFFSIZE) {
3019                 pvr2_trace(
3020                         PVR2_TRACE_ERROR_LEGS,
3021                         "Attempted to execute %d byte"
3022                         " control-read transfer (limit=%d)",
3023                         write_len,PVR2_CTL_BUFFSIZE);
3024                 return -EINVAL;
3025         }
3026         if ((!write_len) && (!read_len)) {
3027                 pvr2_trace(
3028                         PVR2_TRACE_ERROR_LEGS,
3029                         "Attempted to execute null control transfer?");
3030                 return -EINVAL;
3031         }
3032
3033
3034         hdw->cmd_debug_state = 1;
3035         if (write_len) {
3036                 hdw->cmd_debug_code = ((unsigned char *)write_data)[0];
3037         } else {
3038                 hdw->cmd_debug_code = 0;
3039         }
3040         hdw->cmd_debug_write_len = write_len;
3041         hdw->cmd_debug_read_len = read_len;
3042
3043         /* Initialize common stuff */
3044         init_completion(&hdw->ctl_done);
3045         hdw->ctl_timeout_flag = 0;
3046         hdw->ctl_write_pend_flag = 0;
3047         hdw->ctl_read_pend_flag = 0;
3048         init_timer(&timer);
3049         timer.expires = jiffies + timeout;
3050         timer.data = (unsigned long)hdw;
3051         timer.function = pvr2_ctl_timeout;
3052
3053         if (write_len) {
3054                 hdw->cmd_debug_state = 2;
3055                 /* Transfer write data to internal buffer */
3056                 for (idx = 0; idx < write_len; idx++) {
3057                         hdw->ctl_write_buffer[idx] =
3058                                 ((unsigned char *)write_data)[idx];
3059                 }
3060                 /* Initiate a write request */
3061                 usb_fill_bulk_urb(hdw->ctl_write_urb,
3062                                   hdw->usb_dev,
3063                                   usb_sndbulkpipe(hdw->usb_dev,
3064                                                   PVR2_CTL_WRITE_ENDPOINT),
3065                                   hdw->ctl_write_buffer,
3066                                   write_len,
3067                                   pvr2_ctl_write_complete,
3068                                   hdw);
3069                 hdw->ctl_write_urb->actual_length = 0;
3070                 hdw->ctl_write_pend_flag = !0;
3071                 status = usb_submit_urb(hdw->ctl_write_urb,GFP_KERNEL);
3072                 if (status < 0) {
3073                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3074                                    "Failed to submit write-control"
3075                                    " URB status=%d",status);
3076                         hdw->ctl_write_pend_flag = 0;
3077                         goto done;
3078                 }
3079         }
3080
3081         if (read_len) {
3082                 hdw->cmd_debug_state = 3;
3083                 memset(hdw->ctl_read_buffer,0x43,read_len);
3084                 /* Initiate a read request */
3085                 usb_fill_bulk_urb(hdw->ctl_read_urb,
3086                                   hdw->usb_dev,
3087                                   usb_rcvbulkpipe(hdw->usb_dev,
3088                                                   PVR2_CTL_READ_ENDPOINT),
3089                                   hdw->ctl_read_buffer,
3090                                   read_len,
3091                                   pvr2_ctl_read_complete,
3092                                   hdw);
3093                 hdw->ctl_read_urb->actual_length = 0;
3094                 hdw->ctl_read_pend_flag = !0;
3095                 status = usb_submit_urb(hdw->ctl_read_urb,GFP_KERNEL);
3096                 if (status < 0) {
3097                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3098                                    "Failed to submit read-control"
3099                                    " URB status=%d",status);
3100                         hdw->ctl_read_pend_flag = 0;
3101                         goto done;
3102                 }
3103         }
3104
3105         /* Start timer */
3106         add_timer(&timer);
3107
3108         /* Now wait for all I/O to complete */
3109         hdw->cmd_debug_state = 4;
3110         while (hdw->ctl_write_pend_flag || hdw->ctl_read_pend_flag) {
3111                 wait_for_completion(&hdw->ctl_done);
3112         }
3113         hdw->cmd_debug_state = 5;
3114
3115         /* Stop timer */
3116         del_timer_sync(&timer);
3117
3118         hdw->cmd_debug_state = 6;
3119         status = 0;
3120
3121         if (hdw->ctl_timeout_flag) {
3122                 status = -ETIMEDOUT;
3123                 if (!probe_fl) {
3124                         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3125                                    "Timed out control-write");
3126                 }
3127                 goto done;
3128         }
3129
3130         if (write_len) {
3131                 /* Validate results of write request */
3132                 if ((hdw->ctl_write_urb->status != 0) &&
3133                     (hdw->ctl_write_urb->status != -ENOENT) &&
3134                     (hdw->ctl_write_urb->status != -ESHUTDOWN) &&
3135                     (hdw->ctl_write_urb->status != -ECONNRESET)) {
3136                         /* USB subsystem is reporting some kind of failure
3137                            on the write */
3138                         status = hdw->ctl_write_urb->status;
3139                         if (!probe_fl) {
3140                                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3141                                            "control-write URB failure,"
3142                                            " status=%d",
3143                                            status);
3144                         }
3145                         goto done;
3146                 }
3147                 if (hdw->ctl_write_urb->actual_length < write_len) {
3148                         /* Failed to write enough data */
3149                         status = -EIO;
3150                         if (!probe_fl) {
3151                                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3152                                            "control-write URB short,"
3153                                            " expected=%d got=%d",
3154                                            write_len,
3155                                            hdw->ctl_write_urb->actual_length);
3156                         }
3157                         goto done;
3158                 }
3159         }
3160         if (read_len) {
3161                 /* Validate results of read request */
3162                 if ((hdw->ctl_read_urb->status != 0) &&
3163                     (hdw->ctl_read_urb->status != -ENOENT) &&
3164                     (hdw->ctl_read_urb->status != -ESHUTDOWN) &&
3165                     (hdw->ctl_read_urb->status != -ECONNRESET)) {
3166                         /* USB subsystem is reporting some kind of failure
3167                            on the read */
3168                         status = hdw->ctl_read_urb->status;
3169                         if (!probe_fl) {
3170                                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3171                                            "control-read URB failure,"
3172                                            " status=%d",
3173                                            status);
3174                         }
3175                         goto done;
3176                 }
3177                 if (hdw->ctl_read_urb->actual_length < read_len) {
3178                         /* Failed to read enough data */
3179                         status = -EIO;
3180                         if (!probe_fl) {
3181                                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3182                                            "control-read URB short,"
3183                                            " expected=%d got=%d",
3184                                            read_len,
3185                                            hdw->ctl_read_urb->actual_length);
3186                         }
3187                         goto done;
3188                 }
3189                 /* Transfer retrieved data out from internal buffer */
3190                 for (idx = 0; idx < read_len; idx++) {
3191                         ((unsigned char *)read_data)[idx] =
3192                                 hdw->ctl_read_buffer[idx];
3193                 }
3194         }
3195
3196  done:
3197
3198         hdw->cmd_debug_state = 0;
3199         if ((status < 0) && (!probe_fl)) {
3200                 pvr2_hdw_render_useless(hdw);
3201         }
3202         return status;
3203 }
3204
3205
3206 int pvr2_send_request(struct pvr2_hdw *hdw,
3207                       void *write_data,unsigned int write_len,
3208                       void *read_data,unsigned int read_len)
3209 {
3210         return pvr2_send_request_ex(hdw,HZ*4,0,
3211                                     write_data,write_len,
3212                                     read_data,read_len);
3213 }
3214
3215
3216 static int pvr2_issue_simple_cmd(struct pvr2_hdw *hdw,u32 cmdcode)
3217 {
3218         int ret;
3219         unsigned int cnt = 1;
3220         unsigned int args = 0;
3221         LOCK_TAKE(hdw->ctl_lock);
3222         hdw->cmd_buffer[0] = cmdcode & 0xffu;
3223         args = (cmdcode >> 8) & 0xffu;
3224         args = (args > 2) ? 2 : args;
3225         if (args) {
3226                 cnt += args;
3227                 hdw->cmd_buffer[1] = (cmdcode >> 16) & 0xffu;
3228                 if (args > 1) {
3229                         hdw->cmd_buffer[2] = (cmdcode >> 24) & 0xffu;
3230                 }
3231         }
3232         if (pvrusb2_debug & PVR2_TRACE_INIT) {
3233                 unsigned int idx;
3234                 unsigned int ccnt,bcnt;
3235                 char tbuf[50];
3236                 cmdcode &= 0xffu;
3237                 bcnt = 0;
3238                 ccnt = scnprintf(tbuf+bcnt,
3239                                  sizeof(tbuf)-bcnt,
3240                                  "Sending FX2 command 0x%x",cmdcode);
3241                 bcnt += ccnt;
3242                 for (idx = 0; idx < ARRAY_SIZE(pvr2_fx2cmd_desc); idx++) {
3243                         if (pvr2_fx2cmd_desc[idx].id == cmdcode) {
3244                                 ccnt = scnprintf(tbuf+bcnt,
3245                                                  sizeof(tbuf)-bcnt,
3246                                                  " \"%s\"",
3247                                                  pvr2_fx2cmd_desc[idx].desc);
3248                                 bcnt += ccnt;
3249                                 break;
3250                         }
3251                 }
3252                 if (args) {
3253                         ccnt = scnprintf(tbuf+bcnt,
3254                                          sizeof(tbuf)-bcnt,
3255                                          " (%u",hdw->cmd_buffer[1]);
3256                         bcnt += ccnt;
3257                         if (args > 1) {
3258                                 ccnt = scnprintf(tbuf+bcnt,
3259                                                  sizeof(tbuf)-bcnt,
3260                                                  ",%u",hdw->cmd_buffer[2]);
3261                                 bcnt += ccnt;
3262                         }
3263                         ccnt = scnprintf(tbuf+bcnt,
3264                                          sizeof(tbuf)-bcnt,
3265                                          ")");
3266                         bcnt += ccnt;
3267                 }
3268                 pvr2_trace(PVR2_TRACE_INIT,"%.*s",bcnt,tbuf);
3269         }
3270         ret = pvr2_send_request(hdw,hdw->cmd_buffer,cnt,NULL,0);
3271         LOCK_GIVE(hdw->ctl_lock);
3272         return ret;
3273 }
3274
3275
3276 int pvr2_write_register(struct pvr2_hdw *hdw, u16 reg, u32 data)
3277 {
3278         int ret;
3279
3280         LOCK_TAKE(hdw->ctl_lock);
3281
3282         hdw->cmd_buffer[0] = FX2CMD_REG_WRITE;  /* write register prefix */
3283         PVR2_DECOMPOSE_LE(hdw->cmd_buffer,1,data);
3284         hdw->cmd_buffer[5] = 0;
3285         hdw->cmd_buffer[6] = (reg >> 8) & 0xff;
3286         hdw->cmd_buffer[7] = reg & 0xff;
3287
3288
3289         ret = pvr2_send_request(hdw, hdw->cmd_buffer, 8, hdw->cmd_buffer, 0);
3290
3291         LOCK_GIVE(hdw->ctl_lock);
3292
3293         return ret;
3294 }
3295
3296
3297 static int pvr2_read_register(struct pvr2_hdw *hdw, u16 reg, u32 *data)
3298 {
3299         int ret = 0;
3300
3301         LOCK_TAKE(hdw->ctl_lock);
3302
3303         hdw->cmd_buffer[0] = FX2CMD_REG_READ;  /* read register prefix */
3304         hdw->cmd_buffer[1] = 0;
3305         hdw->cmd_buffer[2] = 0;
3306         hdw->cmd_buffer[3] = 0;
3307         hdw->cmd_buffer[4] = 0;
3308         hdw->cmd_buffer[5] = 0;
3309         hdw->cmd_buffer[6] = (reg >> 8) & 0xff;
3310         hdw->cmd_buffer[7] = reg & 0xff;
3311
3312         ret |= pvr2_send_request(hdw, hdw->cmd_buffer, 8, hdw->cmd_buffer, 4);
3313         *data = PVR2_COMPOSE_LE(hdw->cmd_buffer,0);
3314
3315         LOCK_GIVE(hdw->ctl_lock);
3316
3317         return ret;
3318 }
3319
3320
3321 void pvr2_hdw_render_useless(struct pvr2_hdw *hdw)
3322 {
3323         if (!hdw->flag_ok) return;
3324         pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3325                    "Device being rendered inoperable");
3326         if (hdw->vid_stream) {
3327                 pvr2_stream_setup(hdw->vid_stream,NULL,0,0);
3328         }
3329         hdw->flag_ok = 0;
3330         trace_stbit("flag_ok",hdw->flag_ok);
3331         pvr2_hdw_state_sched(hdw);
3332 }
3333
3334
3335 void pvr2_hdw_device_reset(struct pvr2_hdw *hdw)
3336 {
3337         int ret;
3338         pvr2_trace(PVR2_TRACE_INIT,"Performing a device reset...");
3339         ret = usb_lock_device_for_reset(hdw->usb_dev,NULL);
3340         if (ret == 1) {
3341                 ret = usb_reset_device(hdw->usb_dev);
3342                 usb_unlock_device(hdw->usb_dev);
3343         } else {
3344                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3345                            "Failed to lock USB device ret=%d",ret);
3346         }
3347         if (init_pause_msec) {
3348                 pvr2_trace(PVR2_TRACE_INFO,
3349                            "Waiting %u msec for hardware to settle",
3350                            init_pause_msec);
3351                 msleep(init_pause_msec);
3352         }
3353
3354 }
3355
3356
3357 void pvr2_hdw_cpureset_assert(struct pvr2_hdw *hdw,int val)
3358 {
3359         char da[1];
3360         unsigned int pipe;
3361         int ret;
3362
3363         if (!hdw->usb_dev) return;
3364
3365         pvr2_trace(PVR2_TRACE_INIT,"cpureset_assert(%d)",val);
3366
3367         da[0] = val ? 0x01 : 0x00;
3368
3369         /* Write the CPUCS register on the 8051.  The lsb of the register
3370            is the reset bit; a 1 asserts reset while a 0 clears it. */
3371         pipe = usb_sndctrlpipe(hdw->usb_dev, 0);
3372         ret = usb_control_msg(hdw->usb_dev,pipe,0xa0,0x40,0xe600,0,da,1,HZ);
3373         if (ret < 0) {
3374                 pvr2_trace(PVR2_TRACE_ERROR_LEGS,
3375                            "cpureset_assert(%d) error=%d",val,ret);
3376                 pvr2_hdw_render_useless(hdw);
3377         }
3378 }
3379
3380
3381 int pvr2_hdw_cmd_deep_reset(struct pvr2_hdw *hdw)
3382 {
3383         return pvr2_issue_simple_cmd(hdw,FX2CMD_DEEP_RESET);
3384 }
3385
3386
3387 int pvr2_hdw_cmd_powerup(struct pvr2_hdw *hdw)
3388 {
3389         return pvr2_issue_simple_cmd(hdw,FX2CMD_POWER_ON);
3390 }
3391
3392
3393 int pvr2_hdw_cmd_powerdown(struct pvr2_hdw *hdw)
3394 {
3395         return pvr2_issue_simple_cmd(hdw,FX2CMD_POWER_OFF);
3396 }
3397
3398
3399 int pvr2_hdw_cmd_decoder_reset(struct pvr2_hdw *hdw)
3400 {
3401         if (!hdw->decoder_ctrl) {
3402                 pvr2_trace(PVR2_TRACE_INIT,
3403                            "Unable to reset decoder: nothing attached");
3404                 return -ENOTTY;
3405         }
3406
3407         if (!hdw->decoder_ctrl->force_reset) {
3408                 pvr2_trace(PVR2_TRACE_INIT,
3409                            "Unable to reset decoder: not implemented");
3410                 return -ENOTTY;
3411         }
3412
3413         pvr2_trace(PVR2_TRACE_INIT,
3414                    "Requesting decoder reset");
3415         hdw->decoder_ctrl->force_reset(hdw->decoder_ctrl->ctxt);
3416         return 0;
3417 }
3418
3419
3420 static int pvr2_hdw_cmd_hcw_demod_reset(struct pvr2_hdw *hdw, int onoff)
3421 {
3422         hdw->flag_ok = !0;
3423         return pvr2_issue_simple_cmd(hdw,
3424                                      FX2CMD_HCW_DEMOD_RESETIN |
3425                                      (1 << 8) |
3426                                      ((onoff ? 1 : 0) << 16));
3427 }
3428
3429
3430 static int pvr2_hdw_cmd_onair_fe_power_ctrl(struct pvr2_hdw *hdw, int onoff)
3431 {
3432         hdw->flag_ok = !0;
3433         return pvr2_issue_simple_cmd(hdw,(onoff ?
3434                                           FX2CMD_ONAIR_DTV_POWER_ON :
3435                                           FX2CMD_ONAIR_DTV_POWER_OFF));
3436 }
3437
3438
3439 static int pvr2_hdw_cmd_onair_digital_path_ctrl(struct pvr2_hdw *hdw,
3440                                                 int onoff)
3441 {
3442         return pvr2_issue_simple_cmd(hdw,(onoff ?
3443                                           FX2CMD_ONAIR_DTV_STREAMING_ON :
3444                                           FX2CMD_ONAIR_DTV_STREAMING_OFF));
3445 }
3446
3447
3448 static void pvr2_hdw_cmd_modeswitch(struct pvr2_hdw *hdw,int digitalFl)
3449 {
3450         int cmode;
3451         /* Compare digital/analog desired setting with current setting.  If
3452            they don't match, fix it... */
3453         cmode = (digitalFl ? PVR2_PATHWAY_DIGITAL : PVR2_PATHWAY_ANALOG);
3454         if (cmode == hdw->pathway_state) {
3455                 /* They match; nothing to do */
3456                 return;
3457         }
3458
3459         switch (hdw->hdw_desc->digital_control_scheme) {
3460         case PVR2_DIGITAL_SCHEME_HAUPPAUGE:
3461                 pvr2_hdw_cmd_hcw_demod_reset(hdw,digitalFl);
3462                 if (cmode == PVR2_PATHWAY_ANALOG) {
3463                         /* If moving to analog mode, also force the decoder
3464                            to reset.  If no decoder is attached, then it's
3465                            ok to ignore this because if/when the decoder
3466                            attaches, it will reset itself at that time. */
3467                         pvr2_hdw_cmd_decoder_reset(hdw);
3468                 }
3469                 break;
3470         case PVR2_DIGITAL_SCHEME_ONAIR:
3471                 /* Supposedly we should always have the power on whether in
3472                    digital or analog mode.  But for now do what appears to
3473                    work... */
3474                 pvr2_hdw_cmd_onair_fe_power_ctrl(hdw,digitalFl);
3475                 break;
3476         default: break;
3477         }
3478
3479         pvr2_hdw_untrip_unlocked(hdw);
3480         hdw->pathway_state = cmode;
3481 }
3482
3483
3484 static void pvr2_led_ctrl_hauppauge(struct pvr2_hdw *hdw, int onoff)
3485 {
3486         /* change some GPIO data
3487          *
3488          * note: bit d7 of dir appears to control the LED,
3489          * so we shut it off here.
3490          *
3491          */
3492         if (onoff) {
3493                 pvr2_hdw_gpio_chg_dir(hdw, 0xffffffff, 0x00000481);
3494         } else {
3495                 pvr2_hdw_gpio_chg_dir(hdw, 0xffffffff, 0x00000401);
3496         }
3497         pvr2_hdw_gpio_chg_out(hdw, 0xffffffff, 0x00000000);
3498 }
3499
3500
3501 typedef void (*led_method_func)(struct pvr2_hdw *,int);
3502
3503 static led_method_func led_methods[] = {
3504         [PVR2_LED_SCHEME_HAUPPAUGE] = pvr2_led_ctrl_hauppauge,
3505 };
3506
3507
3508 /* Toggle LED */
3509 static void pvr2_led_ctrl(struct pvr2_hdw *hdw,int onoff)
3510 {
3511         unsigned int scheme_id;
3512         led_method_func fp;
3513
3514         if ((!onoff) == (!hdw->led_on)) return;
3515
3516         hdw->led_on = onoff != 0;
3517
3518         scheme_id = hdw->hdw_desc->led_scheme;
3519         if (scheme_id < ARRAY_SIZE(led_methods)) {
3520                 fp = led_methods[scheme_id];
3521         } else {
3522                 fp = NULL;
3523         }
3524
3525         if (fp) (*fp)(hdw,onoff);
3526 }
3527
3528
3529 /* Stop / start video stream transport */
3530 static int pvr2_hdw_cmd_usbstream(struct pvr2_hdw *hdw,int runFl)
3531 {
3532         int ret;
3533
3534         /* If we're in analog mode, then just issue the usual analog
3535            command. */
3536         if (hdw->pathway_state == PVR2_PATHWAY_ANALOG) {
3537                 return pvr2_issue_simple_cmd(hdw,
3538                                              (runFl ?
3539                                               FX2CMD_STREAMING_ON :
3540                                               FX2CMD_STREAMING_OFF));
3541                 /*Note: Not reached */
3542         }
3543
3544         if (hdw->pathway_state != PVR2_PATHWAY_DIGITAL) {
3545                 /* Whoops, we don't know what mode we're in... */
3546                 return -EINVAL;
3547         }
3548
3549         /* To get here we have to be in digital mode.  The mechanism here
3550            is unfortunately different for different vendors.  So we switch
3551            on the device's digital scheme attribute in order to figure out
3552            what to do. */
3553         switch (hdw->hdw_desc->digital_control_scheme) {
3554         case PVR2_DIGITAL_SCHEME_HAUPPAUGE:
3555                 return pvr2_issue_simple_cmd(hdw,
3556                                              (runFl ?
3557                                               FX2CMD_HCW_DTV_STREAMING_ON :
3558                                               FX2CMD_HCW_DTV_STREAMING_OFF));
3559         case PVR2_DIGITAL_SCHEME_ONAIR:
3560                 ret = pvr2_issue_simple_cmd(hdw,
3561                                             (runFl ?
3562                                              FX2CMD_STREAMING_ON :
3563                                              FX2CMD_STREAMING_OFF));
3564                 if (ret) return ret;
3565                 return pvr2_hdw_cmd_onair_digital_path_ctrl(hdw,runFl);
3566         default:
3567                 return -EINVAL;
3568         }
3569 }
3570
3571
3572 /* Evaluate whether or not state_pathway_ok can change */
3573 static int state_eval_pathway_ok(struct pvr2_hdw *hdw)
3574 {
3575         if (hdw->state_pathway_ok) {
3576                 /* Nothing to do if pathway is already ok */
3577                 return 0;
3578         }
3579         if (!hdw->state_pipeline_idle) {
3580                 /* Not allowed to change anything if pipeline is not idle */
3581                 return 0;
3582         }
3583         pvr2_hdw_cmd_modeswitch(hdw,hdw->input_val == PVR2_CVAL_INPUT_DTV);
3584         hdw->state_pathway_ok = !0;
3585         trace_stbit("state_pathway_ok",hdw->state_pathway_ok);
3586         return !0;
3587 }
3588
3589
3590 /* Evaluate whether or not state_encoder_ok can change */
3591 static int state_eval_encoder_ok(struct pvr2_hdw *hdw)
3592 {
3593         if (hdw->state_encoder_ok) return 0;
3594         if (hdw->flag_tripped) return 0;
3595         if (hdw->state_encoder_run) return 0;
3596         if (hdw->state_encoder_config) return 0;
3597         if (hdw->state_decoder_run) return 0;
3598         if (hdw->state_usbstream_run) return 0;
3599         if (hdw->pathway_state == PVR2_PATHWAY_DIGITAL) {
3600                 if (!hdw->hdw_desc->flag_digital_requires_cx23416) return 0;
3601         } else if (hdw->pathway_state != PVR2_PATHWAY_ANALOG) {
3602                 return 0;
3603         }
3604
3605         if (pvr2_upload_firmware2(hdw) < 0) {
3606                 hdw->flag_tripped = !0;
3607                 trace_stbit("flag_tripped",hdw->flag_tripped);
3608                 return !0;
3609         }
3610         hdw->state_encoder_ok = !0;
3611         trace_stbit("state_encoder_ok",hdw->state_encoder_ok);
3612         return !0;
3613 }
3614
3615
3616 /* Evaluate whether or not state_encoder_config can change */
3617 static int state_eval_encoder_config(struct pvr2_hdw *hdw)
3618 {
3619         if (hdw->state_encoder_config) {
3620                 if (hdw->state_encoder_ok) {
3621                         if (hdw->state_pipeline_req &&
3622                             !hdw->state_pipeline_pause) return 0;
3623                 }
3624                 hdw->state_encoder_config = 0;
3625                 hdw->state_encoder_waitok = 0;
3626                 trace_stbit("state_encoder_waitok",hdw->state_encoder_waitok);
3627                 /* paranoia - solve race if timer just completed */
3628                 del_timer_sync(&hdw->encoder_wait_timer);
3629         } else {
3630                 if (!hdw->state_pathway_ok ||
3631                     (hdw->pathway_state != PVR2_PATHWAY_ANALOG) ||
3632                     !hdw->state_encoder_ok ||
3633                     !hdw->state_pipeline_idle ||
3634                     hdw->state_pipeline_pause ||
3635                     !hdw->state_pipeline_req ||
3636                     !hdw->state_pipeline_config) {
3637                         /* We must reset the enforced wait interval if
3638                            anything has happened that might have disturbed
3639                            the encoder.  This should be a rare case. */
3640                         if (timer_pending(&hdw->encoder_wait_timer)) {
3641                                 del_timer_sync(&hdw->encoder_wait_timer);
3642                         }
3643                         if (hdw->state_encoder_waitok) {
3644                                 /* Must clear the state - therefore we did
3645                                    something to a state bit and must also
3646                                    return true. */
3647                                 hdw->state_encoder_waitok = 0;
3648                                 trace_stbit("state_encoder_waitok",
3649                                             hdw->state_encoder_waitok);
3650                                 return !0;
3651                         }
3652                         return 0;
3653                 }
3654                 if (!hdw->state_encoder_waitok) {
3655                         if (!timer_pending(&hdw->encoder_wait_timer)) {
3656                                 /* waitok flag wasn't set and timer isn't
3657                                    running.  Check flag once more to avoid
3658                                    a race then start the timer.  This is
3659                                    the point when we measure out a minimal
3660                                    quiet interval before doing something to
3661                                    the encoder. */
3662                                 if (!hdw->state_encoder_waitok) {
3663                                         hdw->encoder_wait_timer.expires =
3664                                                 jiffies +
3665                                                 (HZ * TIME_MSEC_ENCODER_WAIT
3666                                                  / 1000);
3667                                         add_timer(&hdw->encoder_wait_timer);
3668                                 }
3669                         }
3670                         /* We can't continue until we know we have been
3671                            quiet for the interval measured by this
3672                            timer. */
3673                         return 0;
3674                 }
3675                 pvr2_encoder_configure(hdw);
3676                 if (hdw->state_encoder_ok) hdw->state_encoder_config = !0;
3677         }
3678         trace_stbit("state_encoder_config",hdw->state_encoder_config);
3679         return !0;
3680 }
3681
3682
3683 /* Return true if the encoder should not be running. */
3684 static int state_check_disable_encoder_run(struct pvr2_hdw *hdw)
3685 {
3686         if (!hdw->state_encoder_ok) {
3687                 /* Encoder isn't healthy at the moment, so stop it. */
3688                 return !0;
3689         }
3690         if (!hdw->state_pathway_ok) {
3691                 /* Mode is not understood at the moment (i.e. it wants to
3692                    change), so encoder must be stopped. */
3693                 return !0;
3694         }
3695
3696         switch (hdw->pathway_state) {
3697         case PVR2_PATHWAY_ANALOG:
3698                 if (!hdw->state_decoder_run) {
3699                         /* We're in analog mode and the decoder is not
3700                            running; thus the encoder should be stopped as
3701                            well. */
3702                         return !0;
3703                 }
3704                 break;
3705         case PVR2_PATHWAY_DIGITAL:
3706                 if (hdw->state_encoder_runok) {
3707                         /* This is a funny case.  We're in digital mode so
3708                            really the encoder should be stopped.  However
3709                            if it really is running, only kill it after
3710                            runok has been set.  This gives a chance for the
3711                            onair quirk to function (encoder must run
3712                            briefly first, at least once, before onair
3713                            digital streaming can work). */
3714                         return !0;
3715                 }
3716                 break;
3717         default:
3718                 /* Unknown mode; so encoder should be stopped. */
3719                 return !0;
3720         }
3721
3722         /* If we get here, we haven't found a reason to stop the
3723            encoder. */
3724         return 0;
3725 }
3726
3727
3728 /* Return true if the encoder should be running. */
3729 static int state_check_enable_encoder_run(struct pvr2_hdw *hdw)
3730 {
3731         if (!hdw->state_encoder_ok) {
3732                 /* Don't run the encoder if it isn't healthy... */
3733                 return 0;
3734         }
3735         if (!hdw->state_pathway_ok) {
3736                 /* Don't run the encoder if we don't (yet) know what mode
3737                    we need to be in... */
3738                 return 0;
3739         }
3740
3741         switch (hdw->pathway_state) {
3742         case PVR2_PATHWAY_ANALOG:
3743                 if (hdw->state_decoder_run) {
3744                         /* In analog mode, if the decoder is running, then
3745                            run the encoder. */
3746                         return !0;
3747                 }
3748                 break;
3749         case PVR2_PATHWAY_DIGITAL:
3750                 if ((hdw->hdw_desc->digital_control_scheme ==
3751                      PVR2_DIGITAL_SCHEME_ONAIR) &&
3752                     !hdw->state_encoder_runok) {
3753                         /* This is a quirk.  OnAir hardware won't stream
3754                            digital until the encoder has been run at least
3755                            once, for a minimal period of time (empiricially
3756                            measured to be 1/4 second).  So if we're on
3757                            OnAir hardware and the encoder has never been
3758                            run at all, then start the encoder.  Normal
3759                            state machine logic in the driver will
3760                            automatically handle the remaining bits. */
3761                         return !0;
3762                 }
3763                 break;
3764         default:
3765                 /* For completeness (unknown mode; encoder won't run ever) */
3766                 break;
3767         }
3768         /* If we get here, then we haven't found any reason to run the
3769            encoder, so don't run it. */
3770         return 0;
3771 }
3772
3773
3774 /* Evaluate whether or not state_encoder_run can change */
3775 static int state_eval_encoder_run(struct pvr2_hdw *hdw)
3776 {
3777         if (hdw->state_encoder_run) {
3778                 if (!state_check_disable_encoder_run(hdw)) return 0;
3779                 if (hdw->state_encoder_ok) {
3780                         del_timer_sync(&hdw->encoder_run_timer);
3781                         if (pvr2_encoder_stop(hdw) < 0) return !0;
3782                 }
3783                 hdw->state_encoder_run = 0;
3784         } else {
3785                 if (!state_check_enable_encoder_run(hdw)) return 0;
3786                 if (pvr2_encoder_start(hdw) < 0) return !0;
3787                 hdw->state_encoder_run = !0;
3788                 if (!hdw->state_encoder_runok) {
3789                         hdw->encoder_run_timer.expires =
3790                                 jiffies + (HZ * TIME_MSEC_ENCODER_OK / 1000);
3791                         add_timer(&hdw->encoder_run_timer);
3792                 }
3793         }
3794         trace_stbit("state_encoder_run",hdw->state_encoder_run);
3795         return !0;
3796 }
3797
3798
3799 /* Timeout function for quiescent timer. */
3800 static void pvr2_hdw_quiescent_timeout(unsigned long data)
3801 {
3802         struct pvr2_hdw *hdw = (struct pvr2_hdw *)data;
3803         hdw->state_decoder_quiescent = !0;
3804         trace_stbit("state_decoder_quiescent",hdw->state_decoder_quiescent);
3805         hdw->state_stale = !0;
3806         queue_work(hdw->workqueue,&hdw->workpoll);
3807 }
3808
3809
3810 /* Timeout function for encoder wait timer. */
3811 static void pvr2_hdw_encoder_wait_timeout(unsigned long data)
3812 {
3813         struct pvr2_hdw *hdw = (struct pvr2_hdw *)data;
3814         hdw->state_encoder_waitok = !0;
3815         trace_stbit("state_encoder_waitok",hdw->state_encoder_waitok);
3816         hdw->state_stale = !0;
3817         queue_work(hdw->workqueue,&hdw->workpoll);
3818 }
3819
3820
3821 /* Timeout function for encoder run timer. */
3822 static void pvr2_hdw_encoder_run_timeout(unsigned long data)
3823 {
3824         struct pvr2_hdw *hdw = (struct pvr2_hdw *)data;
3825         if (!hdw->state_encoder_runok) {
3826                 hdw->state_encoder_runok = !0;
3827                 trace_stbit("state_encoder_runok",hdw->state_encoder_runok);
3828                 hdw->state_stale = !0;
3829                 queue_work(hdw->workqueue,&hdw->workpoll);
3830         }
3831 }
3832
3833
3834 /* Evaluate whether or not state_decoder_run can change */
3835 static int state_eval_decoder_run(struct pvr2_hdw *hdw)
3836 {
3837         if (hdw->state_decoder_run) {
3838                 if (hdw->state_encoder_ok) {
3839                         if (hdw->state_pipeline_req &&
3840                             !hdw->state_pipeline_pause &&
3841                             hdw->state_pathway_ok) return 0;
3842                 }
3843                 if (!hdw->flag_decoder_missed) {
3844                         pvr2_decoder_enable(hdw,0);
3845                 }
3846                 hdw->state_decoder_quiescent = 0;
3847                 hdw->state_decoder_run = 0;
3848                 /* paranoia - solve race if timer just completed */
3849                 del_timer_sync(&hdw->quiescent_timer);
3850         } else {
3851                 if (!hdw->state_decoder_quiescent) {
3852                         if (!timer_pending(&hdw->quiescent_timer)) {
3853                                 /* We don't do something about the
3854                                    quiescent timer until right here because
3855                                    we also want to catch cases where the
3856                                    decoder was already not running (like
3857                                    after initialization) as opposed to
3858                                    knowing that we had just stopped it.
3859                                    The second flag check is here to cover a
3860                                    race - the timer could have run and set
3861                                    this flag just after the previous check
3862                                    but before we did the pending check. */
3863                                 if (!hdw->state_decoder_quiescent) {
3864                                         hdw->quiescent_timer.expires =
3865                                                 jiffies +
3866                                                 (HZ * TIME_MSEC_DECODER_WAIT
3867                                                  / 1000);
3868                                         add_timer(&hdw->quiescent_timer);
3869                                 }
3870                         }
3871                         /* Don't allow decoder to start again until it has
3872                            been quiesced first.  This little detail should
3873                            hopefully further stabilize the encoder. */
3874                         return 0;
3875                 }
3876                 if (!hdw->state_pathway_ok ||
3877                     (hdw->pathway_state != PVR2_PATHWAY_ANALOG) ||
3878                     !hdw->state_pipeline_req ||
3879                     hdw->state_pipeline_pause ||
3880                     !hdw->state_pipeline_config ||
3881                     !hdw->state_encoder_config ||
3882                     !hdw->state_encoder_ok) return 0;
3883                 del_timer_sync(&hdw->quiescent_timer);
3884                 if (hdw->flag_decoder_missed) return 0;
3885                 if (pvr2_decoder_enable(hdw,!0) < 0) return 0;
3886                 hdw->state_decoder_quiescent = 0;
3887                 hdw->state_decoder_run = !0;
3888         }
3889         trace_stbit("state_decoder_quiescent",hdw->state_decoder_quiescent);
3890         trace_stbit("state_decoder_run",hdw->state_decoder_run);
3891         return !0;
3892 }
3893
3894
3895 /* Evaluate whether or not state_usbstream_run can change */
3896 static int state_eval_usbstream_run(struct pvr2_hdw *hdw)
3897 {
3898         if (hdw->state_usbstream_run) {
3899                 int fl = !0;
3900                 if (hdw->pathway_state == PVR2_PATHWAY_ANALOG) {
3901                         fl = (hdw->state_encoder_ok &&
3902                               hdw->state_encoder_run);
3903                 } else if ((hdw->pathway_state == PVR2_PATHWAY_DIGITAL) &&
3904                            (hdw->hdw_desc->flag_digital_requires_cx23416)) {
3905                         fl = hdw->state_encoder_ok;
3906                 }
3907                 if (fl &&
3908                     hdw->state_pipeline_req &&
3909                     !hdw->state_pipeline_pause &&
3910                     hdw->state_pathway_ok) {
3911                         return 0;
3912                 }
3913                 pvr2_hdw_cmd_usbstream(hdw,0);
3914                 hdw->state_usbstream_run = 0;
3915         } else {
3916                 if (!hdw->state_pipeline_req ||
3917                     hdw->state_pipeline_pause ||
3918                     !hdw->state_pathway_ok) return 0;
3919                 if (hdw->pathway_state == PVR2_PATHWAY_ANALOG) {
3920                         if (!hdw->state_encoder_ok ||
3921                             !hdw->state_encoder_run) return 0;
3922                 } else if ((hdw->pathway_state == PVR2_PATHWAY_DIGITAL) &&
3923                            (hdw->hdw_desc->flag_digital_requires_cx23416)) {
3924                         if (!hdw->state_encoder_ok) return 0;
3925                         if (hdw->state_encoder_run) return 0;
3926                         if (hdw->hdw_desc->digital_control_scheme ==
3927                             PVR2_DIGITAL_SCHEME_ONAIR) {
3928                                 /* OnAir digital receivers won't stream
3929                                    unless the analog encoder has run first.
3930                                    Why?  I have no idea.  But don't even
3931                                    try until we know the analog side is
3932                                    known to have run. */
3933                                 if (!hdw->state_encoder_runok) return 0;
3934                         }
3935                 }
3936                 if (pvr2_hdw_cmd_usbstream(hdw,!0) < 0) return 0;
3937                 hdw->state_usbstream_run = !0;
3938         }
3939         trace_stbit("state_usbstream_run",hdw->state_usbstream_run);
3940         return !0;
3941 }
3942
3943
3944 /* Attempt to configure pipeline, if needed */
3945 static int state_eval_pipeline_config(struct pvr2_hdw *hdw)
3946 {
3947         if (hdw->state_pipeline_config ||
3948             hdw->state_pipeline_pause) return 0;
3949         pvr2_hdw_commit_execute(hdw);
3950         return !0;
3951 }
3952
3953
3954 /* Update pipeline idle and pipeline pause tracking states based on other
3955    inputs.  This must be called whenever the other relevant inputs have
3956    changed. */
3957 static int state_update_pipeline_state(struct pvr2_hdw *hdw)
3958 {
3959         unsigned int st;
3960         int updatedFl = 0;
3961         /* Update pipeline state */
3962         st = !(hdw->state_encoder_run ||
3963                hdw->state_decoder_run ||
3964                hdw->state_usbstream_run ||
3965                (!hdw->state_decoder_quiescent));
3966         if (!st != !hdw->state_pipeline_idle) {
3967                 hdw->state_pipeline_idle = st;
3968                 updatedFl = !0;
3969         }
3970         if (hdw->state_pipeline_idle && hdw->state_pipeline_pause) {
3971                 hdw->state_pipeline_pause = 0;
3972                 updatedFl = !0;
3973         }
3974         return updatedFl;
3975 }
3976
3977
3978 typedef int (*state_eval_func)(struct pvr2_hdw *);
3979
3980 /* Set of functions to be run to evaluate various states in the driver. */
3981 static const state_eval_func eval_funcs[] = {
3982         state_eval_pathway_ok,
3983         state_eval_pipeline_config,
3984         state_eval_encoder_ok,
3985         state_eval_encoder_config,
3986         state_eval_decoder_run,
3987         state_eval_encoder_run,
3988         state_eval_usbstream_run,
3989 };
3990
3991
3992 /* Process various states and return true if we did anything interesting. */
3993 static int pvr2_hdw_state_update(struct pvr2_hdw *hdw)
3994 {
3995         unsigned int i;
3996         int state_updated = 0;
3997         int check_flag;
3998
3999         if (!hdw->state_stale) return 0;
4000         if ((hdw->fw1_state != FW1_STATE_OK) ||
4001             !hdw->flag_ok) {
4002                 hdw->state_stale = 0;
4003                 return !0;
4004         }
4005         /* This loop is the heart of the entire driver.  It keeps trying to
4006            evaluate various bits of driver state until nothing changes for
4007            one full iteration.  Each "bit of state" tracks some global
4008            aspect of the driver, e.g. whether decoder should run, if
4009            pipeline is configured, usb streaming is on, etc.  We separately
4010            evaluate each of those questions based on other driver state to
4011            arrive at the correct running configuration. */
4012         do {
4013                 check_flag = 0;
4014                 state_update_pipeline_state(hdw);
4015                 /* Iterate over each bit of state */
4016                 for (i = 0; (i<ARRAY_SIZE(eval_funcs)) && hdw->flag_ok; i++) {
4017                         if ((*eval_funcs[i])(hdw)) {
4018                                 check_flag = !0;
4019                                 state_updated = !0;
4020                                 state_update_pipeline_state(hdw);
4021                         }
4022                 }
4023         } while (check_flag && hdw->flag_ok);
4024         hdw->state_stale = 0;
4025         trace_stbit("state_stale",hdw->state_stale);
4026         return state_updated;
4027 }
4028
4029
4030 static unsigned int print_input_mask(unsigned int msk,
4031                                      char *buf,unsigned int acnt)
4032 {
4033         unsigned int idx,ccnt;
4034         unsigned int tcnt = 0;
4035         for (idx = 0; idx < ARRAY_SIZE(control_values_input); idx++) {
4036                 if (!((1 << idx) & msk)) continue;
4037                 ccnt = scnprintf(buf+tcnt,
4038                                  acnt-tcnt,
4039                                  "%s%s",
4040                                  (tcnt ? ", " : ""),
4041                                  control_values_input[idx]);
4042                 tcnt += ccnt;
4043         }
4044         return tcnt;
4045 }
4046
4047
4048 static const char *pvr2_pathway_state_name(int id)
4049 {
4050         switch (id) {
4051         case PVR2_PATHWAY_ANALOG: return "analog";
4052         case PVR2_PATHWAY_DIGITAL: return "digital";
4053         default: return "unknown";
4054         }
4055 }
4056
4057
4058 static unsigned int pvr2_hdw_report_unlocked(struct pvr2_hdw *hdw,int which,
4059                                              char *buf,unsigned int acnt)
4060 {
4061         switch (which) {
4062         case 0:
4063                 return scnprintf(
4064                         buf,acnt,
4065                         "driver:%s%s%s%s%s <mode=%s>",
4066                         (hdw->flag_ok ? " <ok>" : " <fail>"),
4067                         (hdw->flag_init_ok ? " <init>" : " <uninitialized>"),
4068                         (hdw->flag_disconnected ? " <disconnected>" :
4069                          " <connected>"),
4070                         (hdw->flag_tripped ? " <tripped>" : ""),
4071                         (hdw->flag_decoder_missed ? " <no decoder>" : ""),
4072                         pvr2_pathway_state_name(hdw->pathway_state));
4073
4074         case 1:
4075                 return scnprintf(
4076                         buf,acnt,
4077                         "pipeline:%s%s%s%s",
4078                         (hdw->state_pipeline_idle ? " <idle>" : ""),
4079                         (hdw->state_pipeline_config ?
4080                          " <configok>" : " <stale>"),
4081                         (hdw->state_pipeline_req ? " <req>" : ""),
4082                         (hdw->state_pipeline_pause ? " <pause>" : ""));
4083         case 2:
4084                 return scnprintf(
4085                         buf,acnt,
4086                         "worker:%s%s%s%s%s%s%s",
4087                         (hdw->state_decoder_run ?
4088                          " <decode:run>" :
4089                          (hdw->state_decoder_quiescent ?
4090                           "" : " <decode:stop>")),
4091                         (hdw->state_decoder_quiescent ?
4092                          " <decode:quiescent>" : ""),
4093                         (hdw->state_encoder_ok ?
4094                          "" : " <encode:init>"),
4095                         (hdw->state_encoder_run ?
4096                          (hdw->state_encoder_runok ?
4097                           " <encode:run>" :
4098                           " <encode:firstrun>") :
4099                          (hdw->state_encoder_runok ?
4100                           " <encode:stop>" :
4101                           " <encode:virgin>")),
4102                         (hdw->state_encoder_config ?
4103                          " <encode:configok>" :
4104                          (hdw->state_encoder_waitok ?
4105                           "" : " <encode:waitok>")),
4106                         (hdw->state_usbstream_run ?
4107                          " <usb:run>" : " <usb:stop>"),
4108                         (hdw->state_pathway_ok ?
4109                          " <pathway:ok>" : ""));
4110         case 3:
4111                 return scnprintf(
4112                         buf,acnt,
4113                         "state: %s",
4114                         pvr2_get_state_name(hdw->master_state));
4115         case 4: {
4116                 unsigned int tcnt = 0;
4117                 unsigned int ccnt;
4118
4119                 ccnt = scnprintf(buf,
4120                                  acnt,
4121                                  "Hardware supported inputs: ");
4122                 tcnt += ccnt;
4123                 tcnt += print_input_mask(hdw->input_avail_mask,
4124                                          buf+tcnt,
4125                                          acnt-tcnt);
4126                 if (hdw->input_avail_mask != hdw->input_allowed_mask) {
4127                         ccnt = scnprintf(buf+tcnt,
4128                                          acnt-tcnt,
4129                                          "; allowed inputs: ");
4130                         tcnt += ccnt;
4131                         tcnt += print_input_mask(hdw->input_allowed_mask,
4132                                                  buf+tcnt,
4133                                                  acnt-tcnt);
4134                 }
4135                 return tcnt;
4136         }
4137         case 5: {
4138                 struct pvr2_stream_stats stats;
4139                 if (!hdw->vid_stream) break;
4140                 pvr2_stream_get_stats(hdw->vid_stream,
4141                                       &stats,
4142                                       0);
4143                 return scnprintf(
4144                         buf,acnt,
4145                         "Bytes streamed=%u"
4146                         " URBs: queued=%u idle=%u ready=%u"
4147                         " processed=%u failed=%u",
4148                         stats.bytes_processed,
4149                         stats.buffers_in_queue,
4150                         stats.buffers_in_idle,
4151                         stats.buffers_in_ready,
4152                         stats.buffers_processed,
4153                         stats.buffers_failed);
4154         }
4155         default: break;
4156         }
4157         return 0;
4158 }
4159
4160
4161 unsigned int pvr2_hdw_state_report(struct pvr2_hdw *hdw,
4162                                    char *buf,unsigned int acnt)
4163 {
4164         unsigned int bcnt,ccnt,idx;
4165         bcnt = 0;
4166         LOCK_TAKE(hdw->big_lock);
4167         for (idx = 0; ; idx++) {
4168                 ccnt = pvr2_hdw_report_unlocked(hdw,idx,buf,acnt);
4169                 if (!ccnt) break;
4170                 bcnt += ccnt; acnt -= ccnt; buf += ccnt;
4171                 if (!acnt) break;
4172                 buf[0] = '\n'; ccnt = 1;
4173                 bcnt += ccnt; acnt -= ccnt; buf += ccnt;
4174         }
4175         LOCK_GIVE(hdw->big_lock);
4176         return bcnt;
4177 }
4178
4179
4180 static void pvr2_hdw_state_log_state(struct pvr2_hdw *hdw)
4181 {
4182         char buf[128];
4183         unsigned int idx,ccnt;
4184
4185         for (idx = 0; ; idx++) {
4186                 ccnt = pvr2_hdw_report_unlocked(hdw,idx,buf,sizeof(buf));
4187                 if (!ccnt) break;
4188                 printk(KERN_INFO "%s %.*s\n",hdw->name,ccnt,buf);
4189         }
4190 }
4191
4192
4193 /* Evaluate and update the driver's current state, taking various actions
4194    as appropriate for the update. */
4195 static int pvr2_hdw_state_eval(struct pvr2_hdw *hdw)
4196 {
4197         unsigned int st;
4198         int state_updated = 0;
4199         int callback_flag = 0;
4200         int analog_mode;
4201
4202         pvr2_trace(PVR2_TRACE_STBITS,
4203                    "Drive state check START");
4204         if (pvrusb2_debug & PVR2_TRACE_STBITS) {
4205                 pvr2_hdw_state_log_state(hdw);
4206         }
4207
4208         /* Process all state and get back over disposition */
4209         state_updated = pvr2_hdw_state_update(hdw);
4210
4211         analog_mode = (hdw->pathway_state != PVR2_PATHWAY_DIGITAL);
4212
4213         /* Update master state based upon all other states. */
4214         if (!hdw->flag_ok) {
4215                 st = PVR2_STATE_DEAD;
4216         } else if (hdw->fw1_state != FW1_STATE_OK) {
4217                 st = PVR2_STATE_COLD;
4218         } else if ((analog_mode ||
4219                     hdw->hdw_desc->flag_digital_requires_cx23416) &&
4220                    !hdw->state_encoder_ok) {
4221                 st = PVR2_STATE_WARM;
4222         } else if (hdw->flag_tripped ||
4223                    (analog_mode && hdw->flag_decoder_missed)) {
4224                 st = PVR2_STATE_ERROR;
4225         } else if (hdw->state_usbstream_run &&
4226                    (!analog_mode ||
4227                     (hdw->state_encoder_run && hdw->state_decoder_run))) {
4228                 st = PVR2_STATE_RUN;
4229         } else {
4230                 st = PVR2_STATE_READY;
4231         }
4232         if (hdw->master_state != st) {
4233                 pvr2_trace(PVR2_TRACE_STATE,
4234                            "Device state change from %s to %s",
4235                            pvr2_get_state_name(hdw->master_state),
4236                            pvr2_get_state_name(st));
4237                 pvr2_led_ctrl(hdw,st == PVR2_STATE_RUN);
4238                 hdw->master_state = st;
4239                 state_updated = !0;
4240                 callback_flag = !0;
4241         }
4242         if (state_updated) {
4243                 /* Trigger anyone waiting on any state changes here. */
4244                 wake_up(&hdw->state_wait_data);
4245         }
4246
4247         if (pvrusb2_debug & PVR2_TRACE_STBITS) {
4248                 pvr2_hdw_state_log_state(hdw);
4249         }
4250         pvr2_trace(PVR2_TRACE_STBITS,
4251                    "Drive state check DONE callback=%d",callback_flag);
4252
4253         return callback_flag;
4254 }
4255
4256
4257 /* Cause kernel thread to check / update driver state */
4258 static void pvr2_hdw_state_sched(struct pvr2_hdw *hdw)
4259 {
4260         if (hdw->state_stale) return;
4261         hdw->state_stale = !0;
4262         trace_stbit("state_stale",hdw->state_stale);
4263         queue_work(hdw->workqueue,&hdw->workpoll);
4264 }
4265
4266
4267 int pvr2_hdw_gpio_get_dir(struct pvr2_hdw *hdw,u32 *dp)
4268 {
4269         return pvr2_read_register(hdw,PVR2_GPIO_DIR,dp);
4270 }
4271
4272
4273 int pvr2_hdw_gpio_get_out(struct pvr2_hdw *hdw,u32 *dp)
4274 {
4275         return pvr2_read_register(hdw,PVR2_GPIO_OUT,dp);
4276 }
4277
4278
4279 int pvr2_hdw_gpio_get_in(struct pvr2_hdw *hdw,u32 *dp)
4280 {
4281         return pvr2_read_register(hdw,PVR2_GPIO_IN,dp);
4282 }
4283
4284
4285 int pvr2_hdw_gpio_chg_dir(struct pvr2_hdw *hdw,u32 msk,u32 val)
4286 {
4287         u32 cval,nval;
4288         int ret;
4289         if (~msk) {
4290                 ret = pvr2_read_register(hdw,PVR2_GPIO_DIR,&cval);
4291                 if (ret) return ret;
4292                 nval = (cval & ~msk) | (val & msk);
4293                 pvr2_trace(PVR2_TRACE_GPIO,
4294                            "GPIO direction changing 0x%x:0x%x"
4295                            " from 0x%x to 0x%x",
4296                            msk,val,cval,nval);
4297         } else {
4298                 nval = val;
4299                 pvr2_trace(PVR2_TRACE_GPIO,
4300                            "GPIO direction changing to 0x%x",nval);
4301         }
4302         return pvr2_write_register(hdw,PVR2_GPIO_DIR,nval);
4303 }
4304
4305
4306 int pvr2_hdw_gpio_chg_out(struct pvr2_hdw *hdw,u32 msk,u32 val)
4307 {
4308         u32 cval,nval;
4309         int ret;
4310         if (~msk) {
4311                 ret = pvr2_read_register(hdw,PVR2_GPIO_OUT,&cval);
4312                 if (ret) return ret;
4313                 nval = (cval & ~msk) | (val & msk);
4314                 pvr2_trace(PVR2_TRACE_GPIO,
4315                            "GPIO output changing 0x%x:0x%x from 0x%x to 0x%x",
4316                            msk,val,cval,nval);
4317         } else {
4318                 nval = val;
4319                 pvr2_trace(PVR2_TRACE_GPIO,
4320                            "GPIO output changing to 0x%x",nval);
4321         }
4322         return pvr2_write_register(hdw,PVR2_GPIO_OUT,nval);
4323 }
4324
4325
4326 unsigned int pvr2_hdw_get_input_available(struct pvr2_hdw *hdw)
4327 {
4328         return hdw->input_avail_mask;
4329 }
4330
4331
4332 unsigned int pvr2_hdw_get_input_allowed(struct pvr2_hdw *hdw)
4333 {
4334         return hdw->input_allowed_mask;
4335 }
4336
4337
4338 static int pvr2_hdw_set_input(struct pvr2_hdw *hdw,int v)
4339 {
4340         if (hdw->input_val != v) {
4341                 hdw->input_val = v;
4342                 hdw->input_dirty = !0;
4343         }
4344
4345         /* Handle side effects - if we switch to a mode that needs the RF
4346            tuner, then select the right frequency choice as well and mark
4347            it dirty. */
4348         if (hdw->input_val == PVR2_CVAL_INPUT_RADIO) {
4349                 hdw->freqSelector = 0;
4350                 hdw->freqDirty = !0;
4351         } else if ((hdw->input_val == PVR2_CVAL_INPUT_TV) ||
4352                    (hdw->input_val == PVR2_CVAL_INPUT_DTV)) {
4353                 hdw->freqSelector = 1;
4354                 hdw->freqDirty = !0;
4355         }
4356         return 0;
4357 }
4358
4359
4360 int pvr2_hdw_set_input_allowed(struct pvr2_hdw *hdw,
4361                                unsigned int change_mask,
4362                                unsigned int change_val)
4363 {
4364         int ret = 0;
4365         unsigned int nv,m,idx;
4366         LOCK_TAKE(hdw->big_lock);
4367         do {
4368                 nv = hdw->input_allowed_mask & ~change_mask;
4369                 nv |= (change_val & change_mask);
4370                 nv &= hdw->input_avail_mask;
4371                 if (!nv) {
4372                         /* No legal modes left; return error instead. */
4373                         ret = -EPERM;
4374                         break;
4375                 }
4376                 hdw->input_allowed_mask = nv;
4377                 if ((1 << hdw->input_val) & hdw->input_allowed_mask) {
4378                         /* Current mode is still in the allowed mask, so
4379                            we're done. */
4380                         break;
4381                 }
4382                 /* Select and switch to a mode that is still in the allowed
4383                    mask */
4384                 if (!hdw->input_allowed_mask) {
4385                         /* Nothing legal; give up */
4386                         break;
4387                 }
4388                 m = hdw->input_allowed_mask;
4389                 for (idx = 0; idx < (sizeof(m) << 3); idx++) {
4390                         if (!((1 << idx) & m)) continue;
4391                         pvr2_hdw_set_input(hdw,idx);
4392                         break;
4393                 }
4394         } while (0);
4395         LOCK_GIVE(hdw->big_lock);
4396         return ret;
4397 }
4398
4399
4400 /* Find I2C address of eeprom */
4401 static int pvr2_hdw_get_eeprom_addr(struct pvr2_hdw *hdw)
4402 {
4403         int result;
4404         LOCK_TAKE(hdw->ctl_lock); do {
4405                 hdw->cmd_buffer[0] = FX2CMD_GET_EEPROM_ADDR;
4406                 result = pvr2_send_request(hdw,
4407                                            hdw->cmd_buffer,1,
4408                                            hdw->cmd_buffer,1);
4409                 if (result < 0) break;
4410                 result = hdw->cmd_buffer[0];
4411         } while(0); LOCK_GIVE(hdw->ctl_lock);
4412         return result;
4413 }
4414
4415
4416 int pvr2_hdw_register_access(struct pvr2_hdw *hdw,
4417                              u32 match_type, u32 match_chip, u64 reg_id,
4418                              int setFl,u64 *val_ptr)
4419 {
4420 #ifdef CONFIG_VIDEO_ADV_DEBUG
4421         struct pvr2_i2c_client *cp;
4422         struct v4l2_register req;
4423         int stat = 0;
4424         int okFl = 0;
4425
4426         if (!capable(CAP_SYS_ADMIN)) return -EPERM;
4427
4428         req.match_type = match_type;
4429         req.match_chip = match_chip;
4430         req.reg = reg_id;
4431         if (setFl) req.val = *val_ptr;
4432         mutex_lock(&hdw->i2c_list_lock); do {
4433                 list_for_each_entry(cp, &hdw->i2c_clients, list) {
4434                         if (!v4l2_chip_match_i2c_client(
4435                                     cp->client,
4436                                     req.match_type, req.match_chip)) {
4437                                 continue;
4438                         }
4439                         stat = pvr2_i2c_client_cmd(
4440                                 cp,(setFl ? VIDIOC_DBG_S_REGISTER :
4441                                     VIDIOC_DBG_G_REGISTER),&req);
4442                         if (!setFl) *val_ptr = req.val;
4443                         okFl = !0;
4444                         break;
4445                 }
4446         } while (0); mutex_unlock(&hdw->i2c_list_lock);
4447         if (okFl) {
4448                 return stat;
4449         }
4450         return -EINVAL;
4451 #else
4452         return -ENOSYS;
4453 #endif
4454 }
4455
4456
4457 /*
4458   Stuff for Emacs to see, in order to encourage consistent editing style:
4459   *** Local Variables: ***
4460   *** mode: c ***
4461   *** fill-column: 75 ***
4462   *** tab-width: 8 ***
4463   *** c-basic-offset: 8 ***
4464   *** End: ***
4465   */