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