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