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