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