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