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