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