pgm_functions.c 186 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/***************************************************************************//**
* @file      pgm_functions.c
* @brief     Sensor/FPGA programming functions, called from  IRQ/tasklet in
*            response to the parameter changes
* @copyright Copyright 2008-2016 (C) Elphel, Inc.
* @par <b>License</b>
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation, either version 2 of the License, or
*  (at your option) any later version.
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*  You should have received a copy of the GNU General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
/*  $Log: pgm_functions.c,v $
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
*!  Revision 1.24  2012/03/14 00:05:41  elphel
*!  8.2.1 - GPS speed, x353.bit file tested on Eyesis
*!
*!  Revision 1.23  2012/01/16 01:48:00  elphel
*!  increased initial sensor clock frequency (20MHz->40MHz)
*!
*!  Revision 1.22  2011/12/22 05:40:05  elphel
*!  bug fix
*!
*!  Revision 1.21  2010/08/10 21:10:41  elphel
*!  portrait mode now includes all 4 rotations (2 bits)
*!
*!  Revision 1.20  2010/08/03 23:37:34  elphel
*!  rev 8.0.8.37, portrait mode support
*!
*!  Revision 1.19  2010/08/01 19:29:24  elphel
*!  files updated to support coring function for noise filtering
*!
*!  Revision 1.18  2010/06/06 04:24:10  elphel
*!  updated debug message
*!
*!  Revision 1.17  2010/06/05 07:11:48  elphel
*!  modified startup options
*!
*!  Revision 1.16  2010/06/02 16:31:04  elphel
*!  Added P_MULTI_SELECTED parameter
*!
*!  Revision 1.15  2010/06/01 08:30:36  elphel
*!  support for the FPGA code 03534022  with optional master time stamp over the inter-camera sync line(s)
*!
*!  Revision 1.14  2010/05/25 00:52:23  elphel
*!  8.0.8.20, working on multi-sensor
*!
*!  Revision 1.13  2010/05/21 06:12:16  elphel
*!  continue working on multi-sensor software
*!
*!  Revision 1.12  2010/05/13 03:39:31  elphel
*!  8.0.8.12 -  drivers modified for multi-sensor operation
*!
*!  Revision 1.11  2010/04/30 23:38:49  elphel
*!  fixed WOI_TOP in linescan mode
*!
*!  Revision 1.10  2010/04/30 00:29:54  elphel
*!  bug fixes related to linescan mode
*!
*!  Revision 1.9  2010/04/28 02:34:33  elphel
*!  8.0.6.6 - added support for linescan mode (also useful for high fps small images). 2.5K full line pairs/second with 5MPix sensor
*!
*!  Revision 1.8  2010/04/24 21:40:15  elphel
*!  8.0.8.4 (FPGA 03534016), most changes related to sensor signals phase adjustments
*!
*!  Revision 1.7  2010/01/27 22:51:52  elphel
*!  turned off ELPHEL_DEBUG, fixed errors caused by that.
*!
*!  Revision 1.6  2009/03/16 02:07:41  elphel
*!  Bug fix when calculating total width for focus processing - FPGA requires data 16 less than the actual WOI width
*!
*!  Revision 1.5  2008/12/08 21:55:02  elphel
*!  making 3MPix work, minor cleanup
*!
*!  Revision 1.4  2008/12/02 19:11:08  elphel
*!  bug fix in sensor detection, removed unneeded initialization for P_GAIN*
*!
*!  Revision 1.3  2008/12/02 00:29:04  elphel
*!  Added FIXME for the known problem
*!
*!  Revision 1.2  2008/11/30 05:01:03  elphel
*!  Changing gains/scales behavior
*!
*!  Revision 1.1.1.1  2008/11/27 20:04:00  elphel
*!
*!
*!  Revision 1.32  2008/11/27 09:27:31  elphel
*!  Support fro new parameters (vignetting correction related)
*!
*!  Revision 1.31  2008/11/14 01:01:40  elphel
*!  fixed new bug in pgm_gammaload
*!
*!  Revision 1.30  2008/11/13 05:40:45  elphel
*!  8.0.alpha16 - modified histogram storage, profiling
*!
*!  Revision 1.29  2008/11/03 18:43:18  elphel
*!  8.0.alpha12 with working apps/astreamer
*!
*!  Revision 1.28  2008/10/31 18:26:32  elphel
*!  Adding support for constants like SENSOR_REGS32 (defined constant plus 32 to simplify referencing sensor registers from PHP
*!
*!  Revision 1.27  2008/10/29 04:18:28  elphel
*!  v.8.0.alpha10 made a separate structure for global parameters (not related to particular frames in a frame queue)
*!
*!  Revision 1.26  2008/10/23 08:08:05  elphel
*!  corrected histogram window size setup (data written to FPGA is actual window size -2 for both width and height)
*!
*!  Revision 1.25  2008/10/22 05:29:03  elphel
*!  Rev. 8.0.alpha5 - working on external trigger mode - moved programming away from the sequencer that can only pass 24 data bits
*!
*!  Revision 1.24  2008/10/21 04:03:39  elphel
*!  bug fix (missing break in switch)
*!
*!  Revision 1.23  2008/10/20 18:45:07  elphel
*!  just more debug printk
*!
*!  Revision 1.22  2008/10/18 06:14:21  elphel
*!  8.0.alpha4 - removed some obsolete parameters, renumbered others, split P_FLIP into P_FLIPH and P_FLIPV (different latencies because of bad frames), pgm_window-> pgm_window, pgm_window_safe
*!
*!  Revision 1.21  2008/10/17 05:44:48  elphel
*!  fixing latencies
*!
*!  Revision 1.20  2008/10/12 06:13:10  elphel
*!  snapshot
*!
*!  Revision 1.19  2008/10/11 18:46:07  elphel
*!  snapshot
*!
*!  Revision 1.18  2008/10/08 21:26:25  elphel
*!  snapsot 7.2.0.pre4 - first images (actually - second)
*!
*!  Revision 1.17  2008/10/06 08:33:03  elphel
*!  snapshot, first images
*!
*!  Revision 1.15  2008/10/05 05:13:33  elphel
*!  snapshot003
*!
*!  Revision 1.14  2008/10/04 16:10:12  elphel
*!  snapshot
*!
*!  Revision 1.13  2008/09/28 00:31:57  elphel
*!  snapshot
*!
*!  Revision 1.12  2008/09/25 00:58:12  elphel
*!  snapshot
*!
*!  Revision 1.11  2008/09/22 22:55:49  elphel
*!  snapshot
*!
*!  Revision 1.10  2008/09/19 04:37:26  elphel
*!  snapshot
*!
*!  Revision 1.9  2008/09/16 00:49:32  elphel
*!  snapshot
*!
*!  Revision 1.8  2008/09/12 20:40:13  elphel
*!  snapshot
*!
*!  Revision 1.7  2008/09/12 00:23:59  elphel
*!  removed cc353.c, cc353.h
*!
*!  Revision 1.6  2008/09/05 23:21:32  elphel
*!  snapshot
*!
*!  Revision 1.4  2008/09/04 17:37:13  elphel
*!  documenting
*!
*!  Revision 1.3  2008/07/29 01:15:06  elphel
*!  another snapshot
*!
*!  Revision 1.2  2008/07/27 23:25:07  elphel
*!  next snapshot
*!
*!  Revision 1.1  2008/07/27 04:27:49  elphel
*!  next snapshot
*/

// TODO:remove unneeded
183
//#define DEBUG // should be before linux/module.h - enables dev_dbg at boot in this file (needs "debug" in bootarg)
184 185
#include <linux/types.h> // for div 64
#include <asm/div64.h>   // for div 64
186 187 188 189 190 191 192 193 194 195

#include <linux/module.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/vmalloc.h>
Andrey Filippov's avatar
Andrey Filippov committed
196 197
//#include <linux/platform_device.h>
#include <linux/device.h> // for dev_dbg, platform_device.h is OK too
198 199 200 201 202

#include <asm/byteorder.h> // endians
#include <asm/io.h>

#include <asm/irq.h>
203
#include <linux/delay.h>
204
#include <asm/uaccess.h>
205
#include <uapi/elphel/c313a.h>
206 207
#include "framepars.h"
#include "sensor_common.h"
208 209
#include "multi10359.h"
#include "mt9x001.h"
210 211 212 213 214
#include "gamma_tables.h"
#include "quantization_tables.h"
#include "latency.h"
#include "pgm_functions.h"
#include "jpeghead.h"      // to program FPGA Huffman tables
215
#include "x393.h"
216
#include "sensor_i2c.h"
217
#include "x393_videomem.h"
Andrey Filippov's avatar
Andrey Filippov committed
218
#include "detect_sensors.h"
219
#include "x393_fpga_functions.h"
220

221 222 223 224 225
// NC393 debug macros
#include "debug393.h"



226
/**
227
 * @brief optional debug output macros (obsolete)
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
 */
#if ELPHEL_DEBUG
// #define MDF2(x) { if (GLOBALPARS(G_DEBUG) & (1 <<2)) {printk("%s:%d:%s ",__FILE__,__LINE__,__FUNCTION__ );x ;} }
 #define MDF3(x) { if (GLOBALPARS(G_DEBUG) & (1 <<3)) {printk("%s:%d:%s ",__FILE__,__LINE__,__FUNCTION__ );x ;} }
 #define MDF9(x) { if (GLOBALPARS(G_DEBUG) & (1 <<9)) {printk("%s:%d:%s ",__FILE__,__LINE__,__FUNCTION__ );x ;} }
 #define MDF16(x) { if (GLOBALPARS(G_DEBUG) & (1 <<16)) {printk("%s:%d:%s ",__FILE__,__LINE__,__FUNCTION__ );x ;} }
 #define MDF23(x) { if (GLOBALPARS(G_DEBUG) & (1 <<23)) {printk("%s:%d:%s ",__FILE__,__LINE__,__FUNCTION__ );x ;} }
 #define ELPHEL_DEBUG_THIS 0
// #define ELPHEL_DEBUG_THIS 1
#else
// #define MDF2(x)
 #define MDF3(x)
 #define MDF9(x)
 #define MDF16(x)
 #define MDF23(x)
 #define ELPHEL_DEBUG_THIS 0
#endif

#if ELPHEL_DEBUG_THIS
  #define MDF1(x) printk("%s:%d:%s ",__FILE__,__LINE__,__FUNCTION__ );x
  #define MD1(x)  printk("%s:%d: ",__FILE__,__LINE__ );x
#else
  #define MDF1(x)
  #define MD1(x)
#endif

Andrey Filippov's avatar
Andrey Filippov committed
254 255 256 257 258 259 260 261
static struct device *g_dev_ptr=NULL; ///< Global pointer to basic device structure. This pointer is used in debugfs output functions
void pgm_functions_set_device(struct device *dev)
{
    g_dev_ptr = dev;
    mt9x001_set_device(dev);
    multi10359_set_device(dev);
}
//dev_info(g_dev_ptr,
262

263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
  int pgm_recalcseq     (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_detectsensor  (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_sensorphase   (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_i2c           (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_initsensor    (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_afterinit     (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_multisens     (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_window        (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_window_safe   (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_window_common (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_exposure      (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_gains         (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_triggermode   (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_sensorin      (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_sensorstop    (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_sensorrun     (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_gamma         (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_hist          (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_aexp          (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_quality       (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_memsensor     (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_memcompressor (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_limitfps      (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_compmode      (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_focusmode     (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_trigseq       (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_irq           (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_comprestart   (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_compstop      (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_compctl       (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_gammaload     (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_sensorregs    (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);
  int pgm_prescal       (int sensor_port, struct sensor_t * sensor,  struct framepars_t * thispars, struct framepars_t * prevpars, int frame16);

/** Initialize array of functions that program different acquisition parameters (some are sensor dependent)
 * @return always 0 */
Andrey Filippov's avatar
Andrey Filippov committed
299
int init_pgm_proc(int sensor_port)
300 301
{
    int i;
Andrey Filippov's avatar
Andrey Filippov committed
302 303
    struct sensorproc_t * sensorproc = &asensorproc[sensor_port];
    dev_dbg(g_dev_ptr,"Initializing generic parameter-triggered function, port=%d\n",sensor_port); // OK NULL device here (not yet set)
304 305
    MDP(DBGB_PSFN,sensor_port,"Initializing generic parameter-triggered function, %s\n","") // OK NULL device here (not yet set)

306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
    for (i=0;i<64;i++) sensorproc->pgm_func[i]=NULL;
    sensorproc->pgm_func[onchange_recalcseq]=    &pgm_recalcseq;     // recalculate sequences/latencies, according to P_SKIP, P_TRIG
    sensorproc->pgm_func[onchange_detectsensor]= &pgm_detectsensor;  // detect sensor type, sets sensor structure (capabilities), function pointers
    sensorproc->pgm_func[onchange_sensorphase]=  &pgm_sensorphase;   // program sensor clock/phase
    sensorproc->pgm_func[onchange_i2c]=          &pgm_i2c;           // program i2c
    sensorproc->pgm_func[onchange_initsensor]=   &pgm_initsensor;    // resets sensor, reads sensor registers, schedules "secret" manufacturer's corrections to the registers (stops/re-enables hardware i2c)
    sensorproc->pgm_func[onchange_afterinit]=    &pgm_afterinit;     // restore image size, decimation,... after sensor reset or set them according to sensor capabilities if none were specified
    sensorproc->pgm_func[onchange_multisens]=    &pgm_multisens;     // changes related to multiplexed sensors
    sensorproc->pgm_func[onchange_window]=       &pgm_window;        // program sensor WOI and mirroring (flipping)
    sensorproc->pgm_func[onchange_window_safe]=  &pgm_window_safe;   // program sensor WOI and mirroring (flipping) - lower latency, no bad frames
    sensorproc->pgm_func[onchange_exposure]=     &pgm_exposure;      // program exposure
    sensorproc->pgm_func[onchange_gains]=        &pgm_gains;         // program analog gains
    sensorproc->pgm_func[onchange_triggermode]=  &pgm_triggermode;   // program sensor trigger mode
    sensorproc->pgm_func[onchange_sensorin]=     &pgm_sensorin;      // program sensor input in FPGA (Bayer, 8/16 bits, ??)
    sensorproc->pgm_func[onchange_sensorstop]=   &pgm_sensorstop;    // Stop acquisition from the sensor to the FPGA (start has latency of 2)
    sensorproc->pgm_func[onchange_sensorrun]=    &pgm_sensorrun;     // Start/single acquisition from the sensor to the FPGA (stop has latency of 1)
    sensorproc->pgm_func[onchange_gamma]=        &pgm_gamma;         // program gamma table
    sensorproc->pgm_func[onchange_hist]=         &pgm_hist;          // program histogram window
    sensorproc->pgm_func[onchange_aexp]=         &pgm_aexp;          // program autoexposure mode
    sensorproc->pgm_func[onchange_quality]=      &pgm_quality;       // program quantization table(s)
    sensorproc->pgm_func[onchange_memsensor]=    &pgm_memsensor;     // program memory channels 0 (sensor->memory) and 1 (memory->FPN)
    sensorproc->pgm_func[onchange_memcompressor]=&pgm_memcompressor; // program memory channel 2 (memory->compressor)
    sensorproc->pgm_func[onchange_limitfps]=     &pgm_limitfps;      // check compressor will keep up, limit sensor FPS if needed
    sensorproc->pgm_func[onchange_compmode]=     &pgm_compmode;      // program compressor modes
    sensorproc->pgm_func[onchange_focusmode]=    &pgm_focusmode;     // program focus modes
    sensorproc->pgm_func[onchange_trigseq]=      &pgm_trigseq;       // program sequencer (int/ext)
    sensorproc->pgm_func[onchange_irq]=          &pgm_irq;           // program smart IRQ mode
    sensorproc->pgm_func[onchange_comprestart]=  &pgm_comprestart;   // restart after changing geometry  (recognizes ASAP and programs memory channel 2 then)
    sensorproc->pgm_func[onchange_compstop]=     &pgm_compstop;      // stop compressor when changing geometry
    sensorproc->pgm_func[onchange_compctl]=      &pgm_compctl;       // only start/stop/single (after explicitly changed, not when geometry was changed)
    sensorproc->pgm_func[onchange_gammaload]=    &pgm_gammaload;     // write gamma tables (should be prepared). Maybe - just last byte, to activate?
    sensorproc->pgm_func[onchange_sensorregs]=   &pgm_sensorregs;    // write sensor registers (only changed from outside the driver as they may have different latencies)?
    sensorproc->pgm_func[onchange_prescal]=      &pgm_prescal;       // change scales for per-color digital gains, apply vignetting correction
339

340
    return 0;
341
}
Andrey Filippov's avatar
Andrey Filippov committed
342 343 344 345 346 347
/** Add sensor-specific processing function (executes after the non-specific function with the same index) */
int add_sensor_proc(int port,   ///< sensor port
                    int index,  ///< index function index (internally 32 is added to distinguish from the common (not sensor-specific) functions
                    int (*sens_func)(int sensor_port, struct sensor_t * ,  struct framepars_t * , struct framepars_t *, int ))
                                ///< sens_func pointer to a sensor-specific function
                                ///< @return always 0
348
{
Andrey Filippov's avatar
Andrey Filippov committed
349
    dev_dbg(g_dev_ptr,"add_sensor_proc(%d, 0x%x,...)\n", port, index);
350
    MDP(DBGB_PSFN, port,"add_sensor_proc(%d, 0x%x,...)\n", port, index)
Andrey Filippov's avatar
Andrey Filippov committed
351
    asensorproc[port].pgm_func[32+(index & 0x1f)]=       sens_func;
352
    return 0;
353 354
}

355
/** Detect and initialize sensor and related data structures
356 357
 * - detect sensor type
 * - set sensor structure (capabilities),
358 359
 * - set function pointers (by directly calling sensor specific \b *_pgm_detectsensor */
int pgm_detectsensor   (int sensor_port,               ///< sensor port number (0..3)
Andrey Filippov's avatar
Andrey Filippov committed
360 361 362 363 364 365
        struct sensor_t * sensor,      ///< sensor static parameters (capabilities)
        struct framepars_t * thispars, ///< sensor current parameters
        struct framepars_t * prevpars, ///< sensor previous parameters (not used here)
        int frame16)                   ///< 4-bit (hardware) frame number parameters should
///< be applied to,  negative - ASAP
///< @return OK - 0, <0 - error
366
{
Andrey Filippov's avatar
Andrey Filippov committed
367
    x393_camsync_mode_t camsync_mode = {.d32=0};
368
    int was_sensor_freq = 0; // 90000000; // getClockFreq(1);
Andrey Filippov's avatar
Andrey Filippov committed
369 370 371
    int qperiod;
    int i2cbytes;
    int phase;
Andrey Filippov's avatar
Andrey Filippov committed
372 373
    int mux,sens;
    dev_dbg(g_dev_ptr,"{%d}  frame16=%d\n",sensor_port,frame16);
374 375
    MDP(DBGB_PSFN, sensor_port,"frame16=%d\n",frame16)

Andrey Filippov's avatar
Andrey Filippov committed
376
    if (frame16 >= 0) return -1; // can only work in ASAP mode
Andrey Filippov's avatar
Andrey Filippov committed
377 378 379 380 381 382 383 384 385
    if (thispars->pars[P_SENSOR]) {
        dev_dbg(g_dev_ptr,"{%d}  frame16=%d, SENSOR ALREADY DETECTED = %d\n",sensor_port,frame16, (int) thispars->pars[P_SENSOR]);
        return 0; // Sensor is already detected - do not bother (to re-detect it P_SENSOR should be set to 0)
    }
    // no other initializations, just the sensor-related stuff (starting with lowest sensor clock)    // stop hardware i2c controller, so it will not get stuck when waiting for !busy



    #ifndef NC353
Andrey Filippov's avatar
Andrey Filippov committed
386 387
    // NC393 - nothing to do here - use a separate module for sensor setup: DT, sysfs, something else (add pin pullup/down)
    // currently assign same sensor to all subchannles (first present)
Andrey Filippov's avatar
Andrey Filippov committed
388 389 390
//    thispars->pars[P_SENSOR] = get_detected_sensor_code(sensor_port, -1); // "-1" - first detected sensor
    sens=get_detected_sensor_code(sensor_port, -1); // "-1" - first detected sensor
//    setFramePar(sensor_port, thispars, P_SENSOR,  sens); //  FIXME: NC393
Andrey Filippov's avatar
Andrey Filippov committed
391 392
    GLOBALPARS(sensor_port, G_SUBCHANNELS) = get_subchannels(sensor_port);
    mux = get_detected_mux_code(sensor_port); // none/detect/10359
Andrey Filippov's avatar
Andrey Filippov committed
393 394 395
    dev_dbg(g_dev_ptr,"port = %d, mux = %d, sens= %d\n",sensor_port, mux, sens);
//    if ((mux == SENSOR_NONE) && (thispars->pars[P_SENSOR] == SENSOR_NONE))
    if ((mux == SENSOR_NONE) && (sens == SENSOR_NONE))
Andrey Filippov's avatar
Andrey Filippov committed
396 397
        return 0; // no sensor/mux enabled on this port
    //TODO NC393: turn on both sequencers why MRST is active, then i2c frame will definitely match ? Or is it already done in FPGA?
Andrey Filippov's avatar
Andrey Filippov committed
398
    dev_dbg(g_dev_ptr,"Restarting both command and i2c sequencers for port %d\n",sensor_port);
Andrey Filippov's avatar
Andrey Filippov committed
399 400 401
    sequencer_stop_run_reset(sensor_port, SEQ_CMD_RESET);
    sequencer_stop_run_reset(sensor_port, SEQ_CMD_RUN);  // also programs status update
    i2c_stop_run_reset      (sensor_port, I2C_CMD_RESET);
Andrey Filippov's avatar
Andrey Filippov committed
402
    dev_dbg(g_dev_ptr,"Setting i2c drive mode for port %d\n",sensor_port);
Andrey Filippov's avatar
Andrey Filippov committed
403 404
    i2c_drive_mode          (sensor_port, SDA_DRIVE_HIGH, SDA_RELEASE);
    i2c_stop_run_reset      (sensor_port, I2C_CMD_RUN); // also programs status update
Andrey Filippov's avatar
Andrey Filippov committed
405
    legacy_i2c(1<<sensor_port);// Setup i2c pages for legacy i2c commands. TODO NC393: update for compatibility with 14MPix
Andrey Filippov's avatar
Andrey Filippov committed
406 407 408 409 410 411
    camsync_mode.trig =     0;
    camsync_mode.trig_set = 1;
    camsync_mode.ext =      1; // use external timestamp (default)
    camsync_mode.ext_set =  1;
    x393_camsync_mode (camsync_mode);

Andrey Filippov's avatar
Andrey Filippov committed
412
    //     dev_dbg(g_dev_ptr,"trying MT9P001\n");
Andrey Filippov's avatar
Andrey Filippov committed
413 414 415
    //      mt9x001_pgm_detectsensor(sensor_port, sensor,  thispars, prevpars, frame16);  // try Micron 5.0 Mpixel - should return sensor type

    if (mux != SENSOR_NONE) {
Andrey Filippov's avatar
Andrey Filippov committed
416
        dev_dbg(g_dev_ptr,"Mux mode for port %d is %d, tryng 10359\n",sensor_port, mux);
417 418
        MDP(DBGB_PADD, sensor_port,"Mux mode for port %d is %d, tryng 10359\n",sensor_port, mux)

Andrey Filippov's avatar
Andrey Filippov committed
419 420
        // try multisensor here (before removing MRST)
        multisensor_pgm_detectsensor (sensor_port, sensor,  thispars, prevpars, frame16);  // multisensor
Andrey Filippov's avatar
Andrey Filippov committed
421 422
    } else {
        dev_dbg(g_dev_ptr,"Mux mode for port %d SENSOR_NONE, skipping 10359 detection\n",sensor_port);
423
        MDP(DBGB_PADD, sensor_port,"Mux mode for port %d SENSOR_NONE, skipping 10359 detection\n",sensor_port)
Andrey Filippov's avatar
Andrey Filippov committed
424 425 426 427 428 429 430 431 432
    }
//    if ((thispars->pars[P_SENSOR]==0) ||  // multisensor not detected
//            ((thispars->pars[P_SENSOR] & SENSOR_MASK) == SENSOR_MT9X001)) { // or is (from DT) SENSOR_MT9X001
    if ((thispars->pars[P_SENSOR]==0) &&                    // multisensor not detected
            (((sens & SENSOR_MASK) == SENSOR_MT9X001) ||    // and from DT it is some SENSOR_MT9*001
             ((sens & SENSOR_MASK) == SENSOR_MT9P006) )) {  // or SENSOR_MT9P006 or friends
//        dev_dbg(g_dev_ptr,"removing MRST from the sensor\n");
//        dev_info(g_dev_ptr,"pgm_detectsensor(%d): TRYING MT9P001\n",sensor_port);
        dev_dbg(g_dev_ptr,"trying MT9P001, port=%d\n",sensor_port);
433
        MDP(DBGB_PADD, sensor_port,"trying MT9P001, port=%d\n",sensor_port)
Andrey Filippov's avatar
Andrey Filippov committed
434 435
        mt9x001_pgm_detectsensor(sensor_port, sensor,  thispars, prevpars, frame16);  // try Micron 5.0 Mpixel - should return sensor type
    }
Andrey Filippov's avatar
Andrey Filippov committed
436 437
    setFramePar(sensor_port, thispars, P_CLK_FPGA,  200000000); //  FIXME: NC393
    setFramePar(sensor_port, thispars, P_CLK_SENSOR,  48000000);
Andrey Filippov's avatar
Andrey Filippov committed
438 439
    if (thispars->pars[P_SENSOR] == SENSOR_DETECT) {
        sensor->sensorType=SENSOR_NONE;                 // to prevent from initializing again
Andrey Filippov's avatar
Andrey Filippov committed
440
        dev_dbg(g_dev_ptr,"No image sensor found\n");
441
        MDP(DBGB_PADD, sensor_port,"No image sensor found%s\n","")
Andrey Filippov's avatar
Andrey Filippov committed
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
    }
    setFramePar(sensor_port, thispars, P_SENSOR_WIDTH,   sensor->imageWidth);  // Maybe get rid of duplicates?
    setFramePar(sensor_port, thispars, P_SENSOR_HEIGHT,  sensor->imageHeight); // Maybe get rid of duplicates?
    if (sensor->i2c_period==0) sensor->i2c_period=2500;           // SCL period in ns, (standard i2c - 2500)
    qperiod=thispars->pars[P_I2C_QPERIOD];
    if (qperiod==0) qperiod=(sensor->i2c_period * (thispars->pars[P_CLK_FPGA]/1000))/4000000;
    setFramePar(sensor_port, thispars, P_I2C_QPERIOD | FRAMEPAIR_FORCE_NEWPROC,  qperiod); // force i2c
    i2cbytes=thispars->pars[P_I2C_BYTES];
    if (i2cbytes==0) i2cbytes=sensor->i2c_bytes;
    setFramePar(sensor_port, thispars, P_I2C_BYTES | FRAMEPAIR_FORCE_NEWPROC,  i2cbytes); // force i2c
    // restore/set sensor clock
    if ((was_sensor_freq < sensor->minClockFreq) || (was_sensor_freq > sensor->maxClockFreq)) was_sensor_freq=sensor->nomClockFreq;
    setFramePar(sensor_port, thispars, P_CLK_SENSOR | FRAMEPAIR_FORCE_NEWPROC,  was_sensor_freq); // will schedule clock/phase adjustment
    phase=thispars->pars[P_SENSOR_PHASE];
    // TODO: remove phase adjustment from here
    if (phase==0) {
        phase= 0x40000;
        setFramePar(sensor_port, thispars, P_SENSOR_PHASE | FRAMEPAIR_FORCE_NEWPROC,  phase); // will schedule clock/phase adjustment
    }
    setFramePar(sensor_port, thispars, P_IRQ_SMART | FRAMEPAIR_FORCE_NEWPROC,  3);        // smart IRQ mode programming (and enable interrupts)

    // NOTE: sensor detected - enabling camera interrupts here (actual interrupts will start later)
    // Here interrupts are disabled - with compressor_interrupts (0) earlier in this function)

Andrey Filippov's avatar
Andrey Filippov committed
466
    compressor_interrupts (1,sensor_port); // FIXME: Should they already be set beforfe detection? If not - remove from framepars.php
Andrey Filippov's avatar
Andrey Filippov committed
467 468
    sensor_interrupts     (1,sensor_port);
    return 0;
469
#else
Andrey Filippov's avatar
Andrey Filippov committed
470 471
    // NOTE: disabling interrupts here !!!
    compressor_interrupts (0);
Andrey Filippov's avatar
Andrey Filippov committed
472
    dev_dbg(g_dev_ptr,"%s Disabled camera interrupts\n",__func__);
Andrey Filippov's avatar
Andrey Filippov committed
473 474
    // This 3 initialization commands were not here, trying to temporarily fix problem when WP was 8/16 words higher than actual data in DMA buffer
    if (GLOBALPARS(sensor_port, G_TEST_CTL_BITS) & (1<< G_TEST_CTL_BITS_RESET_DMA_COMPRESSOR )) {
Andrey Filippov's avatar
Andrey Filippov committed
475
        dev_dbg(g_dev_ptr,"%s x313_dma_stop()\n",__func__);
Andrey Filippov's avatar
Andrey Filippov committed
476
        ///    x313_dma_stop();
Andrey Filippov's avatar
Andrey Filippov committed
477
        dev_dbg(g_dev_ptr,"%s x313_dma_init()\n",__func__);
Andrey Filippov's avatar
Andrey Filippov committed
478
        ///    x313_dma_init();
Andrey Filippov's avatar
Andrey Filippov committed
479
        dev_dbg(g_dev_ptr,"%s reset_compressor()\n",__func__);
Andrey Filippov's avatar
Andrey Filippov committed
480 481 482 483 484 485 486 487 488
        reset_compressor(sensor_port);
    }
    // TODO: Add 10347 detection here //   if (IS_KAI11000) return init_KAI11000();
    // Need to set slow clock
    //  f1=imageParamsR[P_CLK_SENSOR]=20000000; setClockFreq(1, imageParamsR[P_CLK_SENSOR]); X3X3_RSTSENSDCM;
    was_sensor_freq=getClockFreq(1); // using clock driver data, not thispars
    setFramePar(sensor_port, thispars, P_CLK_FPGA,  getClockFreq(0)); // just in case - read the actual fpga clock frequency and store it (no actions)
    setFramePar(sensor_port, thispars, P_CLK_SENSOR,  48000000);
    setClockFreq(1, thispars->pars[P_CLK_SENSOR]);
Andrey Filippov's avatar
Andrey Filippov committed
489
    dev_dbg(g_dev_ptr,"\nsensor clock set to %d\n",(int) thispars->pars[P_CLK_SENSOR]);
Andrey Filippov's avatar
Andrey Filippov committed
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
    udelay (100);// 0.0001 sec to stabilize clocks
    X3X3_RSTSENSDCM; // FPGA DCM can fail after clock change, needs to be reset
    X3X3_SENSDCM_CLK2X_RESET; // reset pclk2x DCM also
    mdelay (50);// 0.05 sec to stabilize clocks
    // setting reasonable state of the control signals
    CCAM_DCLK_ON;
    CCAM_CNVEN_OFF;
    CCAM_NEGRST;  ///set negative MRST polarity
    CCAM_MRST_ON;
    CCAM_TRIG_INT;
    CCAM_EXTERNALTS_EN; // Maybe use default as enabled - yes, it will not be active if not available
    udelay (100); // apply clock before removing MRS
    // first trying MT9P001 that does not need converter
    // try multisensor here (before removing MRST)
    if (thispars->pars[P_SENSOR]==0) multisensor_pgm_detectsensor (sensor_port, sensor,  thispars, prevpars, frame16);  // multisensor
    if (thispars->pars[P_SENSOR]==0) {
Andrey Filippov's avatar
Andrey Filippov committed
506
        dev_dbg(g_dev_ptr,"removing MRST from the sensor\n");
Andrey Filippov's avatar
Andrey Filippov committed
507 508 509 510
        CCAM_MRST_OFF;
    }
    if (thispars->pars[P_SENSOR]==0) {
        mt9x001_pgm_detectsensor(sensor_port, sensor,  thispars, prevpars, frame16);  // try Micron 5.0 Mpixel - should return sensor type
Andrey Filippov's avatar
Andrey Filippov committed
511
        dev_dbg(g_dev_ptr,"trying MT9P001\n");
Andrey Filippov's avatar
Andrey Filippov committed
512 513
    }
    // temporary - disabling old sensors
514 515
#define ENABLE_OLD_SENSORS 1
#ifdef ENABLE_OLD_SENSORS
Andrey Filippov's avatar
Andrey Filippov committed
516
    if (thispars->pars[P_SENSOR]==0)  { // no - it is not MT9P001)
Andrey Filippov's avatar
Andrey Filippov committed
517
        dev_dbg(g_dev_ptr,"trying other MT9X001\n");
Andrey Filippov's avatar
Andrey Filippov committed
518 519 520 521 522 523
        CCAM_CNVEN_ON;
        //     CCAM_ARST_ON; ///MT9P001 expects ARST==0 (STANDBY) - done inside mt9x001.c
        // enable output for power converter signals
        // This should be done first!!!
        // printk ("Will Turn DC power for the sensor after 1 sec delay...\n");  udelay (1000000);
        // turning on DC-DC converter may cause system to reboot because of a power spike, so start slow
524
#ifdef NC353
525
        port_csp0_addr[X313_WA_DCDC] = 0x44; // 48 - enough, 41 - ok - was 0x61; //
Andrey Filippov's avatar
Andrey Filippov committed
526
        printk ("sensor power set low\n ");
Andrey Filippov's avatar
Andrey Filippov committed
527
        mdelay (10); // Wait voltage to come up (~10 ms)
Andrey Filippov's avatar
Andrey Filippov committed
528
        printk ("will set to 0x41\n");
Andrey Filippov's avatar
Andrey Filippov committed
529
        mdelay (10); // to find the problem
530
        port_csp0_addr[X313_WA_DCDC] = 0x41; // 
Andrey Filippov's avatar
Andrey Filippov committed
531
        printk ("will set to 0x30\n");
Andrey Filippov's avatar
Andrey Filippov committed
532
        mdelay (10); // to find the problem
533
        port_csp0_addr[X313_WA_DCDC] = 0x30; //
Andrey Filippov's avatar
Andrey Filippov committed
534
        printk ("will set to 0x28\n");
Andrey Filippov's avatar
Andrey Filippov committed
535
        mdelay (10); // to find the problem
536
        port_csp0_addr[X313_WA_DCDC] = 0x28; //
Andrey Filippov's avatar
Andrey Filippov committed
537
        printk ("will set to 0x24\n");
Andrey Filippov's avatar
Andrey Filippov committed
538
        mdelay (10); // to find the problem
539
        port_csp0_addr[X313_WA_DCDC] = 0x24; //
Andrey Filippov's avatar
Andrey Filippov committed
540
        printk ("will set to 0x22\n");
Andrey Filippov's avatar
Andrey Filippov committed
541
        mdelay (10); // to find the problem
542
        port_csp0_addr[X313_WA_DCDC] = 0x22; //
Andrey Filippov's avatar
Andrey Filippov committed
543
        mdelay (10); // to find the problem
544
        port_csp0_addr[X313_WA_DCDC] = 0x10; // now - full frequency (same as 0x21). Slow that down if the sensor clock is above 20MHz (i.e.0x22 for 40MHz)
Andrey Filippov's avatar
Andrey Filippov committed
545
        printk (".. full\n");
Andrey Filippov's avatar
Andrey Filippov committed
546 547 548 549
        mdelay (10); // Wait voltage to stabilize
        CCAM_POSRST;  //set positive MRST polarity (default)
        udelay (100); // apply clock before removing MRST
        CCAM_MRST_OFF;
550
#endif
Andrey Filippov's avatar
Andrey Filippov committed
551
    }
552
#ifdef CONFIG_ETRAX_ELPHEL_KAC1310
Andrey Filippov's avatar
Andrey Filippov committed
553
    if (thispars->pars[P_SENSOR]==0) kac1310_pgm_detectsensor(sensor,  thispars, prevpars, frame16);  // try KAC-1310 (does not exist anymore)
554 555
#endif
#ifdef CONFIG_ETRAX_ELPHEL_IBIS51300
Andrey Filippov's avatar
Andrey Filippov committed
556
    if (thispars->pars[P_SENSOR]==0) ibis1300_pgm_detectsensor(sensor,  thispars, prevpars, frame16); // try IBIS5-1300 (software dead)
557
#endif
Andrey Filippov's avatar
Andrey Filippov committed
558 559 560 561 562 563
    // invert MRST for other sensors
    if (thispars->pars[P_SENSOR]==0) {
        CCAM_NEGRST;  //set negative MRST polarity
        printk ("Inverted MRST\n");
        udelay (100);
    }
564
#ifdef CONFIG_ETRAX_ELPHEL_MT9X001
Andrey Filippov's avatar
Andrey Filippov committed
565
    if (thispars->pars[P_SENSOR]==0)  dev_dbg(g_dev_ptr,"trying MT9X001\n");
Andrey Filippov's avatar
Andrey Filippov committed
566
    if (thispars->pars[P_SENSOR]==0) mt9x001_pgm_detectsensor(sensor_port, sensor,  thispars, prevpars, frame16);  // try Micron 1.3/2.0/3.0 Mpixel
567 568
#endif
#ifdef CONFIG_ETRAX_ELPHEL_KAC1310
Andrey Filippov's avatar
Andrey Filippov committed
569
    if (thispars->pars[P_SENSOR]==0) kac5000_pgm_detectsensor(sensorsensor_port, sensor,  thispars, prevpars, frame16);  // try KAC-5000
570 571
#endif
#ifdef CONFIG_ETRAX_ELPHEL_ZR32112
Andrey Filippov's avatar
Andrey Filippov committed
572
    if (thispars->pars[P_SENSOR]==0) zr32112_pgm_detectsensor(sensorsensor_port, sensor,  thispars, prevpars, frame16); // try ZR32112
573 574
#endif
#ifdef CONFIG_ETRAX_ELPHEL_ZR32212
Andrey Filippov's avatar
Andrey Filippov committed
575
    if (thispars->pars[P_SENSOR]==0) zr32212_pgm_detectsensor(sensorsensor_port, sensor,  thispars, prevpars, frame16); // try ZR32212
576
#endif
577
#endif // ENABLE_OLD_SENSORS *************** temporary disabling other sensors ********************
Andrey Filippov's avatar
Andrey Filippov committed
578 579
    if (thispars->pars[P_SENSOR]==0) {
        sensor->sensorType=SENSOR_NONE;                 // to prevent from initializing again
Andrey Filippov's avatar
Andrey Filippov committed
580
        dev_dbg(g_dev_ptr,"No image sensor found\n");
Andrey Filippov's avatar
Andrey Filippov committed
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
    }
    setFramePar(sensor_port, thispars, P_SENSOR_WIDTH,   sensor->imageWidth);  // Maybe get rid of duplicates?
    setFramePar(sensor_port, thispars, P_SENSOR_HEIGHT,  sensor->imageHeight); // Maybe get rid of duplicates?
    if (sensor->i2c_period==0) sensor->i2c_period=2500;           // SCL period in ns, (standard i2c - 2500)
    qperiod=thispars->pars[P_I2C_QPERIOD];
    if (qperiod==0) qperiod=(sensor->i2c_period * (thispars->pars[P_CLK_FPGA]/1000))/4000000;
    setFramePar(sensor_port, thispars, P_I2C_QPERIOD | FRAMEPAIR_FORCE_NEWPROC,  qperiod); // force i2c
    i2cbytes=thispars->pars[P_I2C_BYTES];
    if (i2cbytes==0) i2cbytes=sensor->i2c_bytes;
    setFramePar(sensor_port, thispars, P_I2C_BYTES | FRAMEPAIR_FORCE_NEWPROC,  i2cbytes); // force i2c
    // restore/set sensor clock
    if ((was_sensor_freq < sensor->minClockFreq) || (was_sensor_freq > sensor->maxClockFreq)) was_sensor_freq=sensor->nomClockFreq;
    setFramePar(sensor_port, thispars, P_CLK_SENSOR | FRAMEPAIR_FORCE_NEWPROC,  was_sensor_freq); // will schedule clock/phase adjustment
    phase=thispars->pars[P_SENSOR_PHASE];
    // TODO: remove phase adjustment from here
    if (phase==0) {
        phase= 0x40000;
        setFramePar(sensor_port, thispars, P_SENSOR_PHASE | FRAMEPAIR_FORCE_NEWPROC,  phase); // will schedule clock/phase adjustment
    }
    setFramePar(sensor_port, thispars, P_IRQ_SMART | FRAMEPAIR_FORCE_NEWPROC,  3);        // smart IRQ mode programming (and enable interrupts)
    // NOTE: sensor detected - enabling camera interrupts here (actual interrupts will start later)
    // Here interrupts are disabled - with compressor_interrupts (0) earlier in this function)
    compressor_interrupts (1);
    return 0;
605
#endif
606
}
607 608 609 610 611 612 613 614 615 616 617 618 619
/** Reset and initialize sensor (all is done in sensor-specific functions)
 *  - resets sensor,
 *  - reads sensor registers,
 *  - schedules "secret" manufacturer's corrections to the registers (stops/re-enables hardware i2c)
 *  TODO: Make sure sequencer and hardware i2c are running when needed. */
int pgm_initsensor     (int sensor_port,               ///< sensor port number (0..3)
		struct sensor_t * sensor,      ///< sensor static parameters (capabilities)
		struct framepars_t * thispars, ///< sensor current parameters
		struct framepars_t * prevpars, ///< sensor previous parameters (not used here)
		int frame16)                   ///< 4-bit (hardware) frame number parameters should
									   ///< be applied to,  negative - ASAP
									   ///< @return always 0
{
620 621 622 623 624 625 626 627 628
   // NC393: Putting here some initialization that should later be moved away (Gamma window)
  x393_status_ctrl_t      status_ctrl =      {.d32=0};
  x393_gamma_ctl_t        gamma_ctl =        {.d32=0};
  x393_gamma_height01m1_t gamma_height01m1 = {.d32=0};
  x393_gamma_height2m1_t  gamma_height2m1 =  {.d32=0};
  x393_lens_height_m1_t   vign_hight0 =      {.d32=0};
  x393_lens_height_m1_t   vign_hight1 =      {.d32=0};
  x393_lens_height_m1_t   vign_hight2 =      {.d32=0};
  x393_sens_mode_t        sens_mode =        {.d32=0};
629
  x393_camsync_mode_t     camsync_mode =     {.d32=0};
630

Andrey Filippov's avatar
Andrey Filippov committed
631
  dev_dbg(g_dev_ptr,"{%d}  frame16=%d\n",sensor_port,frame16);
632
  MDP(DBGB_PSFN, sensor_port,"frame16=%d\n",frame16)
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
  status_ctrl.mode = 3; // mode auto
  set_x393_cmprs_status(status_ctrl, sensor_port);

  //Until multiple subchannels supported, use just 0
  gamma_height01m1.height0m1= 0xffff;
  gamma_height01m1.height1m1= 0;
  gamma_height2m1.height2m1 = 0;

  vign_hight0.height_m1 = 0xffff;
  vign_hight1.height_m1 = 0;
  vign_hight2.height_m1 = 0;

  // Enable gamma module to pass through
  gamma_ctl.en =        1;
  gamma_ctl.en_set =    1;
  gamma_ctl.repet =     1;
  gamma_ctl.repet_set = 1;

651 652 653 654
  X393_SEQ_SEND1 (sensor_port, frame16, x393_sens_gamma_ctrl, gamma_ctl);
  dev_dbg(g_dev_ptr,"{%d}  X393_SEQ_SEND1(0x%x,  0x%x, x393_sens_gamma_ctrl,  0x%x)\n",sensor_port, sensor_port, frame16, gamma_ctl.d32);
  MDP(DBGB_PADD, sensor_port,"X393_SEQ_SEND1(0x%x,  0x%x, x393_sens_gamma_ctrl,  0x%x)\n",sensor_port, frame16, gamma_ctl.d32)

655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
  X393_SEQ_SEND1 (sensor_port, frame16, x393_sens_gamma_height01m1, gamma_height01m1);
  dev_dbg(g_dev_ptr,"{%d}  X393_SEQ_SEND1(0x%x,  0x%x, x393_gamma_height01m1,  0x%x)\n",sensor_port, sensor_port, frame16, gamma_height01m1.d32);
  MDP(DBGB_PADD, sensor_port,"X393_SEQ_SEND1(0x%x,  0x%x, x393_gamma_height01m1,  0x%x)\n",sensor_port, frame16, gamma_height01m1.d32)
  X393_SEQ_SEND1 (sensor_port, frame16, x393_sens_gamma_height2m1, gamma_height2m1);
  dev_dbg(g_dev_ptr,"{%d}  X393_SEQ_SEND1(0x%x,  0x%x, x393_gamma_height2m1,  0x%x)\n",sensor_port, sensor_port, frame16, gamma_height2m1.d32);
  MDP(DBGB_PADD, sensor_port,"X393_SEQ_SEND1(0x%x,  0x%x, x393_gamma_height2m1,  0x%x)\n",sensor_port, frame16, gamma_height2m1.d32)

  X393_SEQ_SEND1 (sensor_port, frame16, x393_lens_height0_m1, vign_hight0);
  dev_dbg(g_dev_ptr,"{%d}  X393_SEQ_SEND1(0x%x,  0x%x, x393_lens_height0_m1,  0x%x)\n",sensor_port, sensor_port, frame16, vign_hight0.d32);
  MDP(DBGB_PADD, sensor_port,"X393_SEQ_SEND1(0x%x,  0x%x, x393_lens_height0_m1,  0x%x)\n",sensor_port, frame16, vign_hight0.d32)

  X393_SEQ_SEND1 (sensor_port, frame16, x393_lens_height1_m1, vign_hight1);
  dev_dbg(g_dev_ptr,"{%d}  X393_SEQ_SEND1(0x%x,  0x%x, x393_lens_height1_m1,  0x%x)\n",sensor_port, sensor_port, frame16, vign_hight1.d32);
  MDP(DBGB_PADD, sensor_port,"X393_SEQ_SEND1(0x%x,  0x%x, x393_lens_height1_m1,  0x%x)\n",sensor_port, frame16, vign_hight1.d32)

  X393_SEQ_SEND1 (sensor_port, frame16, x393_lens_height2_m1, vign_hight2);
  dev_dbg(g_dev_ptr,"{%d}  X393_SEQ_SEND1(0x%x,  0x%x, x393_lens_height2_m1,  0x%x)\n",sensor_port, sensor_port, frame16, vign_hight2.d32);
  MDP(DBGB_PADD, sensor_port,"X393_SEQ_SEND1(0x%x,  0x%x, x393_lens_height2_m1,  0x%x)\n",sensor_port, frame16, vign_hight2.d32)

674
  // TODO NC393: Setup for all used sub-channels (or is it in multisensor?)
675 676 677 678 679 680 681 682 683 684 685 686
  sens_mode.hist_en =    1; // just first subchannel
  sens_mode.hist_nrst =  1; // just first subchannel
  sens_mode.hist_set =   1;
  sens_mode.chn_en =     1;
  sens_mode.chn_en_set = 1;

  X393_SEQ_SEND1 (sensor_port, frame16, x393_sens_mode, sens_mode);
  dev_dbg(g_dev_ptr,"{%d}  X393_SEQ_SEND1(0x%x,  0x%x, x393_sens_mode,  0x%x)\n",
          sensor_port, sensor_port, frame16, sens_mode.d32);
  MDP(DBGB_PADD, sensor_port,"X393_SEQ_SEND1(0x%x,  0x%x, x393_sens_mode,  0x%x)\n",
          sensor_port, frame16, sens_mode.d32)

687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
/*
        self.set_camsync_period  (0) # reset circuitry
        self.X393_gpio.set_gpio_ports (port_a = True)
        self.set_camsync_mode (
                               en = True,
                               en_snd = True,
                               en_ts_external = external_timestamp,
                               triggered_mode = trigger_mode,
                               master_chn =     0,
                               chn_en = sensor_mask)

  void                         x393_camsync_mode                   (x393_camsync_mode_t d);                         // CAMSYNC mode

// CAMSYNC mode

typedef union {
    struct {
          u32              en: 1; // [    0] (1) Enable CAMSYNC module
          u32          en_set: 1; // [    1] (1) Set 'en' bit
          u32          en_snd: 1; // [    2] (1) Enable sending timestamps (valid with 'en_snd_set')
          u32      en_snd_set: 1; // [    3] (0) Set 'en_snd'
          u32             ext: 1; // [    4] (1) Use external (received) timestamps, if available. O - use local timestamps
          u32         ext_set: 1; // [    5] (0) Set 'ext'
          u32            trig: 1; // [    6] (1) Sensor triggered mode (0 - free running sensor)
          u32        trig_set: 1; // [    7] (0) Set 'trig'
          u32      master_chn: 2; // [ 9: 8] (0) master sensor channel (zero delay in internal trigger mode, delay used for flash output)
          u32  master_chn_set: 1; // [   10] (0) Set 'master_chn'
          u32         ts_chns: 4; // [14:11] (1) Channels to generate timestmp messages (bit mask)
          u32     ts_chns_set: 4; // [18:15] (0) Sets for 'ts_chns' (each bit controls corresponding 'ts_chns' bit)
          u32                :13;
    };
    struct {
          u32             d32:32; // [31: 0] (0) cast to u32
    };
} x393_camsync_mode_t;
           self.set_camsync_mode (
                               en = True,
                               en_snd = True,
                               en_ts_external = False,
                               triggered_mode = False,
                               master_chn =     0,
                               chn_en = sensor_mask)
729

730 731 732 733
 */

  camsync_mode.en =       1;
  camsync_mode.en_set =   1;
Andrey Filippov's avatar
Andrey Filippov committed
734
  camsync_mode.ext =      1; // 0;
735 736 737 738 739 740 741
  camsync_mode.ext_set =  1;
  camsync_mode.trig =     0;
  camsync_mode.trig_set = 1;

  x393_camsync_mode                   (camsync_mode);  // immediate mode, bypass sequencer CAMSYNC mode
                                                       // (TODO NC393: Make it possible to synchronize writes (through sequencer)
  set_x393_camsync_trig_period        (0);  // reset circuitry (immediate mode)
742 743
  if (frame16 >= 0) return -1; // should be ASAP
//TODO: seems nothing to do here - all in the sensor-specific function:
744
//Adding setup compressor report status mode - maybe move elsethere? Needed for comprfessor frame reporting, has to be done just once
745 746 747 748
  return 0;
}


Andrey Filippov's avatar
Andrey Filippov committed
749 750
/** Restore image size, decimation,... after sensor reset or set them according to sensor capabilities if none were specified
 TODO: NC393 add default P_SENSOR_IFACE_TIM0..3 for parallel/serial? */
751 752 753 754 755 756 757
int pgm_afterinit      (int sensor_port,               ///< sensor port number (0..3)
						struct sensor_t * sensor,      ///< sensor static parameters (capabilities)
						struct framepars_t * thispars, ///< sensor current parameters
						struct framepars_t * prevpars, ///< sensor previous parameters (not used here)
						int frame16)                   ///< 4-bit (hardware) frame number parameters should
													   ///< be applied to,  negative - ASAP
													   ///< @return always 0
758

759
{
760 761
    struct frameparspair_t pars_to_update[24]; // 20 needed, increase if more entries will be added
    int nupdate=0;
762
    int woi_width, woi_height;
Andrey Filippov's avatar
Andrey Filippov committed
763
    dev_dbg(g_dev_ptr,"{%d}  frame16=%d\n",sensor_port,frame16);
764 765
    MDP(DBGB_PSFN, sensor_port,"frame16=%d\n",frame16)

766 767 768 769
    // If this is a multisensor camera, update composite sensor dimensions (will trigger other related changes)
    // For single sensors sensor size is updated only after initialization, with composite it needs to be updated after vertical gap  or number of active sesnors is changed
    //  if (GLOBALPARS(G_SENS_AVAIL) ) multisensor_pgm_afterinit0 (sensor, thispars, prevpars,frame16);
    // Setup WOI. If size is zero - use maximal that sensor can, in non-zero - just refresh so appropriate actions will be scheduled on chnange
770 771
    woi_width=thispars->pars[P_WOI_WIDTH];
    woi_height=thispars->pars[P_WOI_HEIGHT];
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
    if ((woi_width == 0) || (woi_height == 0)) { ///were zeroes
        woi_width= thispars->pars[P_SENSOR_WIDTH];
        woi_height=thispars->pars[P_SENSOR_HEIGHT];
    }
    SETFRAMEPARS_SET(P_WOI_WIDTH | FRAMEPAIR_FORCE_NEW, woi_width);
    SETFRAMEPARS_SET(P_WOI_HEIGHT | FRAMEPAIR_FORCE_NEW, woi_height);
    SETFRAMEPARS_UPDATE(P_WOI_LEFT | FRAMEPAIR_FORCE_NEW);
    SETFRAMEPARS_UPDATE(P_WOI_TOP | FRAMEPAIR_FORCE_NEW);
    SETFRAMEPARS_UPDATE(P_FLIPH | FRAMEPAIR_FORCE_NEW); // FLIPH==0 will use sensor board default flip
    SETFRAMEPARS_UPDATE(P_FLIPV | FRAMEPAIR_FORCE_NEW); // FLIPV==0 will use sensor board default flip

    SETFRAMEPARS_UPDATE_SET(P_HISTWND_RWIDTH | FRAMEPAIR_FORCE_NEW, 0x8000);  // histogram 50% width (0x10000 - 100%)
    SETFRAMEPARS_UPDATE_SET(P_HISTWND_RHEIGHT | FRAMEPAIR_FORCE_NEW, 0x8000); // histogram 50% height
    SETFRAMEPARS_UPDATE_SET(P_HISTWND_RLEFT | FRAMEPAIR_FORCE_NEW, 0x8000);   // histogram 50% left (middle)
    SETFRAMEPARS_UPDATE_SET(P_HISTWND_RTOP | FRAMEPAIR_FORCE_NEW, 0x8000);    // histogram 50% top (middle)

    SETFRAMEPARS_UPDATE_SET(P_DCM_HOR | FRAMEPAIR_FORCE_NEW,  1);
    SETFRAMEPARS_UPDATE_SET(P_DCM_VERT | FRAMEPAIR_FORCE_NEW, 1);
    SETFRAMEPARS_UPDATE_SET(P_BIN_HOR | FRAMEPAIR_FORCE_NEW,  1);
    SETFRAMEPARS_UPDATE_SET(P_BIN_VERT | FRAMEPAIR_FORCE_NEW, 1);
    // Set analog gains to 1.0 if not set otherwise
    // FIXME: Without those 3 lines it is not initialaized  (or immediately reset) from the parameters in autocampars.xml. GAING=0x10000, all the rest - 0
    /*
795
 if (!(GLOBALPARS(G_DEBUG) & (1 <<28))) { // debugging here ! ***********************************
796 797 798 799 800
    SETFRAMEPARS_UPDATE_SET(P_GAINR | FRAMEPAIR_FORCE_NEW, 0x20000); ///gain ==1.0
    SETFRAMEPARS_UPDATE_SET(P_GAING | FRAMEPAIR_FORCE_NEW, 0x20000); ///gain ==1.0
    SETFRAMEPARS_UPDATE_SET(P_GAINB | FRAMEPAIR_FORCE_NEW, 0x20000); ///gain ==1.0
    SETFRAMEPARS_UPDATE_SET(P_GAINGB | FRAMEPAIR_FORCE_NEW,0x20000); ///gain ==1.0
  }
801 802 803 804 805 806 807 808 809 810 811
     */
    SETFRAMEPARS_UPDATE(P_BAYER | FRAMEPAIR_FORCE_NEW);

    // Exposure use non-zero P_EXPOS, then P_VEXPOS, then P_EXPOS=10ms
    if (thispars->pars[P_EXPOS]) {
        SETFRAMEPARS_UPDATE(P_EXPOS | FRAMEPAIR_FORCE_NEW);
    } else if (thispars->pars[P_VEXPOS]) {
        SETFRAMEPARS_UPDATE(P_VEXPOS | FRAMEPAIR_FORCE_NEW);
    } else {
        SETFRAMEPARS_SET(P_EXPOS | FRAMEPAIR_FORCE_NEW, 10000); // set exposure to 0.01 sec
    }
Andrey Filippov's avatar
Andrey Filippov committed
812
    SETFRAMEPARS_UPDATE(P_TRIG | FRAMEPAIR_FORCE_NEW); // set trigger mode (or should it always be internal after init?)
813 814 815 816
    // something else to add? NOTE: Only sensor parameters, erased when it is reset - other parameters should not chnage here
    // NOTE: increase pars_to_update[24] size if needed
    if (nupdate)  setFramePars(sensor_port, thispars, nupdate, pars_to_update);  // save changes, schedule functions
    return 0;
817 818
}

819 820
/** Program sensor clock and phase */
int pgm_sensorphase    (int sensor_port,               ///< sensor port number (0..3)
821 822 823 824 825 826
        struct sensor_t * sensor,      ///< sensor static parameters (capabilities)
        struct framepars_t * thispars, ///< sensor current parameters
        struct framepars_t * prevpars, ///< sensor previous parameters (not used here)
        int frame16)                   ///< 4-bit (hardware) frame number parameters should
///< be applied to,  negative - ASAP
///< @return always 0
827 828

{
Andrey Filippov's avatar
Andrey Filippov committed
829
#ifndef NC353
Andrey Filippov's avatar
Andrey Filippov committed
830
    x393_sensio_ctl_t  sensio_ctl = {.d32=0};
Andrey Filippov's avatar
Andrey Filippov committed
831 832 833 834 835 836
    x393_sensio_tim0_t sensio_tim0 = {.d32=0};
    x393_sensio_tim1_t sensio_tim1 = {.d32=0};
    x393_sensio_tim2_t sensio_tim2 = {.d32=0};
    x393_sensio_tim3_t sensio_tim3 = {.d32=0};
// TODO: Temporary for NC393 - just applying  SENSOR_IFACE_TIM0 - SENSOR_IFACE_TIM3 to FPGA, no calculations
// Actual functionality should be moved to separate modules as they are different for parallel and hispi (may be more in the future)
837
    MDP(DBGB_PSFN, sensor_port,"frame16=%d\n",frame16)
Andrey Filippov's avatar
Andrey Filippov committed
838 839 840 841
    if (FRAMEPAR_MODIFIED(P_SENSOR_IFACE_TIM0)) {
        sensio_tim0.d32 = thispars->pars[P_SENSOR_IFACE_TIM0];
//        X393_SEQ_SEND1 (sensor_port, frame16, x393_sensio_tim0, sensio_tim0);
        set_x393_sensio_tim0  (sensio_tim0, sensor_port); // write directly, sequencer may be not operational
Andrey Filippov's avatar
Andrey Filippov committed
842
        sensio_ctl.set_dly = 1;
Andrey Filippov's avatar
Andrey Filippov committed
843
        dev_dbg(g_dev_ptr,"{%d}  X393_SEQ_SEND1(0x%x,  0x%x, x393_sensio_tim0,  0x%x)\n",sensor_port, sensor_port, frame16, sensio_tim0.d32);
844
        MDP(DBGB_PADD, sensor_port,"X393_SEQ_SEND1(0x%x,  0x%x, x393_sensio_tim0,  0x%x)\n", sensor_port, frame16, sensio_tim0.d32)
Andrey Filippov's avatar
Andrey Filippov committed
845 846 847 848 849
    }
    if (FRAMEPAR_MODIFIED(P_SENSOR_IFACE_TIM1)) {
        sensio_tim1.d32 = thispars->pars[P_SENSOR_IFACE_TIM1];
//        X393_SEQ_SEND1 (sensor_port, frame16, x393_sensio_tim1, sensio_tim1);
        set_x393_sensio_tim1  (sensio_tim1, sensor_port); // write directly, sequencer may be not operational
Andrey Filippov's avatar
Andrey Filippov committed
850
        sensio_ctl.set_dly = 1;
Andrey Filippov's avatar
Andrey Filippov committed
851
        dev_dbg(g_dev_ptr,"{%d}  X393_SEQ_SEND1(0x%x,  0x%x, x393_sensio_tim1,  0x%x)\n",sensor_port, sensor_port, frame16, sensio_tim1 .d32);
852
        MDP(DBGB_PADD, sensor_port,"X393_SEQ_SEND1(0x%x,  0x%x, x393_sensio_tim1,  0x%x)\n", sensor_port, frame16, sensio_tim1 .d32)
Andrey Filippov's avatar
Andrey Filippov committed
853 854 855 856 857
    }
    if (FRAMEPAR_MODIFIED(P_SENSOR_IFACE_TIM2)) {
        sensio_tim2.d32 = thispars->pars[P_SENSOR_IFACE_TIM2];
//        X393_SEQ_SEND1 (sensor_port, frame16, x393_sensio_tim2, sensio_tim2);
        set_x393_sensio_tim2  (sensio_tim2, sensor_port); // write directly, sequencer may be not operational
Andrey Filippov's avatar
Andrey Filippov committed
858
        sensio_ctl.set_dly = 1;
Andrey Filippov's avatar
Andrey Filippov committed
859
        dev_dbg(g_dev_ptr,"{%d}  X393_SEQ_SEND1(0x%x,  0x%x, x393_sensio_tim2,  0x%x)\n",sensor_port, sensor_port, frame16, sensio_tim2.d32);
860
        MDP(DBGB_PADD, sensor_port,"X393_SEQ_SEND1(0x%x,  0x%x, x393_sensio_tim2,  0x%x)\n",sensor_port, frame16, sensio_tim2.d32)
Andrey Filippov's avatar
Andrey Filippov committed
861 862 863 864 865
    }
    if (FRAMEPAR_MODIFIED(P_SENSOR_IFACE_TIM3)) {
        sensio_tim3.d32 = thispars->pars[P_SENSOR_IFACE_TIM3];
//        X393_SEQ_SEND1 (sensor_port, frame16, x393_sensio_tim3, sensio_tim3);
        set_x393_sensio_tim3  (sensio_tim3, sensor_port); // write directly, sequencer may be not operational
Andrey Filippov's avatar
Andrey Filippov committed
866
        sensio_ctl.set_dly = 1;
Andrey Filippov's avatar
Andrey Filippov committed
867
        dev_dbg(g_dev_ptr,"{%d}  X393_SEQ_SEND1(0x%x,  0x%x, x393_sensio_tim3,  0x%x)\n",sensor_port, sensor_port, frame16, sensio_tim3.d32);
868
        MDP(DBGB_PADD, sensor_port,"X393_SEQ_SEND1(0x%x,  0x%x, x393_sensio_tim3,  0x%x)\n", sensor_port, frame16, sensio_tim3.d32)
Andrey Filippov's avatar
Andrey Filippov committed
869 870
    }

871
    if (get_port_interface(sensor_port) == PARALLEL12){
Andrey Filippov's avatar
Andrey Filippov committed
872 873 874 875
        if (FRAMEPAR_MODIFIED(P_SENSOR_PHASE)) { // for parallel sensor it means quadrants:  90-degree shifts for data [1:0], hact [3:2] and vact [5:4]
            sensio_ctl.quadrants = thispars->pars[P_SENSOR_PHASE] & 0x3f;
            sensio_ctl.quadrants_set = 1;
        }
876
        if (sensio_ctl.d32) {
Andrey Filippov's avatar
Andrey Filippov committed
877
            x393_sensio_ctrl(sensio_ctl, sensor_port);
878 879 880
            dev_dbg(g_dev_ptr,"{%d} x393_sensio_ctrl(0x%08x, %d))\n",sensor_port, sensio_ctl.d32, sensor_port);
            MDP(DBGB_PADD, sensor_port,"x393_sensio_ctrl(0x%08x, %d))\n", sensio_ctl.d32, sensor_port)
        }
Andrey Filippov's avatar
Andrey Filippov committed
881 882 883 884

    } else {
        /* TODO 393: Add HISPI code */
    }
Andrey Filippov's avatar
Andrey Filippov committed
885 886 887
    return 0;

#else
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
    struct frameparspair_t pars_to_update[5]; // ??? needed, increase if more entries will be added
    int nupdate=0;
    int i;
    int old_sensor_phase;
    int old_sensor_phase90;
    int sensor_phase;
    int sensor_phase90;
    int diff_phase;
    int diff_phase90;
    int new_freq= thispars->pars[P_CLK_SENSOR];
    int thisPhase=thispars->pars[P_SENSOR_PHASE];
    int was_sensor_freq = new_freq; // bypassing for nc393
    int  hact_shift;
    long * cableDelay;
    long * FPGADelay;
    int clk_period;  // period in ps
    int px_delay;
    int px_delay90;
    uint64_t ull_result = 1000000000000LL;

Andrey Filippov's avatar
Andrey Filippov committed
908
    dev_dbg(g_dev_ptr,"%s  frame16=%d\n",__func__,frame16);
909 910 911 912 913 914 915 916
    if (frame16 >= 0) return -1; // can only work in ASAP mode
    //Can not change sensor frequency
    int was_sensor_freq=getClockFreq(1); // using clock driver data, not thispars
    if (unlikely(new_freq > sensor->maxClockFreq)) {
        new_freq= sensor->maxClockFreq;
        SETFRAMEPARS_SET(P_CLK_SENSOR,  new_freq);
    }
    if ((new_freq != was_sensor_freq) || (thisPhase & 0x40000)) { // 0x40000 reprogram clock even if it did not change
Andrey Filippov's avatar
Andrey Filippov committed
917
        if (unlikely(setClockFreq(1, thispars->pars[P_CLK_SENSOR])<0)) { // if failed to setup frequency - use the old one
918 919 920 921 922 923 924 925 926 927 928
            new_freq=was_sensor_freq;
            setClockFreq(1, was_sensor_freq);
            SETFRAMEPARS_SET(P_CLK_SENSOR,  new_freq);
        }
        X3X3_RSTSENSDCM; // Make Xilinx Spartan DCM happy (it does not like changing input clock)
        X3X3_SENSDCM_CLK2X_RESET; // reset pclk2x DCM also
        if (sensor->needReset & SENSOR_NEED_RESET_CLK) schedule_this_pgm_func(sensor_port, thispars, onchange_initsensor);
        // set HACT PHASE here - 90 deg. increment - seems like a bug in MT9P001 sensors - horisontal (and vert.) sync has different phase than data
        // Update (program) hact_shift only when the frequency is changed, not when just the phase is
        // adjustment range is 270 early to 360 late
        hact_shift= 0.004f * (((int)sensor->hact_delay)/(1000000000.0f/new_freq)) + 4.5f;
Andrey Filippov's avatar
Andrey Filippov committed
929
        MDF16(printk ("hact_shift=%d-4\n",hact_shift));
930
        hact_shift-=4;
Andrey Filippov's avatar
Andrey Filippov committed
931
        MDF16(printk ("hact_shift=%d\n",hact_shift));
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
        if (hact_shift>4) hact_shift=4;
        else if (hact_shift<-3) hact_shift=-3;
        X3X3_SENSDCM_HACT_ZERO;
        if      (hact_shift>0) for (i=0; i <  hact_shift; i++) {
            X3X3_SENSDCM_HACT_LATE90;
        }
        else if (hact_shift<0) for (i=0; i < -hact_shift; i++) {
            X3X3_SENSDCM_HACT_EARLY90;
        }
        // Calculate and set sensor phase (only initially and when clock frequency is chnaged)
        cableDelay= (long *) &GLOBALPARS(sensor_port, G_CABLE_TIM );
        FPGADelay=  (long *) &GLOBALPARS(sensor_port, G_FPGA_TIM0 );
//        clk_period= 1000000000000.0f/new_freq;  // period in ps
//        clk_period= 1.0E12f/new_freq;  // period in ps
        do_div(ull_result,new_freq);
        clk_period= ull_result;

Andrey Filippov's avatar
Andrey Filippov committed
949
        MDF16(printk ("cableDelay=%ld, FPGADelay=%ld, clk_period=%d\n",cableDelay[0], FPGADelay[0], clk_period));
950
        px_delay=-(clk_period/2 - FPGADelay[0]- cableDelay[0] - ((int) sensor->sensorDelay)) ;
Andrey Filippov's avatar
Andrey Filippov committed
951
        MDF16(printk ("px_delay=%d\n",px_delay));
952 953
        px_delay90=(4*px_delay+clk_period/2)/clk_period;
        px_delay -= (px_delay90*clk_period)/4; // -clk_period/8<= now px_delay <= +clk_period/8
Andrey Filippov's avatar
Andrey Filippov committed
954
        MDF16(printk ("px_delay=%d, px_delay90=%d\n",px_delay,px_delay90));
955 956 957
        px_delay/= FPGA_DCM_STEP; // in DCM steps
        thisPhase= (px_delay & 0xffff) | ((px_delay90 & 3) <<16) | 0x80000;
    }
958 959


960 961 962 963 964 965 966 967 968 969 970 971 972 973
    if (thisPhase!=prevpars->pars[P_SENSOR_PHASE]) {
        old_sensor_phase= prevpars->pars[P_SENSOR_PHASE] & 0xffff;  if (old_sensor_phase>=0x8000) old_sensor_phase-=0x10000; // make it signed
        old_sensor_phase90= (prevpars->pars[P_SENSOR_PHASE]>>16)&3;
        if (thisPhase & 0x80000) {
            X3X3_RSTSENSDCM; // start from zero phase
            old_sensor_phase=0;
            old_sensor_phase90=0;
        }
        sensor_phase90=(thisPhase>>16)&3;
        sensor_phase=   thisPhase & 0xffff;  if (sensor_phase>=0x8000) sensor_phase-=0x10000; // make it signed
        diff_phase=  sensor_phase-  old_sensor_phase;
        diff_phase90=sensor_phase90-old_sensor_phase90;
        if (diff_phase90>2)diff_phase90-=4;
        else if (diff_phase90<-1)diff_phase90+=4;
Andrey Filippov's avatar
Andrey Filippov committed
974 975 976
        dev_dbg(g_dev_ptr,"%s old_sensor_phase=0x%x old_sensor_phase90=0x%x\n",__func__, old_sensor_phase, old_sensor_phase90 );
        dev_dbg(g_dev_ptr,"%s sensor_phase=0x%x sensor_phase90=0x%x\n",__func__, sensor_phase, sensor_phase90 );
        dev_dbg(g_dev_ptr,"%s diff_phase=0x%x diff_phase90=0x%x\n",__func__, diff_phase, diff_phase90 );
977 978 979 980 981 982
        if      (diff_phase > 0) for (i=diff_phase; i > 0; i--) {X3X3_SENSDCM_INC ; udelay(1); }
        else if (diff_phase < 0) for (i=diff_phase; i < 0; i++) {X3X3_SENSDCM_DEC ; udelay(1); }
        if      (diff_phase90 > 0) for (i=diff_phase90; i > 0; i--) {X3X3_SENSDCM_INC90 ; udelay(1); }
        else if (diff_phase90 < 0) for (i=diff_phase90; i < 0; i++) {X3X3_SENSDCM_DEC90 ; udelay(1); }
        SETFRAMEPARS_SET(P_SENSOR_PHASE,  thisPhase & 0x3ffff);
    }
983

984 985
    if (nupdate)  setFramePars(sensor_port, thispars, nupdate, pars_to_update);  // save changes, schedule functions
    return 0;
Andrey Filippov's avatar
Andrey Filippov committed
986
#endif
987 988
}

989 990 991 992 993 994 995 996 997
/** Program sensor exposure - nothing to be done here, all sensor-specific */
int pgm_exposure   (int sensor_port,               ///< sensor port number (0..3)
					struct sensor_t * sensor,      ///< sensor static parameters (capabilities)
					struct framepars_t * thispars, ///< sensor current parameters
					struct framepars_t * prevpars, ///< sensor previous parameters (not used here)
					int frame16)                   ///< 4-bit (hardware) frame number parameters should
												   ///< be applied to,  negative - ASAP
												   ///< @return always 0
{
Andrey Filippov's avatar
Andrey Filippov committed
998
    dev_dbg(g_dev_ptr,"{%d}  frame16=%d\n",sensor_port,frame16);
999
    MDP(DBGB_PSFN, sensor_port,"frame16=%d\n",frame16)
1000
    return 0;
1001 1002
}

1003 1004 1005 1006 1007 1008 1009 1010 1011
/** Program i2c bytes/speed (may be per-frame?) 393: remove*/
int pgm_i2c        (int sensor_port,               ///< sensor port number (0..3)
					struct sensor_t * sensor,      ///< sensor static parameters (capabilities)
					struct framepars_t * thispars, ///< sensor current parameters
					struct framepars_t * prevpars, ///< sensor previous parameters (not used here)
					int frame16)                   ///< 4-bit (hardware) frame number parameters should
												   ///< be applied to,  negative - ASAP
												   ///< @return always 0
{
Andrey Filippov's avatar
Andrey Filippov committed
1012
    dev_dbg(g_dev_ptr,"{%d}  frame16=%d\n",sensor_port,frame16);
1013
    MDP(DBGB_PSFN, sensor_port,"frame16=%d (do nothing here?)\n",frame16)
1014
    if (frame16 >= PARS_FRAMES) return -1; // wrong frame
1015
#ifdef NC353
1016 1017 1018
    int fpga_addr = frame16;
    X3X3_SEQ_SEND1(fpga_addr,   X313_I2C_CMD,  X3X3_SET_I2C_BYTES(thispars->pars[P_I2C_BYTES]+1) |
            X3X3_SET_I2C_DLY  (thispars->pars[P_I2C_QPERIOD]));
1019
#endif
Andrey Filippov's avatar
Andrey Filippov committed
1020
//dev_dbg(g_dev_ptr,"%s   X3X3_SEQ_SEND1(0x%x,0x%x, 0x%x)\n",__func__, frame16,  (int) X313_I2C_CMD, (int) (X3X3_SET_I2C_BYTES(thispars->pars[P_I2C_BYTES]+1) | X3X3_SET_I2C_DLY  (thispars->pars[P_I2C_QPERIOD]))  );
1021
return 0;
1022 1023
}

1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
/** Program sensor WOI and mirroring
 *
 * As different sensors may produce "bad frames" for differnt WOI changes (i.e. MT9P001 seems to do fine with FLIP, but not WOI_WIDTH)
 * pgm_window and pgm_window_safe will do the same - they will just be called with different latencies and with compressor stopped) */
int pgm_window     (int sensor_port,               ///< sensor port number (0..3)
					struct sensor_t * sensor,      ///< sensor static parameters (capabilities)
					struct framepars_t * thispars, ///< sensor current parameters
					struct framepars_t * prevpars, ///< sensor previous parameters (not used here)
					int frame16)                   ///< 4-bit (hardware) frame number parameters should
												   ///< be applied to,  negative - ASAP
												   ///< @return always 0

{
Andrey Filippov's avatar
Andrey Filippov committed
1037
    dev_dbg(g_dev_ptr,"{%d}  frame16=%d\n",sensor_port,frame16);
1038
    MDP(DBGB_PSFN, sensor_port,"frame16=%d\n",frame16)
1039
    return pgm_window_common (sensor_port, sensor,  thispars, prevpars, frame16);
1040
}
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051

/** Program sensor WOI and mirroring, safe mode. Does the same as pgm_window, at least not sensor-specific */
int pgm_window_safe (int sensor_port,               ///< sensor port number (0..3)
					 struct sensor_t * sensor,      ///< sensor static parameters (capabilities)
					 struct framepars_t * thispars, ///< sensor current parameters
					 struct framepars_t * prevpars, ///< sensor previous parameters (not used here)
					 int frame16)                   ///< 4-bit (hardware) frame number parameters should
												    ///< be applied to,  negative - ASAP
												    ///< @return always 0

{
Andrey Filippov's avatar
Andrey Filippov committed
1052
    dev_dbg(g_dev_ptr,"{%d}  frame16=%d\n",sensor_port,frame16);
1053
    MDP(DBGB_PSFN, sensor_port,"frame16=%d\n",frame16)
1054
    return pgm_window_common (sensor_port, sensor,  thispars, prevpars, frame16);
1055
}
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065

//** Common (not sensor-specific) part of processing WOI parameters*/
int pgm_window_common  (int sensor_port,               ///< sensor port number (0..3)
						struct sensor_t * sensor,      ///< sensor static parameters (capabilities)
						struct framepars_t * thispars, ///< sensor current parameters
						struct framepars_t * prevpars, ///< sensor previous parameters (not used here)
						int frame16)                   ///< 4-bit (hardware) frame number parameters should
													   ///< be applied to,  negative - ASAP
													   ///< @return always 0
{
1066 1067 1068 1069 1070
    int dv,dh,bv,bh,width,height,timestamp_len,oversize,pfh,pf_stripes,ah, left,top,is_color;
    int sensor_width;
    int sensor_height;
    struct frameparspair_t pars_to_update[18]; // 15 needed, increase if more entries will be added
    int nupdate=0;
Andrey Filippov's avatar
Andrey Filippov committed
1071 1072 1073
    int clearHeight;
    dev_dbg(g_dev_ptr,"{%d}  frame16=%d\n",            sensor_port,frame16);
    dev_dbg(g_dev_ptr,"{%d} thispars->pars[P_WOI_HEIGHT]=%lx thispars->pars[P_WOI_WIDTH]=%lx\n", sensor_port,thispars->pars[P_WOI_HEIGHT], thispars->pars[P_WOI_WIDTH]);
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
    //  if (GLOBALPARS(G_SENS_AVAIL) ) multisensor_pgm_window_common0 (sensor, thispars, prevpars, frame16);

    sensor_width= thispars->pars[P_SENSOR_WIDTH];
    sensor_height=thispars->pars[P_SENSOR_HEIGHT];
    oversize=thispars->pars[P_OVERSIZE];
    is_color=1;

    switch (thispars->pars[P_COLOR] & 0x0f){
    case COLORMODE_MONO6:
    case COLORMODE_MONO4:
        is_color=0;
1085
    }
1086 1087 1088 1089 1090
    // flips changed?
    if (FRAMEPAR_MODIFIED(P_FLIPH)) {
        if (unlikely((thispars->pars[P_FLIPH] & sensor->flips & 1)!=thispars->pars[P_FLIPH])) { // remove unsupoported flips
            SETFRAMEPARS_SET(P_FLIPH, (thispars->pars[P_FLIPH] & sensor->flips & 1));
        }
1091
    }
1092 1093 1094 1095 1096 1097 1098
    if (FRAMEPAR_MODIFIED(P_FLIPV)) {
        if (unlikely((thispars->pars[P_FLIPV] & (sensor->flips>>1) & 1)!=thispars->pars[P_FLIPV])) { // remove unsupoported flips
            SETFRAMEPARS_SET(P_FLIPV, (thispars->pars[P_FLIPV] & (sensor->flips >> 1 ) & 1));
        }
    }
    // dh (decimation changed)?
    dh = thispars->pars[P_DCM_HOR];
1099
    dh = dh?dh:1;
1100 1101 1102 1103 1104 1105 1106
    if (FRAMEPAR_MODIFIED(P_DCM_HOR)) {
        if (dh<1) dh=1; else if (dh>32) dh=32;
        while ((dh>1) && !(sensor->dcmHor  & (1 << (dh-1)))) dh--; // adjust decimation to maximal supported (if requested is not supported)
        if (unlikely(dh!=thispars->pars[P_DCM_HOR])) SETFRAMEPARS_SET(P_DCM_HOR, dh);
    }
    // dv (decimation changed)?
    dv = thispars->pars[P_DCM_VERT];
1107
    dv = dv?dv:1;
1108 1109 1110 1111 1112 1113 1114
    if (FRAMEPAR_MODIFIED(P_DCM_VERT)) {
        if (dv<1) dv=1; else if (dv>32) dv=32;
        while ((dv>1) && !(sensor->dcmVert  & (1 << (dv-1)))) dv--; // adjust decimation to maximal supported (if requested is not supported)
        if (unlikely(dv!=thispars->pars[P_DCM_HOR])) SETFRAMEPARS_SET(P_DCM_VERT, dv);
    }
    // bh (binning changed)?
    bh = thispars->pars[P_BIN_HOR];
1115
    dv = dv?dv:1;
1116 1117 1118 1119 1120 1121 1122
    if (FRAMEPAR_MODIFIED(P_BIN_HOR)) {
        if (bh<1) bh=1; else if (bh>dh) bh=dh;
        while ((bh>1) && !(sensor->binHor  & (1 << (bh-1)))) bh--; // adjust binning to maximal supported (if requested is not supported)
        if (unlikely(bh!=thispars->pars[P_BIN_HOR])) SETFRAMEPARS_SET(P_DCM_HOR, bh);
    }
    // bv (binning changed)?
    bv = thispars->pars[P_BIN_VERT];
1123
    bv = bv?bv:1;
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
    if (FRAMEPAR_MODIFIED(P_BIN_VERT)) {
        if (bv<1) bv=1; else if (bv>dv) bv=dv;
        while ((bv>1) && !(sensor->binVert  & (1 << (bv-1)))) bv--; // adjust binning to maximal supported (if requested is not supported)
        if (unlikely(bv!=thispars->pars[P_BIN_VERT])) SETFRAMEPARS_SET(P_DCM_VERT, bv);
    }
    // any other binning adjustmens needed?
    // adjustP_WOI_WIDTH, P_ACTUAL_WIDTH, P_SENSOR_PIXH - depends on decimation, photofinish mode
    timestamp_len = (((thispars->pars[P_PF_HEIGHT] >> 16) & 3)==2)? X313_TIMESTAMPLEN*dh : 0;
    // adjust width/height first, then adjust left top
    width=thispars->pars[P_WOI_WIDTH];
    //  if ((!oversize) && (width > sensor->imageWidth)) width= sensor->imageWidth;
    //  if ((!oversize) && (width > sensor_width)) width= sensor_width;
    if ((!oversize) && (width > sensor_width)) width= sensor_width;

    // make width to be multiple of the compressor tile (before adding margins of 4 pixels)
1139
    width= (((width/dh) + timestamp_len)/X393_TILEHOR)*X393_TILEHOR-timestamp_len; // divided by dh
1140
    // suppose minimal width refers to decimated output
1141
    while (width < sensor->minWidth) width+=X393_TILEHOR;
1142 1143 1144
    if (unlikely(thispars->pars[P_ACTUAL_WIDTH] != (width+timestamp_len))) {
        SETFRAMEPARS_SET(P_ACTUAL_WIDTH, width+timestamp_len); ///full width for the compressor, including timestamp, but excluding margins
    }
1145 1146
    if (unlikely(thispars->pars[P_SENSOR_PIXH] != width+(2 * COLOR_MARGINS)))
        SETFRAMEPARS_SET(P_SENSOR_PIXH,  width+(2 * COLOR_MARGINS)); ///full width for the sensor (after decimation), including margins
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
    width*=dh;
    if (unlikely(thispars->pars[P_WOI_WIDTH] != width))
        SETFRAMEPARS_SET(P_WOI_WIDTH, width);  // WOI width, as specified (corrected for the sensor if needed)
    // adjustP_WOI_HEIGHT, P_ACTUAL_HEIGHT, P_SENSOR_PIXV - depends on decimation, photofinish mode
    pfh = (thispars->pars[P_PF_HEIGHT] & 0xffff);
    height=thispars->pars[P_WOI_HEIGHT];
    //  pf_stripes;
    if(pfh > 0) {
        if (pfh < sensor->minHeight)  pfh =  sensor->minHeight;
        if (pfh & 1) pfh++;
1157
        if (height > X393_MAXHEIGHT*dv) height=X393_MAXHEIGHT*dv;
1158 1159 1160 1161
        pf_stripes = height / (pfh * dv);
        if(pf_stripes < 1) pf_stripes = 1;
        if (unlikely(thispars->pars[P_SENSOR_PIXV] != pfh)) {
            SETFRAMEPARS_SET(P_SENSOR_PIXV,  pfh);
1162 1163
            dev_dbg(g_dev_ptr,"{%d}  SETFRAMEPARS_SET(P_SENSOR_PIXV,  0x%x)\n", sensor_port, pfh);
            MDP(DBGB_PADD, sensor_port,"SETFRAMEPARS_SET(P_SENSOR_PIXV,  0x%x)\n", pfh)
1164 1165 1166
        }
    } else {
        if ((!oversize ) && (height > sensor_height)) height=sensor_height;
1167
        height= ((height/dv)/X393_TILEVERT) * X393_TILEVERT; // divided by dv (before multisensor options)
1168
        // suppose minimal height refers to decimated output
1169
        while (height < sensor->minHeight) height+=X393_TILEVERT;
1170 1171
        if (unlikely(thispars->pars[P_SENSOR_PIXV] != height+(2 * COLOR_MARGINS)))
            SETFRAMEPARS_SET(P_SENSOR_PIXV,  height+(2 * COLOR_MARGINS)); ///full height for the sensor (after decimation), including margins
1172 1173 1174 1175 1176 1177
        height*=dv;
        pf_stripes = 0;
        pfh = 0;
    }
    // update photofinish height P_PF_HEIGHT
    if (unlikely((thispars->pars[P_PF_HEIGHT] & 0xffff) != pfh)) {
1178
        SETFRAMEPARS_SET(P_PF_HEIGHT, (thispars->pars[P_PF_HEIGHT] & 0xffff0000 ) | pfh );
1179 1180
        dev_dbg(g_dev_ptr,"{%d}  SETFRAMEPARS_SET(P_PF_HEIGHT,  0x%x)\n", sensor_port,(int) ((thispars->pars[P_PF_HEIGHT] & 0xffff0000 ) | pfh));
        MDP(DBGB_PADD, sensor_port,"SETFRAMEPARS_SET(P_PF_HEIGHT,  0x%x)\n", (int) ((thispars->pars[P_PF_HEIGHT] & 0xffff0000 ) | pfh))
1181 1182 1183
    }
    // update WOI height [P_WOI_HEIGHT
    if (unlikely(thispars->pars[P_WOI_HEIGHT] != height)) {
1184
        SETFRAMEPARS_SET(P_WOI_HEIGHT, height); ///full height for the compressor (excluding margins)
1185 1186
        dev_dbg(g_dev_ptr,"{%d}  SETFRAMEPARS_SET(P_WOI_HEIGHT,  0x%x)\n", sensor_port, height);
        MDP(DBGB_PADD, sensor_port,"SETFRAMEPARS_SET(P_WOI_HEIGHT,  0x%x)\n", height)
1187 1188 1189 1190
    }
    // update P_ACTUAL_HEIGHT
    ah=height/dv;
    if (unlikely(thispars->pars[P_ACTUAL_HEIGHT] != ah)) {
1191
        SETFRAMEPARS_SET(P_ACTUAL_HEIGHT, ah); ///full height for the compressor (excluding margins)
1192 1193
        dev_dbg(g_dev_ptr,"{%d}  SETFRAMEPARS_SET(P_ACTUAL_HEIGHT,  0x%x)\n", sensor_port, ah);
        MDP(DBGB_PADD, sensor_port,"SETFRAMEPARS_SET(P_ACTUAL_HEIGHT,  0x%x)\n", ah)
1194 1195 1196 1197 1198
    }
    // left margin
    left = thispars->pars[P_WOI_LEFT];
    if (!oversize) { // in oversize mode let user to specify any margin, including odd ones (bayer shifted)
        if (is_color)                    left &= 0xfffe;
1199 1200
        if ((left + width + (2 * COLOR_MARGINS)) > sensor->clearWidth) {
            left = sensor->clearWidth - width - (2 * COLOR_MARGINS);
1201 1202 1203 1204 1205 1206 1207
            if (is_color)               left &= 0xfffe;
        }
        if (left & 0x8000) left = 0;
    }
    // update P_WOI_LEFT
    if (unlikely(thispars->pars[P_WOI_LEFT] != left)) {
        SETFRAMEPARS_SET(P_WOI_LEFT, left);
1208 1209
        dev_dbg(g_dev_ptr,"{%d}  SETFRAMEPARS_SET(P_WOI_LEFT,  0x%x)\n", sensor_port, left);
        MDP(DBGB_PADD, sensor_port,"SETFRAMEPARS_SET(P_WOI_LEFT,  0x%x)\n", left)
1210
    }
1211

1212 1213
    // top margin
    top = thispars->pars[P_WOI_TOP];
Andrey Filippov's avatar
Andrey Filippov committed
1214
    clearHeight=(sensor->clearHeight-sensor->imageHeight) + thispars->pars[P_SENSOR_HEIGHT];
1215 1216
    if (!oversize) { // in oversize mode let user to specify any margin, including odd ones (bayer shifted)
        if (is_color)                    top &= 0xfffe;
1217 1218
        if ((top + ((pfh>0)?0:height) + (2 * COLOR_MARGINS)) > clearHeight) {
            top = clearHeight - ((pfh>0)?0:height) - (2 * COLOR_MARGINS);
1219 1220 1221
            if (is_color)               top &= 0xfffe;
        }
        if (top & 0x8000) top = 0;
1222
    }
1223 1224 1225
    // update P_WOI_TOP
    if (unlikely(thispars->pars[P_WOI_TOP] != top)) {
        SETFRAMEPARS_SET(P_WOI_TOP, top);
1226 1227
        dev_dbg(g_dev_ptr,"{%d}  SETFRAMEPARS_SET(P_WOI_TOP,  0x%x)\n", sensor_port, top);
        MDP(DBGB_PADD, sensor_port,"SETFRAMEPARS_SET(P_WOI_TOP,  0x%x)\n", top)
1228 1229 1230
    }
    if (nupdate)  setFramePars(sensor_port, thispars, nupdate, pars_to_update);  // save changes, schedule functions
    return 0;
1231 1232
}

1233 1234 1235 1236 1237 1238 1239 1240 1241
/** Convert time interval in camsync periods (10ns) to sensor pixel periods */
unsigned long camsync_to_sensor(unsigned long camsync_time,  ///< time interval in camsync periods (@100MHz)
                                unsigned long sensor_clk)    ///< sensor pixel clock in Hz
                                                          ///< @return time interval in pixel clock periods
{
    uint64_t ull_period = (((long long) sensor_clk) * ((long long) camsync_time));
    do_div(ull_period, CAMSYNC_FREQ);
    return (unsigned long) ull_period;
}
1242

1243 1244 1245 1246 1247 1248 1249 1250 1251
/** Convert time interval sesnor pixel periods to camsync periods (10ns)*/
unsigned long sensor_to_camsync(unsigned long pixel_time, ///< time interval in pixel clock periods
                                unsigned long sensor_clk) ///< sensor pixel clock in Hz
                                                          ///< @return time interval in camsync periods (@100MHz)
{
    uint64_t ull_period = (((long long) pixel_time) * ((long long) CAMSYNC_FREQ));
    do_div(ull_period, sensor_clk);
    return (unsigned long) ull_period;
}
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266

/** Check if compressor can keep up, limit sensor FPS if needed.
 *  Apply both user FPS limits (both low and high), prepare data for the sensor function and sequencer.
 *
 * TODO: Program external trigger frequency to the same value!
 * FIXME:  when geometry changes, _video_ exposure needs to be adjusted to keep absolute one (at least - mark as new?) */
int pgm_limitfps   (int sensor_port,               ///< sensor port number (0..3)
					struct sensor_t * sensor,      ///< sensor static parameters (capabilities)
					struct framepars_t * thispars, ///< sensor current parameters
					struct framepars_t * prevpars, ///< sensor previous parameters (not used here)
					int frame16)                   ///< 4-bit (hardware) frame number parameters should
												   ///< be applied to,  negative - ASAP
												   ///< @return always 0

{
1267 1268 1269 1270 1271 1272 1273 1274 1275
    // Calculate minimal frame period compressor can handle, apply requested fps, limit/program the sequencer
    struct frameparspair_t pars_to_update[8]; // 4 needed, increase if more entries will be added
    int nupdate=0;
    int async=(thispars->pars[P_TRIG] & 4)?1:0;
    int cycles;  // number of FPGA clock cycles per frame;
    int min_period;  // number of pixel clock periods needed for the compressor (or user limit)
    int period=0;
    int pfh;
    int n_stripes;
1276 1277
    int min_period_camsync, period_camsync;
    //#define CAMSYNC_FREQ 100000000 ///< 100MHz - frequency used for external trigger periods and delays
Andrey Filippov's avatar
Andrey Filippov committed
1278
    u32 clk_sensor = thispars->pars[P_CLK_SENSOR];
1279
    u32 clk_fpga = thispars->pars[P_CLK_FPGA];
1280
#if USELONGLONG
1281 1282 1283
    uint64_t ull_min_period;
    uint64_t ull_period;
#endif
1284
    if (!clk_fpga) clk_fpga = 240000000; // 240MHz
1285 1286 1287
    dev_dbg(g_dev_ptr,"{%d}  frame16=%d\n",sensor_port,frame16);
    MDP(DBGB_PSFN, sensor_port,"frame16=%d\n",frame16)
    if (frame16 >= PARS_FRAMES) return -1; // wrong frame
1288
    cycles=thispars->pars[P_TILES]; // number of tiles
Andrey Filippov's avatar
Andrey Filippov committed
1289
    //  dev_dbg(g_dev_ptr,"{%d}  tiles=%d(0x%x)\n",sensor_port,cycles,cycles);
1290 1291 1292 1293 1294 1295
    switch (thispars->pars[P_COLOR] & 0x0f){
    case COLORMODE_MONO6:
    case COLORMODE_COLOR:
    case COLORMODE_JP46:
    case COLORMODE_JP46DC:
    case COLORMODE_COLOR20:
1296
        cycles*=6; // now - blocks per frame
1297
        break;
1298
    default:
1299
        cycles*=4;
1300
    }
1301
    //    cycles  *=64 *2; //cycles per frame (64 pixels/block, 2 clock cycles/pixel)
1302
    cycles  *=64; //cycles per frame (64 pixels/block, 1 clock cycles/pixel in NC393)
Andrey Filippov's avatar
Andrey Filippov committed
1303
    dev_dbg(g_dev_ptr,"{%d}  cycles=%d(0x%x)\n",sensor_port,cycles,cycles);
1304
    MDP(DBGB_PADD, sensor_port,"cycles=%d(0x%x)\n",cycles,cycles)
1305
    cycles += thispars->pars[P_FPGA_XTRA]; // extra cycles needed for the compressor to start/finish the frame;
Andrey Filippov's avatar
Andrey Filippov committed
1306
    dev_dbg(g_dev_ptr,"{%d}  cycles with P_FPGA_XTRA =%d(0x%x)\n",sensor_port,cycles,cycles);
1307
    MDP(DBGB_PADD, sensor_port,"cycles with P_FPGA_XTRA =%d(0x%x)\n",cycles,cycles)
1308
    // #define P_CLK_FPGA, #define P_CLK_SENSOR    27-28 bits, cycles - 24-25 bits
1309 1310 1311 1312 1313
    if (!clk_sensor) {
        clk_sensor=90000000;
        dev_dbg(g_dev_ptr,"{%d}  clk_sensor is 0, setting to %d\n",sensor_port,(int)clk_sensor);
        MDP(DBGB_PADD, sensor_port,"clk_sensor is 0, setting to %d\n",(int)clk_sensor)
    }
1314 1315

#if USELONGLONG
Andrey Filippov's avatar
Andrey Filippov committed
1316
    ull_min_period=(((long long) cycles) * ((long long) clk_sensor));
1317
#ifdef __div64_32
1318
    __div64_32(&ull_min_period, clk_fpga);
1319
#else
1320
    do_div(ull_min_period, clk_fpga);
1321
    //    ull_min_period/=thispars->pars[P_CLK_FPGA];
1322 1323
#endif
    min_period= ull_min_period;
1324 1325
    dev_dbg(g_dev_ptr,"{%d} min_period =%d(0x%x)\n", sensor_port, min_period, min_period);
    MDP(DBGB_PADD, sensor_port,"min_period =%d(0x%x)\n", min_period, min_period)
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
    //  min_period = (((long long) cycles) * ((long long) thispars->pars[P_CLK_SENSOR])) / ((long long) thispars->pars[P_CLK_FPGA]);
#else
    if (cycles <          (1<<16) ) {
        min_period = (cycles * (thispars->pars[P_CLK_SENSOR] >> 12)) / (thispars->pars[P_CLK_FPGA]>>12);
    } else   if (cycles < (1<<18) ) {
        min_period = (((cycles>>2) * (thispars->pars[P_CLK_SENSOR] >> 12)) / (thispars->pars[P_CLK_FPGA]>>12)) << 2 ;
    } else   if (cycles < (1<<20) ) {
        min_period = (((cycles>>4) * (thispars->pars[P_CLK_SENSOR] >> 12)) / (thispars->pars[P_CLK_FPGA]>>12)) << 4 ;
    } else   if (cycles < (1<<22) ) {
        min_period = (((cycles>>6) * (thispars->pars[P_CLK_SENSOR] >> 12)) / (thispars->pars[P_CLK_FPGA]>>12)) << 6 ;
    } else   if (cycles < (1<<24) ) {
        min_period = (((cycles>>8) * (thispars->pars[P_CLK_SENSOR] >> 12)) / (thispars->pars[P_CLK_FPGA]>>12)) << 8 ;
    } else {
        min_period = (((cycles>>10) *(thispars->pars[P_CLK_SENSOR] >> 12)) / (thispars->pars[P_CLK_FPGA]>>12)) << 10 ;
    }
    ///? fp1000s= 10*sclk/(pix_period/100);
Andrey Filippov's avatar
Andrey Filippov committed
1342
    dev_dbg(sensor_port,"%s min_period =%d(0x%x)\n",sensor_port,min_period,min_period);
1343
#endif
1344 1345
    // is there limit set for the FPS?
    if (thispars->pars[P_FPSFLAGS]) {
1346
#if USELONGLONG
Andrey Filippov's avatar
Andrey Filippov committed
1347
        ull_period=(((long long) clk_sensor) * (long long) 1000);
1348 1349
#ifdef __div64_32
        __div64_32(&ull_period, thispars->pars[P_FP1000SLIM]);
1350
#else
1351
        do_div(ull_period, thispars->pars[P_FP1000SLIM]);
1352
        //        ull_period /= thispars->pars[P_FP1000SLIM];
1353
#endif
1354
        period= ull_period;
1355 1356
        dev_dbg(g_dev_ptr,"{%d} period =%d(0x%x)\n", sensor_port, period, period);
        MDP(DBGB_PADD, sensor_port,"period =%d(0x%x)\n", period, period)
Andrey Filippov's avatar
Andrey Filippov committed
1357
        //    period=(((long long) clk_sensor) * (long long) 1000)/((long long) thispars->pars[P_FP1000SLIM]);
1358 1359
#else
        period=125*(( thispars->pars[P_CLK_SENSOR] << 3) / thispars->pars[P_FP1000SLIM]); // 125 <<3 = 1000
Andrey Filippov's avatar
Andrey Filippov committed
1360
        dev_dbg(g_dev_ptr,"{%d} period =%d(0x%x)\n",sensor_port,period,period);
1361 1362
#endif
    }
Andrey Filippov's avatar
Andrey Filippov committed
1363
    dev_dbg(g_dev_ptr,"{%d}  period=%d\n",sensor_port,period);
1364
    MDP(DBGB_PADD, sensor_port,"period =%d(0x%x)\n", period, period)
1365 1366 1367 1368 1369 1370 1371
    if ((thispars->pars[P_FPSFLAGS] & 1) && (period>min_period)) min_period=period;
    // *********************************************************** P_PF_HEIGHT
    pfh=thispars->pars[P_PF_HEIGHT] &0xffff ;
    if (pfh>0) {
        n_stripes=thispars->pars[P_WOI_HEIGHT]/pfh;
        if (n_stripes>0) min_period/=n_stripes;
    }
1372

1373 1374
    if (min_period != thispars->pars[P_PERIOD_MIN]) {
        SETFRAMEPARS_SET(P_PERIOD_MIN, min_period);  // set it (and propagate to the later frames)
1375 1376
        dev_dbg(g_dev_ptr,"{%d}  SETFRAMEPARS_SET(P_PERIOD_MIN,  0x%x)\n", sensor_port, min_period);
        MDP(DBGB_PADD, sensor_port,"SETFRAMEPARS_SET(P_PERIOD_MIN,  0x%x)\n", min_period)
1377
    }
1378 1379 1380 1381 1382 1383 1384
    if (((thispars->pars[P_FPSFLAGS] & 2)==0) || (period < min_period)) period=0x7fffffff; // no upper limit
    if (period != thispars->pars[P_PERIOD_MAX]) SETFRAMEPARS_SET(P_PERIOD_MAX, period);         // set it (and propagate to the later frames)
    // Now see if the sequencer period needs to be adjusted
    //  if (async && (thispars->pars[P_TRIG_PERIOD] >=256)) { // <256 - single trig
    //  if (async && (thispars->pars[P_TRIG_PERIOD] !=1)) { // <256 - single trig, here only ==1 is for single
    // Update period to comply even if it is not in async mode
    if (thispars->pars[P_TRIG_PERIOD] !=1) { // <256 - single trig, here only ==1 is for single
1385 1386 1387 1388 1389 1390 1391 1392 1393
        min_period_camsync = sensor_to_camsync(min_period, thispars->pars[P_CLK_SENSOR]);
        if (thispars->pars[P_TRIG_PERIOD] < min_period_camsync) SETFRAMEPARS_SET(P_TRIG_PERIOD, min_period_camsync);  // set it (and propagate to the later frames)
        //        if (async &&  (thispars->pars[P_FPSFLAGS] & 2) && (thispars->pars[P_TRIG_PERIOD] > period)) {
        if (async &&  (thispars->pars[P_FPSFLAGS] & 2)) {
            period_camsync = sensor_to_camsync(period, thispars->pars[P_CLK_SENSOR]);
            if (thispars->pars[P_TRIG_PERIOD] > period_camsync) {
                SETFRAMEPARS_SET(P_TRIG_PERIOD, period_camsync);  // set it (and propagate to the later frames)
                MDP(DBGB_PADD, sensor_port,"SETFRAMEPARS_SET(P_TRIG_PERIOD, 0x%x)\n", period_camsync)
            }
1394 1395 1396 1397 1398
        }
    }
    if (nupdate)  setFramePars(sensor_port, thispars, nupdate, pars_to_update);  // save changes, schedule functions
    //  That's all - sensor or sequencer will be programmed later using the parameters specified here
    return 0;
1399 1400
}

1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
/** Program analog gains (all is done in sensor-specific function)
 * Nothing to do here - all in the sensor-specific function  */
int pgm_gains          (int sensor_port,               ///< sensor port number (0..3)
						struct sensor_t * sensor,      ///< sensor static parameters (capabilities)
						struct framepars_t * thispars, ///< sensor current parameters
						struct framepars_t * prevpars, ///< sensor previous parameters (not used here)
						int frame16)                   ///< 4-bit (hardware) frame number parameters should
													   ///< be applied to,  negative - ASAP
													   ///< @return always 0
{
Andrey Filippov's avatar
Andrey Filippov committed
1411
    dev_dbg(g_dev_ptr,"{%d}  frame16=%d\n",sensor_port,frame16);
1412
    MDP(DBGB_PSFN, sensor_port,"frame16=%d\n",frame16)
1413
    return 0;
1414 1415
}

1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
/** Program sensor trigger mode (needs sensor-specific one too), programs timestamp mode (early/normal)
 * TODO: implement for 393 */
int pgm_triggermode(int sensor_port,               ///< sensor port number (0..3)
					struct sensor_t * sensor,      ///< sensor static parameters (capabilities)
					struct framepars_t * thispars, ///< sensor current parameters
					struct framepars_t * prevpars, ///< sensor previous parameters (not used here)
					int frame16)                   ///< 4-bit (hardware) frame number parameters should
												   ///< be applied to,  negative - ASAP
												   ///< @return OK - 0, <0 - error
{
Andrey Filippov's avatar
Andrey Filippov committed
1426
    x393_camsync_mode_t camsync_mode = {.d32=0};
Andrey Filippov's avatar
Andrey Filippov committed
1427
    dev_dbg(g_dev_ptr,"{%d}  frame16=%d\n",sensor_port,frame16);
1428
    MDP(DBGB_PSFN, sensor_port,"frame16=%d\n",frame16)
1429
    if (frame16 >= PARS_FRAMES) return -1; // wrong frame
Andrey Filippov's avatar
Andrey Filippov committed
1430 1431 1432 1433 1434
#ifndef NC353
    camsync_mode.trig =     (thispars->pars[P_TRIG] & 4)?1:0;
    if (camsync_mode.trig) {  // if trigger mode, enable camsync module, if off - do nothing
        camsync_mode.en = 1;
        camsync_mode.en_set = 1;
1435 1436 1437
//When does it need to be disabled?
        camsync_mode.ts_chns =     (thispars->pars[P_EXTERN_TIMESTAMP]?1:0) << sensor_port;
        camsync_mode.ts_chns_set = 1 << sensor_port;
Andrey Filippov's avatar
Andrey Filippov committed
1438 1439 1440 1441
    }
    camsync_mode.trig_set = 1;
    // set directly, bypassing sequencer as it may fail with wrong trigger
    x393_camsync_mode (camsync_mode);
1442
    MDP(DBGB_PADD, sensor_port,"x393_camsync_mode(0x%x)\n",camsync_mode.d32)
Andrey Filippov's avatar
Andrey Filippov committed
1443 1444 1445 1446 1447
    return 0;
#else
    //    int fpga_addr= frame16;
    //    int async=(thispars->pars[P_TRIG] & 4)?1:0;
    X3X3_SEQ_SEND1(frame16,  X313_WA_DCR0, X353_DCR0(SENSTRIGEN,async));
1448
    return 0;
Andrey Filippov's avatar
Andrey Filippov committed
1449
#endif
1450 1451 1452
}


1453 1454
/** Program sensor input in FPGA (Bayer, 8/16 bits, FPN, test mode, number of lines).
 * TODO: implement for 393 (program_sensor())
1455 1456
 */

1457 1458 1459 1460 1461 1462 1463 1464
int pgm_sensorin   (int sensor_port,               ///< sensor port number (0..3)
					struct sensor_t * sensor,      ///< sensor static parameters (capabilities)
					struct framepars_t * thispars, ///< sensor current parameters
					struct framepars_t * prevpars, ///< sensor previous parameters (not used here)
					int frame16)                   ///< 4-bit (hardware) frame number parameters should
												   ///< be applied to,  negative - ASAP
												   ///< @return OK - 0, <0 - error
{
1465
#ifndef NC353
1466 1467 1468 1469
    x393_sens_mode_t      sens_mode =    {.d32=0};
    x393_sensio_width_t   sensio_width = {.d32=0};
    x393_sens_sync_mult_t sync_mult =    {.d32=0};
    x393_gamma_ctl_t      gamma_ctl =    {.d32=0};
1470
    int bayer;
Andrey Filippov's avatar