Showing error 1639

User: Jiri Slaby
Error type: Invalid Pointer Dereference
Error type description: A pointer which is invalid is being dereferenced
File location: drivers/media/video/pvrusb2/pvrusb2-hdw.c
Line in file: 2563
Project: Linux Kernel
Project version: 2.6.28
Tools: Smatch (1.59)
Entered: 2013-09-10 07:54:05 UTC


Source:

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