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