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