x393_mcntrl_adjust.py 232 KB
Newer Older
1 2 3
from __future__ import print_function
'''
# Copyright (C) 2015, Elphel.inc.
4
# Class to measure and adjust I/O delays  
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
# 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 3 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/>.

@author:     Andrey Filippov
@copyright:  2015 Elphel, Inc.
@license:    GPLv3.0+
@contact:    andrey@elphel.coml
@deffield    updated: Updated
'''
__author__ = "Andrey Filippov"
__copyright__ = "Copyright 2015, Elphel, Inc."
__license__ = "GPL"
__version__ = "3.0+"
__maintainer__ = "Andrey Filippov"
__email__ = "andrey@elphel.com"
__status__ = "Development"
31
import sys
32
import pickle
33 34
#import x393_mem
#x393_pio_sequences
35
#from import_verilog_parameters import VerilogParameters
36
from x393_mem                import X393Mem
37 38
#from x393_axi_control_status import X393AxiControlStatus
import x393_axi_control_status
39 40 41
from x393_pio_sequences      import X393PIOSequences
from x393_mcntrl_timing      import X393McntrlTiming
from x393_mcntrl_buffers     import X393McntrlBuffers
42
from verilog_utils import split_delay,combine_delay,NUM_FINE_STEPS, convert_w32_to_mem16,convert_mem16_to_w32
43 44 45

import get_test_dq_dqs_data # temporary to test processing            
import x393_lma
46
import time
47 48
import vrlg
#NUM_FINE_STEPS=    5
49 50 51 52 53
NUM_DLY_STEPS =NUM_FINE_STEPS * 32 # =160
DQI_KEY='dqi'
DQO_KEY='dqo'
ODD_KEY='odd'
 
54 55 56 57 58 59 60 61 62 63

class X393McntrlAdjust(object):
    DRY_MODE= True # True
    DEBUG_MODE=1
    x393_mem=None
    x393_axi_tasks=None #x393X393AxiControlStatus
    x393_pio_sequences=None
    x393_mcntrl_timing=None
    x393_mcntrl_buffers=None
    verbose=1
64
    adjustment_state={}
65 66 67 68
    def __init__(self, debug_mode=1,dry_mode=True):
        self.DEBUG_MODE=  debug_mode
        self.DRY_MODE=    dry_mode
        self.x393_mem=            X393Mem(debug_mode,dry_mode)
69 70
#        self.x393_axi_tasks=      X393AxiControlStatus(debug_mode,dry_mode)
        self.x393_axi_tasks=      x393_axi_control_status.X393AxiControlStatus(debug_mode,dry_mode)
71 72 73
        self.x393_pio_sequences=  X393PIOSequences(debug_mode,dry_mode)
        self.x393_mcntrl_timing=  X393McntrlTiming(debug_mode,dry_mode)
        self.x393_mcntrl_buffers= X393McntrlBuffers(debug_mode,dry_mode)
74
#        self.__dict__.update(VerilogParameters.__dict__["_VerilogParameters__shared_state"]) # Add verilog parameters to the class namespace
75
        try:
76
            self.verbose=vrlg.VERBOSE
77 78
        except:
            pass
79 80
#keep as command        

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    def format_dq_to_verilog(self,
                             estr):
        """
        Convert dq delays list to the form to paste to the Verilog parameters code
        <estr> quoted string, such as:
         "[['0xd9', '0xdb', '0xdc', '0xd4', '0xe0', '0xda', '0xd4', '0xd8'], ['0xdc', '0xe0', '0xf1', '0xdc', '0xe0', '0xdc', '0xdc', '0xdc']]"
        Returns a pair of strings to paste
        """
        se=eval(estr) # now a list of list of strings
        for l in se:
            for i,v in enumerate(l):
                l[i]=int(v,16)
        for lane in range(2):
            print("lane%d = 64'h"%lane,end="")
            for i in range(len(se[lane])):
                print("%02x"%se[lane][-i-1],end="")
            print()
98

99
    def missing_dqs_notused(self,
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
                     rd_blk,
                     quiet=False):
        """
        Suspect missing final DQS puls(es) during write if last written burst matches previous one
        <rd_blk> - block of 32-bit data read from DDR3 device
        <quiet>  - no output
        Returns True if missing DQS pulse is suspected
        """
        if (not rd_blk) or (len(rd_blk) <8 ):
            return False
        for i in range(-4,0):
            if rd_blk[i] != rd_blk[i-4]:
                break
        else:
            if not quiet:
                print ("End of the block repeats 2 last 8-bursts, insufficient number of trailing DQS pulses is suspected:")
                print("\n%03x:"%(len(rd_blk)-8),end=" ")
                for i in range(len(rd_blk)-8,len(rd_blk)):
                    print("%08x"%rd_blk[i],end=" ")
                print("\n")
            return True
        return False            
                   
123 124
    def set_phase_with_refresh(self, # check result for not None
                               phase,
125
                               quiet=1):
126 127
        """
        Set specified phase and matching cmda_odelay while temporarily turning off refresh
128 129
        @param phase phase to set, signed short
        @param quiet reduce output 
130 131 132 133 134 135 136 137 138 139 140 141
        @return cmda_odelay linear value or None if there is no valid cmda output delay for this phase
        """
        if not "cmda_bspe" in self.adjustment_state:
            raise Exception ("No cmda_odelay data is available. 'adjust_cmda_odelay 0 1 0.1 3' command should run first.")
        dly_steps=self.x393_mcntrl_timing.get_dly_steps()
        numPhaseSteps= int(dly_steps['SDCLK_PERIOD']/dly_steps['PHASE_STEP']+0.5)
        cmda_odly_data=self.adjustment_state['cmda_bspe'][phase % numPhaseSteps]
        if (not cmda_odly_data): # phase is invalid for CMDA
            return None
        cmda_odly_lin=cmda_odly_data['ldly']
        self.x393_axi_tasks.enable_refresh(0)
        self.x393_mcntrl_timing.axi_set_phase(phase,quiet=quiet)
142
        self.x393_mcntrl_timing.axi_set_cmda_odelay(combine_delay(cmda_odly_lin),quiet=quiet)
143 144
        self.x393_axi_tasks.enable_refresh(1)
        return cmda_odly_lin
145 146 147 148 149 150
    
    def set_phase_delays(self,
                         phase,
                         inp_period='A',
                         out_period='A',
                         refresh=True,
151
                         delays_phase=None, # if None - use global
152 153 154 155 156 157 158 159 160 161
                         quiet=1):
        """
        Set clock phase and all I/O delays optimal for this phase
        @param phase value to set
        @param inp_period - period branch for DQ inputs: E<arly>, N<ominal>, L<ate> or A<ny>    
        @param out_period - period branch for DQ outputs: E<arly>, N<ominal>, L<ate> or A<ny>
        @param refresh - turn refresh OFF before and ON after changing the delays and phase
        @param quiet - reduce output
        @return True on success, False on invalid phase    
        """
162 163 164
        num_addr=vrlg.ADDRESS_NUMBER
        num_banks=3
        
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
        rslt_names=("early","nominal","late")
        enl_in=None
        enl_out=None
        enl_in_used=None
        enl_out_used=None
        try:
            inp=str(inp_period)[0].upper()
        except:
            print ("Invalid parameter <inp_period>=%s"%(str(inp_period)))
            return False
        try:
            outp=str(out_period)[0].upper()
        except:
            print ("Invalid parameter <out_period>=%s"%(str(out_period)))
            return False
        
        if inp == 'A':
            enl_in=rslt_names
        else:
            for k in rslt_names:
                if inp == k[0].upper():
                    enl_in=(k,)
                    break
            else:
                print ("Unrecognized parameter <inp_period>=%s"%(str(inp_period)))
                return False

        if outp == 'A':
            enl_out=rslt_names
        else:
            for k in rslt_names:
                if outp == k[0].upper():
                    enl_out=(k,)
                    break
            else:
                print ("Unrecognized parameter <out_period>=%s"%(str(out_period)))
                return False
                    
                    
        dly_steps=self.x393_mcntrl_timing.get_dly_steps()
        numPhaseSteps= int(dly_steps['SDCLK_PERIOD']/dly_steps['PHASE_STEP']+0.5)
        phase= phase % numPhaseSteps # valid for negative also, numPhaseSteps should be <=128 (now it is 112)
207
        if delays_phase == None:
208
            try:
209
                delays_phase=self.adjustment_state['delays_phase']
210
            except:
211 212 213 214 215 216 217
                print("Delays for phases (self.adjustment_state['delays_phase']) are not set, running 'get_delays_vs_phase' command ")
                try:
                    delays_phase=self.get_delays_vs_phase(filter_dqo=2,
                                             filter_dqi=2,
                                             filter_dqso=2,
                                             filter_dqsi=2,
                                             filter_cmda=2,
218 219 220 221
                                             filter_read=0,
                                             filter_write=0,
                                             filter_rsel=None,
                                             filter_wsel=None,
222 223 224 225 226
                                             keep_all=False,
                                             set_table=True,
                                             quiet=quiet+2)
                    self.adjustment_state['delays_phase']=delays_phase
                except:
227
                    print ("Failed to execute 'get_delays_vs_phase' command")
228 229 230
                    return False
        elif quiet < 2:
            print ("using provided delays_phase")
231 232 233 234 235
        try:
            delays=delays_phase[phase]
        except:
            print("No valid delay data for phase %d is available"%(phase))
            return False
236 237
        if quiet<1:
            print ("delays=",delays)
238 239 240 241 242 243 244 245 246 247 248 249 250

        try:
            cmda_odly=delays['cmda']
        except:
            print("No valid CMDA output delay data for phase %d is available, it is required"%(phase))
            return False

        try:
            dqs_idelays=delays['dqsi']
        except:
            dqs_idelays=None
            if quiet < 2:
                print ("No valid DQS input delay data for phase %d is available, it will not be set"%(phase))
251

252 253 254 255 256 257 258 259 260 261 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
        try:
            dqs_odelays=delays['dqso']
        except:
            dqs_odelays=None
            if quiet < 2:
                print ("No valid DQS output delay data for phase %d is available, it will not be set"%(phase))
                
        for k in enl_in:
            try:
                dq_idelays=delays['dqi'][k]
                enl_in_used=k
                break
            except:
                pass
        else:
            dq_idelays=None
            if quiet < 2:
                print ("No valid DQ input delay data for phase %d (period(s)=%s) is available, it will not be set"%(phase,str(enl_in)))
                
        for k in enl_out:
            try:
                dq_odelays=delays['dqo'][k]
                enl_out_used=k
                break
            except:
                pass
        else:
            dq_odelays=None
            if quiet < 2:
                print ("No valid DQ output delay data for phase %d (period(s)=%s) is available, it will not be set"%(phase,str(enl_out)))
                
        if quiet < 2:
            print ("Going to set:")
            print ("phase=",phase)
            print ('cmda_odly=',cmda_odly)
            print ('dqs_idelays=',dqs_idelays)
            print ('dqs_odelays=',dqs_odelays)
            print ('dq_idelays=',dq_idelays,' (',enl_in_used,')')
            print ('dq_odelays=',dq_odelays,' (',enl_out_used,')')
            print ('Memory refresh will %sbe controlled'%(('NOT ','')[refresh]))
        if refresh:
            self.x393_axi_tasks.enable_refresh(0)
        self.x393_mcntrl_timing.axi_set_phase(phase,quiet=quiet)
295 296 297
        if isinstance(cmda_odly,(list,tuple)):
            self.x393_mcntrl_timing.axi_set_address_odelay(combine_delay(cmda_odly[:num_addr]),quiet=quiet)
            self.x393_mcntrl_timing.axi_set_bank_odelay   (combine_delay(cmda_odly[num_addr:num_addr+num_banks]),quiet=quiet)
298 299 300 301 302
            cmd_dly_data=cmda_odly[num_addr+num_banks:]
            while len(cmd_dly_data) < 5:
                cmd_dly_data.append(cmd_dly_data[-1]) # repeat last element (average address/command delay)
            self.x393_mcntrl_timing.axi_set_cmd_odelay    (combine_delay(cmd_dly_data),quiet=quiet) # for now - same delay TODO: upgrade!
#            self.x393_mcntrl_timing.axi_set_cmda_odelay(combine_delay(cmda_odly),quiet=quiet)
303 304
        else:
            self.x393_mcntrl_timing.axi_set_cmda_odelay(combine_delay(cmda_odly),quiet=quiet)
305 306 307
        if refresh:
            self.x393_axi_tasks.enable_refresh(1)
        if not dqs_idelays is None:
308
            self.x393_mcntrl_timing.axi_set_dqs_idelay(combine_delay(dqs_idelays),quiet=quiet)
309
        if not dq_idelays is None:
310
            self.x393_mcntrl_timing.axi_set_dq_idelay(combine_delay(dq_idelays),quiet=quiet)
311
        if not dqs_odelays is None:
312
            self.x393_mcntrl_timing.axi_set_dqs_odelay(combine_delay(dqs_odelays),quiet=quiet)
313
        if not dq_odelays is None:
314
            self.x393_mcntrl_timing.axi_set_dq_odelay(combine_delay(dq_odelays),quiet=quiet)
315 316
#        if refresh: #already set
#            self.x393_axi_tasks.enable_refresh(1)
317
        return True
318

319 320 321 322 323 324 325
    def adjust_cmda_odelay(self,
                           start_phase=0,
                           reinits=1, #higher the number - more re-inits are used (0 - only where absolutely necessary
                           max_phase_err=0.1,
                           quiet=1
                           ):
        """
326 327 328 329 330 331 332 333 334
        Find CMDA output delay for each phase value using linear interpolation for available results
        Use write levelling mode (refresh off) and A7 (that makes it write levelling or not).
        Only A7 is subject to marginal timing, other signals are kept safe. But accidentally it still can hit
        wrong timing - in that case memory is reset and re-initialized
        Sets global parameters, including self.adjustment_state['cmda_bspe']
        @param start_phase initial phase to start measuremts (non-0 only for debugging dependencies)
        @param reinits higher the number - more re-inits are used (0 - only where absolutely necessary)
        @param max_phase_err maximal phase error for command and address line as a fraction of SDCLK period to consider
        @param quiet reduce output
335
        """
336
        nbursts=16
337 338 339 340
        start_phase &= 0xff
        if start_phase >=128:
            start_phase -= 256 # -128..+127
        recover_cmda_dly_step=0x20 # subtract/add from cmda_odelay (hardware!!!) and retry (same as 20 decimal)
341
        max_lin_dly=NUM_DLY_STEPS-1
342 343 344 345 346 347 348 349 350 351
        wlev_address_bit=7
        wlev_max_bad=0.01 # <= OK, > bad
        def phase_step(phase,cmda_dly):
            """
            Find marginal delay for address/comand lines for particular
            clock pahse
            Raises exception if failed to get write levelling data even after
            changing cmda delay and restarting memory device
            Returns a tuple of the current cmda_odelay (hardware) and a marginal one for a7
            """
352
            cmda_dly_lin=split_delay(cmda_dly)
353 354
            self.x393_mcntrl_timing.axi_set_phase(phase,quiet=quiet)
            self.x393_mcntrl_timing.axi_set_cmda_odelay(cmda_dly,quiet=quiet)
355
            wlev_rslt=self.x393_pio_sequences.write_levelling(1, nbursts, quiet+1)
356 357 358 359 360
            if wlev_rslt[2]>wlev_max_bad: # should be 0, if not - Try to recover
                if quiet <4:
                    print("*** FAILED to read data in write levelling mode, restarting memory device")
                    print("    Retrying with the same cmda_odelay value = 0x%x"%cmda_dly)
                self.x393_pio_sequences.restart_ddr3()
361
                wlev_rslt=self.x393_pio_sequences.write_levelling(1,nbursts, quiet)
362 363 364 365 366 367 368 369 370 371 372
                if wlev_rslt[2]>wlev_max_bad: # should be 0, if not - change delay and restart memory
                    cmda_dly_old=cmda_dly
                    if cmda_dly >=recover_cmda_dly_step:
                        cmda_dly -= recover_cmda_dly_step
                    else:
                        cmda_dly += recover_cmda_dly_step
                    if quiet <4:
                        print("*** FAILED to read data in write levelling mode, restarting memory device")
                        print("    old cmda_odelay= 0x%x, new cmda_odelay =0x%x"%(cmda_dly_old,cmda_dly))
                    self.x393_mcntrl_timing.axi_set_cmda_odelay(cmda_dly,quiet=quiet)
                    self.x393_pio_sequences.restart_ddr3()
373
                    wlev_rslt=self.x393_pio_sequences.write_levelling(1, nbursts, quiet)
374 375 376 377 378 379
                    if wlev_rslt[2]>wlev_max_bad: # should be 0, if not - change delay and restart memory
                        raise Exception("Failed to read in write levelling mode after modifying cmda_odelay, aborting")
                    
# Try twice step before giving up (was not needed so far)                    
            d_high=max_lin_dly
            self.x393_mcntrl_timing.axi_set_address_odelay(
380
                                                           combine_delay(d_high),
381 382
                                                           wlev_address_bit,
                                                           quiet=quiet)
383
            wlev_rslt=self.x393_pio_sequences.write_levelling(1, nbursts, quiet+1)
384
            if not wlev_rslt[2]>wlev_max_bad:
385
                return  (split_delay(cmda_dly),-1) # even maximal delay is not enough to make rising sdclk separate command from A7
386 387 388 389 390
            # find marginal value of a7 delay to spoil write levelling mode
            d_high=max_lin_dly
            d_low=cmda_dly_lin
            while d_high > d_low:
                dly= (d_high + d_low)//2
391
                self.x393_mcntrl_timing.axi_set_address_odelay(combine_delay(dly),wlev_address_bit,quiet=quiet)
392
                wlev_rslt=self.x393_pio_sequences.write_levelling(1, nbursts, quiet+1)
393 394 395 396 397 398 399
                if wlev_rslt[2] > wlev_max_bad:
                    d_high=dly
                else:
                    if d_low == dly:
                        break
                    d_low=dly
            self.x393_mcntrl_timing.axi_set_cmda_odelay(cmda_dly,quiet=quiet)
400
            return (split_delay(cmda_dly),d_low)
401 402 403 404 405 406 407 408 409 410 411 412 413 414
               
        dly_steps=self.x393_mcntrl_timing.get_dly_steps()
        if quiet<1:
            print (dly_steps)
        numPhaseSteps= int(dly_steps['SDCLK_PERIOD']/dly_steps['PHASE_STEP']+0.5)
        if (start_phase+numPhaseSteps)>128:
            old_start_phase=start_phase
            while (start_phase+numPhaseSteps)>128:
                start_phase -= numPhaseSteps
            print("Selected scan phase range (%d..%d) does not fit into -128..+127, changing it to %d..%d)"%
                  (old_start_phase,old_start_phase+numPhaseSteps-1,start_phase,start_phase+numPhaseSteps-1))
#start_phase
        cmda_marg_dly=[None]*numPhaseSteps
        cmda_dly=0
415
        safe_early=split_delay(recover_cmda_dly_step)/2
416 417 418
#        print ("safe_early=%d(0x%x), recover_cmda_dly_step=%d(0x%x)"%(safe_early,safe_early,recover_cmda_dly_step,recover_cmda_dly_step))
        if reinits>0:
            self.x393_pio_sequences.restart_ddr3()
419 420
        else:
            self.x393_axi_tasks.enable_refresh(0) # if not init, at least turn refresh off!
421 422 423 424 425

        for phase in range(start_phase,start_phase+numPhaseSteps):
            if quiet <3:
                print ("%d:"%(phase),end=" ")
                sys.stdout.flush()
426 427 428
            elif quiet < 5:
                print (".",end="")
                sys.stdout.flush()
429 430 431
            phase_mod=phase % numPhaseSteps
            dlys= phase_step(phase,cmda_dly)
            cmda_marg_dly[phase_mod]=dlys # [1] # Marginal delay or -1
432
            cmda_dly = combine_delay(dlys[0]) # update if it was modified during recover
433 434 435 436 437
            # See if cmda_odelay is dangerously close - increase it (and re-init?)
            if dlys[1]<0:
                if quiet <3:
                    print ("X",end=" ")
                    sys.stdout.flush()
438 439 440
                elif quiet < 5:
                    print (".",end="")
                    sys.stdout.flush()
441 442 443 444 445 446 447 448 449
                if reinits > 1: #re-init each time failed to find delay
                    if quiet <3:
                        print ("\nFailed to find marginal odelay for A7 - re-initializing DDR3 with odelay=0x%x",cmda_dly)
                    self.x393_mcntrl_timing.axi_set_cmda_odelay(cmda_dly,quiet=quiet)
                    self.x393_pio_sequences.restart_ddr3()
            else:
                if quiet <3:
                    print ("%d"%dlys[1],end=" ")
                    sys.stdout.flush()
450 451 452
                elif quiet < 5:
                    print (".",end="")
                    sys.stdout.flush()
453
                lin_dly=split_delay(cmda_dly)
454 455 456 457 458 459
                if (dlys[1]-lin_dly) < safe_early:
                    if (lin_dly > 0):
                        lin_dly=max(0,lin_dly-2*safe_early)
                if (dlys[1]-lin_dly) < safe_early:
                    lin_dly=min(max_lin_dly,lin_dly+2*safe_early) # or just add safe_early to dlys[1]?
                
460 461
                if lin_dly != split_delay(cmda_dly):   
                    cmda_dly=combine_delay(lin_dly)
462 463 464 465 466
                    self.x393_mcntrl_timing.axi_set_cmda_odelay(cmda_dly,quiet=quiet)
                    if reinits > 0: #re-init each time failed to find delay
                        if quiet <3:
                            print ("\nMeasured marginal delay for A7 is too close to cmda_odelay,re-initializing DDR3 with odelay=0x%x"%cmda_dly)
                        self.x393_pio_sequences.restart_ddr3()
467
            
468 469 470 471

        if quiet <2:
            for i,d in enumerate(cmda_marg_dly):
                print ("%d %d %d"%(i, d[0], d[1]))
472 473
        elif quiet < 5:
                print ()
474 475 476 477 478 479
        #find the largest positive step of cmda_marg_dly while cyclically increasing phase
        numValid=0
        for i,d in enumerate(cmda_marg_dly):
            if d[1]>0:
                numValid += 1
        if numValid < 2:
480
            raise Exception("Too few points with measured marginal CMDA odelay: %d"%numValid)
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
        maxPosSep=0
        firstIndex=None
        for i,d in enumerate(cmda_marg_dly):
            if d[1]>0:
                for j in range(1,numPhaseSteps):
                    d1=cmda_marg_dly[(i + j) % numPhaseSteps][1]
                    if d1 >= 0: # valid data
                        if (d1 - d[1]) > maxPosSep:
                            maxPosSep = d1 - d[1]
                            firstIndex=(i + j) % numPhaseSteps
                        break;
        #now data from  firstIndex to (firstIndex+numPhaseSteps)%numPhaseSteps is ~monotonic - apply linear approximation
        if quiet <2:
            print ("firstIndex=%d"%(firstIndex))
        
        S0=0
        SX=0
        SY=0
        SX2=0
        SXY=0
        for x in range(numPhaseSteps):
            y=cmda_marg_dly[(x+firstIndex) % numPhaseSteps][1]
            if y>=0:
                y+=0.5
                S0+=1
                SX+=x
                SY+=y
                SX2+=x*x
                SXY+=x*y
#            print("x=%f, index=%d, y=%f, S0=%f, SX=%f, SY=%f, SX2=%f, SXY=%f"%(x, (x+firstIndex) % numPhaseSteps, y, S0, SX, SY, SX2, SXY))
        a = (SXY*S0 - SY*SX) / (SX2*S0 - SX*SX)
        b = (SY*SX2 - SXY*SX) / (SX2*S0 - SX*SX)
        if quiet < 2:
            print ("a=%f, b=%f"%(a,b))
        # fine delay corrections
        fineCorr= [0.0]*5
        fineCorrN=[0]*5
        for x in range(numPhaseSteps):
            y=cmda_marg_dly[(x+firstIndex) % numPhaseSteps][1]
            if (y>0):
                i=y % 5
                y+=0.5
                diff=y- (a * x + b)
                fineCorr[i]  += diff
                fineCorrN[i] += 1
        for i in range(5):
            if fineCorrN[i]>0:
                fineCorr[i]/=fineCorrN[i]
        if (quiet <2):
            print ("fineCorr = %s"%str(fineCorr))
531
            
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
        variantStep=-a*numPhaseSteps #how much b changes when moving over the full SDCLK period
        if (quiet <2):
            print ("Delay matching the full SDCLK period = %f"%(variantStep))
        b-=a*firstIndex # recalculate b for phase=0
        b_period=0
        if (quiet <2):
            print ("a=%f, b=%f"%(a,b))
        #Make b fit into 0..max_lin_dly range
        while (b>max_lin_dly):
            b-=variantStep
            b_period-=1
        while (b<0):
            b+=variantStep # can end up having b>max_lin_dly - if the phase adjust by delay is lower than full period
            b_period+=1
        if (quiet <2):
            print ("a=%f, b=%f, b_period=%d"%(a,b,b_period))
548

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
        # Find best minimal delay (with higher SDCLK frequency delay range can exceed the period and there could
        # be more than one solution
        bestSolPerErr=[] #list ot tuples, each containing(best cmda_odelay,number of added periods,error)  
        max_dly_err=abs(a)*max_phase_err*numPhaseSteps # maximal allowed delay error (in 160-step scale)
        if (quiet <2):
            print("Max dly error=%f"%(max_dly_err))
        for phase in range (numPhaseSteps):
            periods=0 # b_period
            y=a*phase+b
            y0=y
            #find the lowest approximate solution to consider
            if y0 > (-max_dly_err):
                while (y0 >= (variantStep-max_dly_err)):
                    y0 -= variantStep
                    periods -= 1
            else:
                while (y0<(-max_dly_err)):
                    y0 += variantStep
                    periods += 1
            dly_min= max(0,int(y0-4.5))
            dly_max= min(max_lin_dly,int(y0+5.5))
            dly_to_try=[]
            for d in range(dly_min,dly_max+1):
                dly_to_try.append((d,periods))
            if (y0<0): # add a second range to try (higher delay values
                y0+=variantStep
                periods += 1
                dly_min= max(0,int(y0-4.5))
                dly_max= min(max_lin_dly,int(y0+5.5))
                for d in range(dly_min,dly_max+1):
                    dly_to_try.append((d,periods))
            bestDly=None
            bestDiff=None
            bestPeriods=None
            for dp in dly_to_try:
                actualDelay=dp[0]-fineCorr[dp[0] % 5] # delay corrected for the non-uniform 160-scale
                diff=actualDelay-(y+variantStep*dp[1]) # dp[1] - number of added/removed full periods
                if (bestDiff is None) or (abs(bestDiff) > abs(diff)):
                    bestDiff = diff
                    bestDly =  dp[0]
                    bestPeriods= dp[1]
            phase_rslt=() #Default, if nothing was found
            if not bestDiff is None:
                phase_rslt=(bestDly,bestPeriods,bestDiff)
            if (quiet <2):
                print ("%d: %s %s"%(phase, str(dly_to_try), str(phase_rslt)) )
595
            
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
            bestSolPerErr.append(phase_rslt)
        if (quiet <2):
            for i in range(numPhaseSteps): # enumerate(cmda_marg_dly):
                d=cmda_marg_dly[i]
                print ("%d %d %d"%(i, d[0], d[1]),end=" ")
                if (bestSolPerErr[i]):
                    print("%d %d %f"%(bestSolPerErr[i][0],bestSolPerErr[i][1],bestSolPerErr[i][2]))
                else:
                    print()

#numPhaseSteps            
        #Add 180 dwegree shift (move cmda_odelay to EARLY of the marginal
        period_shift=0
        b_center= b- 0.5*variantStep
        if b_center < 0: # have to move late
            b_center+=variantStep
            period_shift+=1
        cmda_dly_per_err=[]
        for phase in range (numPhaseSteps):
            marg_phase=(phase+numPhaseSteps//2) % numPhaseSteps
            extra_periods=(phase+numPhaseSteps//2) // numPhaseSteps
            bspe= bestSolPerErr[marg_phase]
618 619 620 621 622 623 624
#            err_for_zero=int(round(-(phase+(b+fineCorr[0])/a))%numPhaseSteps)/(1.0*numPhaseSteps)
            err_for_zero=int(round(-(marg_phase+(b+fineCorr[0])/a))%numPhaseSteps)/(1.0*numPhaseSteps)
            if err_for_zero >0.5:
                err_for_zero=1.0-err_for_zero
            else:
                err_for_zero=None 

625 626 627 628
            if bspe:
                cmda_dly_per_err.append({'ldly':bspe[0],
                                         'period':bspe[1]+period_shift+extra_periods+b_period, # b_period - shift from the branch
                                                                  # where phase starts from the longest cmda_odelay and goes down
629 630 631
                                         'err':bspe[2],
                                         'zerr':err_for_zero
                                         })
632 633 634 635 636 637 638 639 640 641 642 643 644
            else:
                cmda_dly_per_err.append({}) # No solution for this phase value
        rdict={"cmda_odly_a":a,
               "cmda_odly_b":b_center,
               "cmda_odly_period":period_shift+b_period, # 
               "cmda_fine_corr":fineCorr,
               "cmda_bspe":cmda_dly_per_err}
        if (quiet <3):
            print("\ncmda_odelay adjustmet results:")
            print('cmda_odly_a:      %f'%(rdict['cmda_odly_a']))
            print('cmda_odly_b:      %f'%(rdict['cmda_odly_b']))
            print('cmda_odly_period: %d'%(rdict['cmda_odly_period']))
            print('cmda_fine_corr:   %s'%(rdict['cmda_fine_corr']))
645
            print("\nPhase DLY0 MARG_A7 CMDA PERIODS*10 ERR*10 ZERR*100")
646 647 648 649
            for i in range(numPhaseSteps): # enumerate(cmda_marg_dly):
                d=cmda_marg_dly[i]
                print ("%d %d %d"%(i, d[0], d[1]),end=" ")
                if (rdict['cmda_bspe'][i]):
650 651 652 653 654 655 656
                    e1=rdict['cmda_bspe'][i]['zerr']
                    if not e1 is None:
                        e1="%.3f"%(100*e1)
                    print("%d %d %f %s"%(rdict['cmda_bspe'][i]['ldly'],
                                           10*rdict['cmda_bspe'][i]['period'],
                                           10*rdict['cmda_bspe'][i]['err'],
                                           e1))
657 658 659
                else:
                    print()
#TODO: Add 180 shift to get center, not marginal cmda_odelay        
660
        self.adjustment_state.update(rdict)
661 662 663 664 665
        if (quiet <3):
            print ("rdict={")
            for k,v in rdict.items():
                print("'%s':%s,"%(k,str(v)))
            print ("}")
666 667
        return rdict
        
668 669 670 671 672 673 674
    def adjust_write_levelling(self,
                               start_phase=0,
                               reinits=1, #higher the number - more re-inits are used (0 - only where absolutely necessary
                               invert=0, # anti-align DQS (should be 180 degrees off from the normal one)
                               max_phase_err=0.1,
                               quiet=1
                               ):
675
        """
676
        Find DQS output delay for each phase value
677
        Depends on adjust_cmda_odelay results
678
        """
679
        nbursts=16
680 681 682
        try:
            self.adjustment_state['cmda_bspe']
        except:
683 684 685 686
            raise Exception("Command/Address delay calibration data is not found - please run 'adjust_cmda_odelay' command first")
        start_phase &= 0xff
        if start_phase >=128:
            start_phase -= 256 # -128..+127
687
        max_lin_dly=NUM_DLY_STEPS-1
688 689 690 691 692
        wlev_max_bad=0.01 # <= OK, > bad
        numPhaseSteps=len(self.adjustment_state['cmda_bspe'])
        if quiet < 2:
            print("cmda_bspe = %s"%str(self.adjustment_state['cmda_bspe']))
            print ("numPhaseSteps=%d"%(numPhaseSteps))
693 694 695
            
        self.x393_pio_sequences.set_write_lev(nbursts) # write leveling, 16 times   (full buffer - 128)
         
696 697 698 699 700 701 702 703 704 705 706 707
        def wlev_phase_step (phase):
            def norm_wlev(wlev): #change results to invert wlev data
                if invert:
                    return [1.0-wlev[0],1.0-wlev[1],wlev[2]]
                else:
                    return wlev
            dly90=int(0.25*numPhaseSteps*abs(self.adjustment_state['cmda_odly_a']) + 0.5) # linear delay step ~ SDCLK period/4
            cmda_odly_data=self.adjustment_state['cmda_bspe'][phase % numPhaseSteps]
            if (not cmda_odly_data): # phase is invalid for CMDA
                return None
            cmda_odly_lin=cmda_odly_data['ldly']
            self.x393_mcntrl_timing.axi_set_phase(phase,quiet=quiet)
708
            self.x393_mcntrl_timing.axi_set_cmda_odelay(combine_delay(cmda_odly_lin),quiet=quiet)
709 710
            d_low=0
            while d_low <= max_lin_dly:
711
                self.x393_mcntrl_timing.axi_set_dqs_odelay(combine_delay(d_low),quiet=quiet)
712
                wlev_rslt=norm_wlev(self.x393_pio_sequences.write_levelling(1, nbursts, quiet+1))
713 714 715 716 717
                if wlev_rslt[2]>wlev_max_bad: # should be 0 - otherwise wlev did not work (CMDA?)
                    raise Exception("Write levelling gave unespected data, aborting (may be wrong command/address delay, incorrectly initializaed")
                if (wlev_rslt[0] <= wlev_max_bad) and (wlev_rslt[1] <= wlev_max_bad):
                    break
                d_low+=dly90
718
            else:
719 720 721 722 723 724
                if quiet < 3:
                    print ("Failed to find d_low during initial quadrant search for phase=%d (0x%x)"%(phase,phase))
                return None
            # Now find d_high>d_low to get both bytes result above
            d_high= d_low+dly90   
            while d_high <= max_lin_dly:
725
                self.x393_mcntrl_timing.axi_set_dqs_odelay(combine_delay(d_high),quiet=quiet)
726
                wlev_rslt=norm_wlev(self.x393_pio_sequences.write_levelling(1, nbursts, quiet+1))
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
                if wlev_rslt[2]>wlev_max_bad: # should be 0 - otherwise wlev did not work (CMDA?)
                    raise Exception("Write levelling gave unespected data, aborting (may be wrong command/address delay, incorrectly initializaed")
                if (wlev_rslt[0] >= (1.0 -wlev_max_bad)) and (wlev_rslt[1] >= (1.0-wlev_max_bad)):
                    break
                d_high+=dly90
            else:
                if quiet < 3:
                    print ("Failed to find d_high during initial quadrant search for phase=%d (0x%x)"%(phase,phase))
                return None
            # Narrow range while both bytes fit
            if quiet < 2:
                print ("After quadrant adjust d_low=%d, d_high=%d"%(d_low,d_high))
            
            while d_high > d_low:
                dly= (d_high + d_low)//2
742
                self.x393_mcntrl_timing.axi_set_dqs_odelay(combine_delay(dly),quiet=quiet)
743
                wlev_rslt=norm_wlev(self.x393_pio_sequences.write_levelling(1, nbursts, quiet+1))
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
                if wlev_rslt[2]>wlev_max_bad: # should be 0 - otherwise wlev did not work (CMDA?)
                    raise Exception("Write levelling gave unespected data, aborting (may be wrong command/address delay, incorrectly initializaed")
                if (wlev_rslt[0] <= wlev_max_bad) and (wlev_rslt[1] <= wlev_max_bad):
                    if d_low == dly:
                        break
                    d_low=dly
                elif (wlev_rslt[0] >= (1.0 -wlev_max_bad)) and (wlev_rslt[1] >= (1.0-wlev_max_bad)):
                    d_high=dly
                else:
                    break #mixed results
            # Now process each byte separately
            if quiet < 2:
                print ("After common adjust d_low=%d, d_high=%d"%(d_low,d_high))
            d_low=[d_low,d_low]
            d_high=[d_high,d_high]
            for i in range(2):
                while d_high[i] > d_low[i]: 
                    dly= (d_high[i] + d_low[i])//2
                    if quiet < 1:
                        print ("i=%d, d_low=%d, d_high=%d, dly=%d"%(i,d_low[i],d_high[i],dly))
                    dly01=[d_low[0],d_low[1]]
                    dly01[i]=dly
766
                    self.x393_mcntrl_timing.axi_set_dqs_odelay(combine_delay(dly01),quiet=quiet)
767
                    wlev_rslt=norm_wlev(self.x393_pio_sequences.write_levelling(1, nbursts, quiet+1))
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
                    if wlev_rslt[2]>wlev_max_bad: # should be 0 - otherwise wlev did not work (CMDA?)
                        raise Exception("Write levelling gave unespected data, aborting (may be wrong command/address delay, incorrectly initializaed")
                    if wlev_rslt[i] <= wlev_max_bad:
                        if d_low[i] == dly:
                            break
                        d_low[i]=dly
                    else:
                        d_high[i]=dly
            return d_low

        if (start_phase+numPhaseSteps)>128:
            old_start_phase=start_phase
            while (start_phase+numPhaseSteps)>128:
                start_phase -= numPhaseSteps
            print("Selected scan phase range (%d..%d) does not fit into -128..+127, changing it to %d..%d)"%
                  (old_start_phase,old_start_phase+numPhaseSteps-1,start_phase,start_phase+numPhaseSteps-1))
#start_phase
        if reinits > 1: # Normally not needed (When started after adjust_cmda_odelay, but refresh should be off (init will do that)
            self.x393_pio_sequences.restart_ddr3()
        wlev_dqs_delays=[None]*numPhaseSteps
        
        for phase in range(start_phase,start_phase+numPhaseSteps):
            phase_mod=phase % numPhaseSteps
            if quiet <3:
                print ("%d(%d):"%(phase,phase_mod),end=" ")
                sys.stdout.flush()
794 795 796
            elif quiet < 5:
                print (".",end="")
                sys.stdout.flush()
797 798 799 800 801
            dlys=wlev_phase_step(phase)
            wlev_dqs_delays[phase_mod]=dlys
            if quiet <3:
                print ("%s"%str(dlys),end=" ")
                sys.stdout.flush()
802 803 804 805
            elif quiet < 5:
                print (".",end="")
                sys.stdout.flush()
            if quiet< 2:
806 807 808 809 810 811 812 813
                print()
                
        if quiet <2:
            for i,d in enumerate(wlev_dqs_delays):
                if d:
                    print ("%d %d %d"%(i, d[0], d[1]))
                else:
                    print ("%d"%(i))
814 815
        elif quiet < 5:
            print ()
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
            
        #find the largest positive step of cmda_marg_dly while cyclically increasing phase
        numValid=0
        for i,d in enumerate(wlev_dqs_delays):
            if d:
                numValid += 1
        if numValid < 2:
            raise Exception("Too few points with DQS output delay in write levelling mode: %d"%numValid)

        firstIndex=[None]*2
        for lane in range(2):
            maxPosSep=0
            for i,d in enumerate(wlev_dqs_delays):
                if d>0:
                    for j in range(1,numPhaseSteps):
                        d1=wlev_dqs_delays[(i + j) % numPhaseSteps]
                        if d1: # valid data
                            if (d1[lane] - d[lane]) > maxPosSep:
                                maxPosSep = d1[lane] - d[lane]
                                firstIndex[lane]=(i + j) % numPhaseSteps
                            break;
        #now data from  firstIndex to (firstIndex+numPhaseSteps)%numPhaseSteps is ~monotonic - apply linear approximation
        if quiet <2:
            print ("firstIndices=[%d,%d]"%(firstIndex[0],firstIndex[1]))
        #Linear approximate each lane
        a=[None]*2
        b=[None]*2
        for lane in range(2):
            S0=0
            SX=0
            SY=0
            SX2=0
            SXY=0
            for x in range(numPhaseSteps):
                dlys=wlev_dqs_delays[(x+firstIndex[lane]) % numPhaseSteps]
                if dlys:
                    y=dlys[lane]+0.5
                    S0+=1
                    SX+=x
                    SY+=y
                    SX2+=x*x
                    SXY+=x*y
    #            print("x=%f, index=%d, y=%f, S0=%f, SX=%f, SY=%f, SX2=%f, SXY=%f"%(x, (x+firstIndex) % numPhaseSteps, y, S0, SX, SY, SX2, SXY))
            a[lane] = (SXY*S0 - SY*SX) / (SX2*S0 - SX*SX)
            b[lane] = (SY*SX2 - SXY*SX) / (SX2*S0 - SX*SX)
        if quiet < 2:
            print ("a=[%f, %f], b=[%f, %f]"%(a[0],a[1],b[0],b[1]))

        # fine delay corrections
        fineCorr= [[0.0]*5,[0.0]*5] # not [[0.0]*5]*2 ! - they will poin to the same top element 
        fineCorrN=[[0]*5,[0]*5]     # not [[0]*5]*2 !
        for lane in range(2):
            for x in range(numPhaseSteps):
                dlys=wlev_dqs_delays[(x+firstIndex[lane]) % numPhaseSteps]
                if dlys:
                    y=dlys[lane]
                    i=y % 5
                    y+=0.5
                    diff=y- (a[lane] * x + b[lane])
                    fineCorr[lane][i]  += diff
                    fineCorrN[lane][i] += 1
#                    print("lane,x,y,i,diff,fc,fcn= %d, %d, %f, %d, %f, %f, %d"%(lane,x,y,i,diff,fineCorr[lane][i],fineCorrN[lane][i]))
#            print ("lane=%d, fineCorr=%s, fineCorrN=%s"%(lane, fineCorr[lane], fineCorrN[lane]))
            for i in range(5):
                if fineCorrN[lane][i]>0:
                    fineCorr[lane][i]/=fineCorrN[lane][i]
#            print ("lane=%d, fineCorr=%s, fineCorrN=%s"%(lane, fineCorr[lane], fineCorrN[lane]))
                    
        if (quiet <2):
            print ("fineCorr lane0 = %s"%str(fineCorr[0])) # Why ar they both the same?
            print ("fineCorr lane1 = %s"%str(fineCorr[1]))
        variantStep=[-a[0]*numPhaseSteps,-a[1]*numPhaseSteps] #how much b changes when moving over the full SDCLK period
        if (quiet <2):
            print ("Delay matching the full SDCLK period = [%f, %f]"%(variantStep[0],variantStep[1]))
        b_period=[None]*2
        for lane in range(2):
            b[lane]-=a[lane]*firstIndex[lane] # recalculate b for phase=0
            b_period[lane]=0
            if (quiet <2):
                print ("a[%d]=%f, b[%d]=%f"%(lane,a[lane],lane,b[lane]))
            #Make b fit into 0..max_lin_dly range
            while (b[lane] > max_lin_dly):
                b[lane]-=variantStep[lane]
                b_period[lane]-=1
            while (b[lane] < 0):
                b[lane] += variantStep[lane] # can end up having b>max_lin_dly - if the phase adjust by delay is lower than full period
                b_period[lane] += 1
        if (quiet <2):
            print ("a[0]=%f, b[0]=%f, b_period[0]=%d"%(a[0],b[0],b_period[0]))
            print ("a[1]=%f, b[1]=%f, b_period[1]=%d"%(a[1],b[1],b_period[1]))
            
        # Find best minimal delay (with higher SDCLK frequency delay range can exceed the period and there could
        # be more than one solution
        bestSolPerErr=[[],[]] # pair (for two lanes) of lists ot tuples, each containing(best cmda_odelay,number of added periods,error)
        max_dly_err=[abs(a[0])*max_phase_err*numPhaseSteps, # maximal allowed delay error (in 160-step scale)
                     abs(a[1])*max_phase_err*numPhaseSteps]
        if (quiet <2):
            print("Max dly error=%s"%(str(max_dly_err)))
        for lane in range(2):
            for phase in range (numPhaseSteps):
                periods=0 # b_period[lane]
                y=a[lane]*phase+b[lane]
                y0=y
                #find the lowest approximate solution to consider
                if y0 > (-max_dly_err[lane]):
                    while (y0 >= (variantStep[lane]-max_dly_err[lane])):
                        y0 -= variantStep[lane]
                        periods -= 1
                else:
                    while (y0<(-max_dly_err[lane])):
                        y0 += variantStep[lane]
                        periods += 1
928
                dly_min= max(0,int(y0-4.5))
929 930 931 932 933 934 935 936 937 938 939
                dly_max= min(max_lin_dly,int(y0+5.5))
                dly_to_try=[]
                for d in range(dly_min,dly_max+1):
                    dly_to_try.append((d,periods))
                if (y0<0): # add a second range to try (higher delay values
                    y0+=variantStep[lane]
                    periods += 1
                    dly_min= max(0,int(y0-4.5))
                    dly_max= min(max_lin_dly,int(y0+5.5))
                    for d in range(dly_min,dly_max+1):
                        dly_to_try.append((d,periods))
940 941
                bestDly=None
                bestDiff=None
942 943 944 945
                bestPeriods=None
                for dp in dly_to_try:
                    actualDelay=dp[0]-fineCorr[lane][dp[0] % 5] # delay corrected for the non-uniform 160-scale
                    diff=actualDelay-(y+variantStep[lane]*dp[1]) # dp[1] - number of added/removed full periods
946 947
                    if (bestDiff is None) or (abs(bestDiff) > abs(diff)):
                        bestDiff = diff
948 949 950
                        bestDly =  dp[0]
                        bestPeriods= dp[1]
                phase_rslt=() #Default, if nothing was found
951
                if not bestDiff is None:
952 953 954 955 956 957 958 959 960 961
                    phase_rslt=(bestDly,bestPeriods,bestDiff)
                if (quiet <2):
                    print ("%d:%d: %s %s"%(lane, phase, str(dly_to_try), str(phase_rslt)) )
                
                bestSolPerErr[lane].append(phase_rslt)
        if (quiet <2):
            for i in range(numPhaseSteps): # enumerate(cmda_marg_dly):
                d=wlev_dqs_delays[i]
                if d:
                    print ("%d %d %d"%(i, d[0], d[1]),end=" ")
962
                else:
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
                    print ("%d X X"%(i),end=" ")
                for lane in range(2):
                    bspe=bestSolPerErr[lane][i]
                    if bspe:
                        print("%d %d %f"%(bspe[0], bspe[1], bspe[2]),end=" ")
                    else:
                        print("X X X",end=" ")
                print()
        wlev_bspe=[[],[]]
        for lane in range (2):
            for phase in range (numPhaseSteps):
                bspe=bestSolPerErr[lane][phase]
                if bspe:
                    wlev_bspe[lane].append({'ldly':bspe[0],
                                             'period':bspe[1]+b_period[lane], # b_period - shift from the branch
                                                                        # where phase starts from the longest cmda_odelay and goes down
                                             'err':bspe[2]})
980
                else:
981
                    wlev_bspe[lane].append({})
982
                
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
        rdict={"wlev_dqs_odly_a":    a, #[,]
               "wlev_dqs_odly_b":    b,#[,]
               "wlev_dqs_period":    b_period, # 
               "wlev_dqs_fine_corr": fineCorr,
               "wlev_dqs_bspe":      wlev_bspe}
        if (quiet <3):
            print("\nwrite levelling DQS output delay adjustmet results:")
            print('wlev_dqs0_odly_a:    %f'%(rdict['wlev_dqs_odly_a'][0]))
            print('wlev_dqs1_odly_a:    %f'%(rdict['wlev_dqs_odly_a'][1]))
            print('wlev_dqs0_odly_b:    %f'%(rdict['wlev_dqs_odly_b'][0]))
            print('wlev_dqs1_odly_b:    %f'%(rdict['wlev_dqs_odly_b'][1]))
            print('wlev_dqs0_period:    %d'%(rdict['wlev_dqs_period'][0]))
            print('wlev_dqs1_period:    %d'%(rdict['wlev_dqs_period'][1]))
            print('wlev_dqs0_fine_corr: %s'%(rdict['wlev_dqs_fine_corr'][0]))
            print('wlev_dqs1_fine_corr: %s'%(rdict['wlev_dqs_fine_corr'][1]))
            print("\nPhase Measured_DQS0 Measured_DQS1 DQS0 PERIODS0*10 ERR0*10 DQS1 PERIODS1*10 ERR1*10")
            for i in range(numPhaseSteps): # enumerate(cmda_marg_dly):
                d=wlev_dqs_delays[i]
                if d:
                    print ("%d %d %d"%(i, d[0], d[1]),end=" ")
                else:
                    print ("%d X X"%(i),end=" ")
                for lane in range(2):
                    bspe=rdict['wlev_dqs_bspe'][lane][i] # bestSolPerErr[lane][i]
                    if bspe:
                        print("%d %d %f"%(bspe['ldly'], 10*bspe['period'], 10*bspe['err']),end=" ")
                    else:
                        print("X X X",end=" ")
1011 1012
                print()
                            
1013
        self.adjustment_state.update(rdict)
1014 1015 1016 1017 1018
        if (quiet <3):
            print ("rdict={")
            for k,v in rdict.items():
                print("'%s':%s,"%(k,str(v)))
            print ("}")
1019
        return rdict
1020
          
1021
    def measure_pattern(self,
1022 1023 1024
                       compare_prim_steps=True, # while scanning, compare this delay with 1 less by primary(not fine) step,
                                                # save None for fraction in unknown (previous -0.5, next +0.5) 
                       limit_step=0.125, # initial delay step as a fraction of the period
1025 1026 1027 1028 1029 1030 1031 1032
                       max_phase_err=0.1,
                       quiet=1,
                       start_dly=0): #just to check dependence
        """
        for each DQS input delay find 4 DQ transitions for each DQ bit,
        then use them to find finedelay for each of the DQS and DQ,
        linear coefficients (a,b) for each DQ vs DQS and asymmetry
        (late 0->1, early 1->0) for each of the DQ and DQS
1033 1034
        @param quiet reduce output

1035 1036
        """
        nrep=8
1037
        max_lin_dly=NUM_DLY_STEPS-1#159
1038 1039
        timing=self.x393_mcntrl_timing.get_dly_steps()
        #steps={'DLY_FINE_STEP': 0.01, 'DLY_STEP': 0.078125, 'PHASE_STEP': 0.022321428571428572, 'SDCLK_PERIOD': 2.5}
1040 1041
        dly_step=int(NUM_FINE_STEPS*limit_step*timing['SDCLK_PERIOD']/timing['DLY_STEP']+0.5)
        step180= int(NUM_FINE_STEPS*0.5* timing['SDCLK_PERIOD'] / timing['DLY_STEP'] +0.5)                                                                                                                                                                                                                 
1042 1043 1044 1045 1046 1047 1048 1049
        if quiet<2:
            print ("timing)=%s, dly_step=%d step180=%d"%(str(timing),dly_step,step180))
        self.x393_pio_sequences.set_read_pattern(nrep+3) # set sequence once
        
        def patt_dqs_step(dqs_lin):
            patt_cache=[None]*(max_lin_dly+1) # cache for holding already measured delays
            def measure_patt(dly,force_meas=False):
                if (patt_cache[dly] is None) or force_meas:
1050
                    self.x393_mcntrl_timing.axi_set_dq_idelay(combine_delay(dly),quiet=quiet)
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
                    patt= self.x393_pio_sequences.read_levelling(nrep,
                                                                 -1, # sel=1, # 0 - early, 1 - late read command (shift by a SDCLK period), -1 - use current sequence 
                                                                 quiet+1)
                    patt_cache[dly]=patt
                    if quiet < 1:
                        print ('measure_patt(%d,%s) - new measurement'%(dly,str(force_meas)))
                else:
                    patt=patt_cache[dly]
                    if quiet < 1:
                        print ('measure_patt(%d,%s) - using cache'%(dly,str(force_meas)))
                return patt
            def get_sign(data,edge=None):
                """
                edge: 0 - first 16, 1 - second 16
                return -1 if  all <0.5
                return +1 if all >0.5
                return 0 otherwise
                """
                if edge == 0:
                    return get_sign(data[:16])
                if edge == 1:
#                    return -get_sign(data[16:])
                    return get_sign(data[16:])
                m1=True
                p1=True
                for d in data:
                    m1 &= (d < 0.5)
                    p1 &= (d > 0.5)
                    if not (m1 or p1):
                        break
                else:
                    if m1:
                        return -1
                    elif p1:
                        return 1
                return 0
            
            rslt=[None]*16 # each bit will have [inphase][dqs_falling]
1089
            self.x393_mcntrl_timing.axi_set_dqs_idelay(combine_delay(dqs_lin),quiet=quiet)
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
            d_low=[None]*2  # first - lowest when all are -+, second - when all are +-  
            d_high=[None]*2 # first - when all are +- after -+, second - when all are -+ after +-
            dly=0
            notLast=True
            needSigns=None
            lowGot=None
            highGot=None
            while (dly <= max_lin_dly) and notLast:
                notLast= dly < max_lin_dly
                patt=measure_patt(dly) # ,force_meas=False)
                signs=(get_sign(patt,0),get_sign(patt,1))
                if quiet < 1:
                    print ('dly=%d lowGot=%s, highGot=%s, signs=%s'%(dly,str(lowGot),str(highGot),str(signs)))
                if lowGot is None : # looking for the first good sample
                    if (signs==(-1,1)) or  (signs==(1,-1)) :
                        if signs[0] == -1: #  == (-1,1):
                            lowGot=0
                        else:
                            lowGot=1
                        d_low[lowGot] = dly
                        needSigns=((1,-1),(-1,1))[lowGot]
                        dly += step180-dly_step # almost 180 degrees
                    else: # at least one is 0
                        dly += dly_step # small step
                    if quiet < 1:
                        print ('lowGot was None : dly=%d, lowGot=%s, needSigns=%s'%(dly,str(lowGot),str(needSigns)))
                elif highGot is None : # only one good sample is available so far
                    if signs == needSigns:
                        highGot=lowGot
                        d_high[highGot] = dly
                        d_low[1-lowGot] = dly
                        needSigns=((-1,1),(1,-1))[lowGot]
                        dly += step180-dly_step # almost 180 degrees
                    else:
                        dly += dly_step # small step
                    if quiet < 1:
                        print ('highGot was None : dly=%d, lowGot=%s, highGot=%s, needSigns=%s'%(dly,str(lowGot),str(lowGot),str(needSigns)))
                else: # looking for the 3-rd sample 
                    if signs == needSigns:
                        highGot=1-highGot
                        d_high[highGot] = dly
                        break
                    else:
                        dly += dly_step # small step
                dly = min (dly,max_lin_dly)
            if highGot is None:
                if quiet < 3:
                    print ("Could not find initial bounds for DQS input delay = %d d_low=%s, d_high=%s"%(dqs_lin,str(d_low),str(d_high)))
                return None
            if quiet < 2:
                    print ("DQS input delay = %d , preliminary bounds: d_low=%s, d_high=%s"%(dqs_lin,str(d_low),str(d_high)))
            for inPhase in range(2):
                if not d_high[inPhase] is None:
                    # Try to squeeze d_low, d_high closer to reduce scan range
                    while d_high[inPhase]>d_low[inPhase]:
                        dly=(d_high[inPhase] + d_low[inPhase])//2
                        patt=measure_patt(dly) # ,force_meas=False)
                        signs=(get_sign(patt,0),get_sign(patt,1))
                        if signs==(-1,1):
                            if inPhase:
                                d_high[inPhase]=dly 
                            else:
                                if d_low[inPhase]==dly:
                                    break
                                d_low[inPhase]=dly 
                        elif signs==(1,-1):     
                            if inPhase:
                                if d_low[inPhase]==dly:
                                    break
                                d_low[inPhase]=dly 
                            else:
                                d_high[inPhase]=dly 
                        else: # uncertain result 
                            break
            if quiet < 2:
                    print ("DQS input delay = %d , squeezed bounds: d_low=%s, d_high=%s"%(dqs_lin,str(d_low),str(d_high)))
#Improve squeezing - each limit to the last

            for inPhase in range(2):
                if not d_high[inPhase] is None:
                    # Try to squeeze d_low first
                    d_uncertain=d_high[inPhase]
                    while d_uncertain > d_low[inPhase]:
                        dly=(d_uncertain + d_low[inPhase])//2
                        patt=measure_patt(dly) # ,force_meas=False)
                        signs=(get_sign(patt,0),get_sign(patt,1))
                        if signs==(-1,1):
                            if inPhase:
                                d_uncertain=dly 
                            else:
                                if d_low[inPhase]==dly:
                                    break
                                d_low[inPhase]=dly 
                        elif signs==(1,-1):     
                            if inPhase:
                                if d_low[inPhase]==dly:
                                    break
                                d_low[inPhase]=dly 
                            else:
                                d_uncertain=dly 
                        else: # uncertain result
                            d_uncertain=dly
                    #now udjust upper limit
                    while d_high[inPhase] > d_uncertain:
                        dly=(d_high[inPhase] + d_uncertain)//2
                        patt=measure_patt(dly) # ,force_meas=False)
                        signs=(get_sign(patt,0),get_sign(patt,1))
                        if signs==(-1,1):
                            if inPhase:
                                d_high[inPhase]=dly 
                            else:
                                if d_uncertain==dly:
                                    break
                                d_uncertain=dly 
                        elif signs==(1,-1):     
                            if inPhase:
                                if d_uncertain==dly:
                                    break
                                d_uncertain=dly 
                            else:
                                d_high[inPhase]=dly 
                        else: # uncertain result 
                            if d_uncertain==dly:
                                break
                            d_uncertain=dly
            if quiet < 2:
                    print ("DQS input delay = %d , tight squeezed bounds: d_low=%s, d_high=%s"%(dqs_lin,str(d_low),str(d_high)))

                    
            # scan ranges, find closest solutions
1220
            #compare_prim_steps
1221 1222 1223 1224
            best_dly= [[],[]]
            best_diff=[[],[]]
            for inPhase in range(2):
                if not d_high[inPhase] is None:
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
#                    patt=None
                    best_dly[inPhase]=[d_low[inPhase]]*32
                    best_diff[inPhase]=[None]*32
#                    for b,p in enumerate(patt):
#                        positiveJump=((not inPhase) and (b<16)) or (inPhase and (b >= 16)) # may be 0, False, True
#                        if positiveJump:
#                            best_diff[inPhase].append(p-0.5)
#                        else:
#                            best_diff[inPhase].append(0.5-p)
                    for dly in range(d_low[inPhase]+1,d_high[inPhase]+1):
#                        patt_prev=patt
                        #as measured data is cached, there is no need to specially maintain patt_prev from earlier measurement
                        dly_prev= max(0,dly-(1,NUM_FINE_STEPS)[compare_prim_steps])
                        patt_prev=measure_patt(dly_prev) # ,force_meas=False) - will be stored in cache
                        patt=     measure_patt(dly) # ,force_meas=False) - will be stored in cache
                        for b in range(32):
                            positiveJump=((not inPhase) and (b<16)) or (inPhase and (b >= 16)) # may be 0, False, True       
                            signs=((-1,1)[patt_prev[b]>0.5],(-1,1)[patt[b]>0.5])
                            if (positiveJump and (signs==(-1,1))) or (not positiveJump and (signs==(1,-1))):
                                if positiveJump:
                                    diffs_prev_this=(patt_prev[b]-0.5,patt[b]-0.5)
                                else:
                                    diffs_prev_this=(0.5-patt_prev[b],0.5-patt[b])
                                if abs(diffs_prev_this[0]) <= abs(diffs_prev_this[1]): # store previos sample
                                    if (best_diff[inPhase][b] is None) or (abs (diffs_prev_this[0])<abs(best_diff[inPhase][b])):
                                        best_dly[inPhase][b]=dly_prev # dly-1
                                        best_diff[inPhase][b]=diffs_prev_this[0]
                                        if quiet < 1:
                                            print ("*%d:%0.3f:%0.3f%s"%(b,diffs_prev_this[0],diffs_prev_this[1],str(signs)),end="")
                                else:
                                    if (best_diff[inPhase][b] is None) or (abs (diffs_prev_this[1])<abs(best_diff[inPhase][b])):
                                        best_dly[inPhase][b]=dly # dly-1
                                        best_diff[inPhase][b]=diffs_prev_this[1]
                                        if quiet < 1:
                                            print ("?%d:%0.3f:%0.3f%s"%(b,diffs_prev_this[0],diffs_prev_this[1],str(signs)),end="")
                        if quiet < 1:
                            print("\n dly=%d dly_prev=%d:"%(dly,dly_prev),end=" ")
                    for b in range(32):
                        if  best_diff[inPhase][b] == -0.5:
                            best_diff[inPhase][b] = None # will have to add half-interval (0.5 or 2.5) 
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
                # rslt=[None]*16 # each bit will have [inphase][dqs_falling], each - a pair of (delay,diff)
            for b in range(16):
                rslt[b]=[[None]*2,[None]*2] # [inphase][dqs_falling]
                for inPhase in range(2):
                    if not d_high[inPhase] is None:
                        rslt[b][inPhase]= [(best_dly[inPhase][b],best_diff[inPhase][b]),(best_dly[inPhase][b+16],best_diff[inPhase][b+16])]
            if quiet < 2:
                    print ("%d: rslt=%s"%(dqs_lin,str(rslt)))
            return rslt
#        meas_data=[]
#        for ldly in range(max_lin_dly+1):
#            if quiet <3:
1277
#                print ("%d(0x%x):"%(ldly,combine_delay(ldly)),end=" ")
1278 1279 1280 1281
#                sys.stdout.flush()
#            meas_data.append(patt_dqs_step(ldly))
#        if quiet <3:
#            print ()
1282
        # main method code
1283 1284 1285 1286 1287 1288
        meas_data=[None]*(max_lin_dly+1)
        #start_dly
        for sdly in range(max_lin_dly+1):
            ldly = (start_dly+sdly)%(max_lin_dly+1)
#        for ldly in range(max_lin_dly+1):
            if quiet <3:
1289
                print ("%d(0x%x):"%(ldly,combine_delay(ldly)),end=" ")
1290
                sys.stdout.flush()
1291 1292 1293
            elif quiet < 5:
                print (".",end="")
                sys.stdout.flush()
1294
            meas_data[ldly] = patt_dqs_step(ldly)
1295
        if quiet < 5:
1296 1297 1298
            print ()

        if quiet < 3:
1299
            print("\n\nMeasured data, integer portion, measured with %s steps"%(("fine","primary")[compare_prim_steps]))
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
            print ("DQS",end=" ")
            for f in ('ir','if','or','of'):
                for b in range (16):
                    print ("%s_%d"%(f,b),end=" ")
            print()        
            for ldly, data in enumerate(meas_data):
                print("%d"%ldly,end=" ")
                if data:
                    for typ in ((0,0),(0,1),(1,0),(1,1)):
                        for pData in data: # 16 DQs, each None nor a pair of lists for inPhase in (0,1), each a pair of edges, each a pair of (dly,diff)
                            if pData:
                                if pData[typ[0]] and pData[typ[0]][typ[1]]:
                                    print ("%d"%pData[typ[0]][typ[1]][0],end=" ")
                                    '''
                                    try:
                                        print ("%d"%pData[typ[0]][typ[1]][0],end=" ")
                                    except:
                                        print (".", end=" ")
                                    '''
                                else:
                                    print ("?", end=" ")
                            else:
                                print ("x",end=" ")
1323
                        
1324
                print()
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
        if quiet < 2:
            print("\n\nMasked measured data, integer portion, measured with %s steps"%(("fine","primary")[compare_prim_steps]))
            for f in ('ir','if','or','of'):
                for b in range (16):
                    print ("%s_%d"%(f,b),end=" ")
            print()        
            for ldly, data in enumerate(meas_data):
                print("%d"%ldly,end=" ")
                if data:
                    for typ in ((0,0),(0,1),(1,0),(1,1)):
                        for pData in data: # 16 DQs, each None nor a pair of lists for inPhase in (0,1), each a pair of edges, each a pair of (dly,diff)
                            if pData:
                                if pData[typ[0]] and pData[typ[0]][typ[1]] and (not pData[typ[0]][typ[1]][1] is None):
                                    print ("%d"%pData[typ[0]][typ[1]][0],end=" ")
                                    '''
                                    try:
                                        print ("%d"%pData[typ[0]][typ[1]][0],end=" ")
                                    except:
                                        print (".", end=" ")
                                    '''
                                else:
                                    print ("?", end=" ")
                            else:
                                print ("x",end=" ")
                        
                print()
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
                    
        if quiet < 2:
            print ("\nDifferences from 0.5:")

            print ("DQS",end=" ")
            for f in ('ir','if','or','of'):
                for b in range (16):
                    print ("%s_%d"%(f,b),end=" ")
            print()        
            for ldly, data in enumerate(meas_data):
                print("%d"%ldly,end=" ")
                if data:
                    for typ in ((0,0),(0,1),(1,0),(1,1)):
                        for pData in data: # 16 DQs, each None nor a pair of lists for inPhase in (0,1), each a pair of edges, each a pair of (dly,diff)
                            if pData:
1366
                                if pData[typ[0]] and pData[typ[0]][typ[1]] and (not pData[typ[0]][typ[1]][1] is None):
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
                                    print ("%.2f"%pData[typ[0]][typ[1]][1],end=" ")
                                    '''
                                    try:
                                        print ("%d"%pData[typ[0]][typ[1]][0],end=" ")
                                    except:
                                        print (".", end=" ")
                                    '''
                                else:
                                    print ("?", end=" ")
                            else:
                                print ("x",end=" ")
                        
                print()
1380 1381 1382 1383
        if quiet < 3:
            print("\n\nMeasured data, comparing current data with the earlier by one %s step"%(("fine","primary")[compare_prim_steps]))
            print("When the fractional (second in the tuple) data is exactly -0.5, the actual result is in the range %s from the integer delay"%
                  (("+0.0..+1.0","+0.0..+%d"%NUM_FINE_STEPS)[compare_prim_steps]))
1384 1385 1386
            print ("meas_data=[")
            for d in meas_data:
                print("%s,"%(str(d)))
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
            print("]")
        rdict={"patt_prim_steps":    compare_prim_steps,
               "patt_meas_data":     meas_data} # TODO: May delete after LMA fitting
        self.adjustment_state.update(rdict)

    def measure_dqs_idly_phase(self,
                               compare_prim_steps = True, # while scanning, compare this delay with 1 less by primary(not fine) step,
                                                # save None for fraction in unknown (previous -0.5, next +0.5) 
                               frac_step=0.125,
                               sel=1,
                               quiet=1):
        """
        Scan phase and find DQS input delay value to find when
        the result changes (it is caused by crossing clock boundarty from extrenal memory device derived
        to system-synchronous one
        cmda_odelay should be already calibrated, refresh will be turned on.
        Uses random/previously written pattern in one memory block (should have some varying data
1404
        @param quiet reduce output
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
        """
        
        try:
            dqi_dqsi=self.adjustment_state['dqi_dqsi']
        except:
            print ("No DQ IDELAY vs. DQS IDELAY data available, exiting")
            return
        # Mark DQS idelay values that have all DQ delays valid 
        dqsi_valid={} #[None]*NUM_DLY_STEPS
        for k,v in dqi_dqsi.items():
            if v:
                dqsi_valid[k]=[False]*NUM_DLY_STEPS
                for dly in range(NUM_DLY_STEPS):
                    if v[dly]:
                        for d in v[dly]:
                            if d is None:
                                break
                        else: # All values are not None
                            dqsi_valid[k][dly]=True
        if not dqsi_valid:
            print ("No Valid DQ IDELAY vs. DQS IDELAY data is available, exiting")
            return
        if quiet <1:
            print ('dqi_dqsi=%s'%(str(dqi_dqsi)))
            print("\n\n")
        if quiet <2:
            print ('dqsi_valid=%s'%(str(dqsi_valid)))
        dqsi_lohi={}
        for k,vdly in dqsi_valid.items():
            if quiet <2:
                print ("k='%s', vdly=%s"%(k,str(vdly)))
            for i,v in enumerate(vdly):
                if v:
                    low=i
                    break
            else:
                print ("Could not find valid data in dqsi_valid[%s]=%s"%(k,str(vdly)))
                continue
            for i in range(low+1,NUM_DLY_STEPS):
                if not vdly[i]:
                    high=i
                    break
            else:
                high= NUM_DLY_STEPS-1
            dqsi_lohi[k]=(low,high)       
        if quiet <2:
            print ('dqsi_valid=%s'%(str(dqsi_valid)))
        if quiet <3:
            print ('dqsi_lohi=%s'%(str(dqsi_lohi)))
         

        brc=(5,        # 3'h5,     # bank
             0x1234,   # 15'h1234, # row address
             0x100)     # 10'h100   # column address
        nrep=8 # number of 8-bursts to compare (actual will have 3 more, first/last will be discarded
        timing=self.x393_mcntrl_timing.get_dly_steps()
        #steps={'DLY_FINE_STEP': 0.01, 'DLY_STEP': 0.078125, 'PHASE_STEP': 0.022321428571428572, 'SDCLK_PERIOD': 2.5}
        dly_step=int(NUM_FINE_STEPS*frac_step*timing['SDCLK_PERIOD']/timing['DLY_STEP']+0.5)
        numPhaseSteps= int(timing['SDCLK_PERIOD']/timing['PHASE_STEP']+0.5)
        step180= int(NUM_FINE_STEPS*0.5* timing['SDCLK_PERIOD'] / timing['DLY_STEP'] +0.5)                                                                                                                                                                                                                 
        if quiet<2:
            print ("timing)=%s, dly_step=%d step180=%d"%(str(timing),dly_step,step180))
        self.x393_pio_sequences.set_read_block(*(brc+(nrep+3,sel))) # set sequence once
1468 1469
        #prepare writing block:
        wdata16=(0,0,0xffff,0xffff)*(2*(nrep+3)) # Data will have o/1 transitions in every bit, even if DQ_OPDELAY to DQS_OPDELAY is not yet adjusted
1470
        wdata32=convert_mem16_to_w32(wdata16)
1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
        self.x393_mcntrl_buffers.write_block_buf_chn(0,0,wdata32,quiet) # fill block memory (channel, page, number)
        self.x393_pio_sequences.set_write_block(*(brc+(nrep+3,0,sel))) # set sequence once
        cmda_bspe=self.adjustment_state['cmda_bspe']
        wlev_dqs_bspe=self.adjustment_state['wlev_dqs_bspe']
        for phase in range(numPhaseSteps):
            try:
                dqs_odelay=[wlev_dqs_bspe[lane][phase]['ldly'] for lane in range(len(wlev_dqs_bspe))]
                cmda_odelay=cmda_bspe[phase]['ldly']
                if (not None in dqs_odelay) and (not cmda_odelay is None):
                    break
            except:
                pass    
        else:
            raise Exception("BUG: could not find phase that has valid cmda_odelay and dqs_odelay")
        phase_ok=self.set_phase_with_refresh( # check result for not None
                           phase,
                           quiet)
        if not phase_ok:
            raise Exception("BUG: Failed set_phase_with_refresh(%s)"%(str(phase)))
1490
        self.x393_mcntrl_timing.axi_set_dqs_odelay(combine_delay(dqs_odelay),quiet=quiet)
1491 1492 1493 1494 1495
        self.x393_pio_sequences.write_block() #page= 0, wait_complete=1)

        
       
        
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509
        
        def dqsi_phase_step (phase):
            dqsi_cache=[None]*NUM_DLY_STEPS # cache for holding already measured delays. None - not measured, 0 - no data, [[]..[]]
            def measure_dqsi(dqs_idly,branch,force_meas=False):
                if not dqsi_valid[branch]:
                    return None
                if (dqs_idly > len(dqsi_cache)) or (dqs_idly <0 ):
                    print ("dqs_idly=%d, dqsi_cache=%s"%(dqs_idly,str(dqsi_cache)))
                try:
                    dqsi_cache[dqs_idly] 
                except:
                    print ("dqs_idly=%d, dqsi_cache=%s"%(dqs_idly,str(dqsi_cache)))
                       
                if (dqsi_cache[dqs_idly] is None) or force_meas:
1510 1511
                    self.x393_mcntrl_timing.axi_set_dqs_idelay(combine_delay(dqs_idly),quiet=quiet)
                    self.x393_mcntrl_timing.axi_set_dq_idelay(combine_delay(dqi_dqsi[branch][dqs_idly]),quiet=quiet)
1512 1513 1514 1515
                    buf=self.x393_pio_sequences.read_block(4 * (nrep+1) +2,
                                                           (0,1)[quiet<1], #show_rslt,
                                                           1) # wait_complete=1)
                    buf= buf[4:(nrep*4)+4] # discard first 4*32-bit words and the "tail" after nrep*4 words32
1516
                    patt=convert_w32_to_mem16(buf)# will be nrep*8 items
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
                    dqsi_cache[dqs_idly]=patt
                    if quiet < 1:
                        print ('measure_phase(%d,%s) - new measurement'%(phase,str(force_meas)))
                else:
                    patt=dqsi_cache[dqs_idly]
                    if quiet < 1:
                        print ('measure_patt(%d,%s) - using cache'%(phase,str(force_meas)))
                return patt
            def get_bit_diffs(dqs_idly0,dqs_idly1,branch):
                patt0=measure_dqsi(dqs_idly0,branch)
                patt1=measure_dqsi(dqs_idly1,branch)
                if (patt0 is None) or (patt1 is None):
                    raise Exception("Tried to compare invalid(s): dqs_idly0=%d, dqs_idly1=%d, branch=%s"%(dqs_idly0, dqs_idly1, branch))
                rslt=[0]*16
                for i in range (nrep*8): # with 8 nursts - 64 x16-bit words
                    diffs=patt0[i] ^ patt1[i]
                    for b in range(len(rslt)):
                        rslt[b]+= (diffs >> b) & 1
                return rslt        
            def get_lane_diffs(dqs_idly0,dqs_idly1,branch):
                diffs= get_bit_diffs(dqs_idly0,dqs_idly1,branch)
#                lane_diffs=[0]*(len(diffs)//8)
                lane_diffs=[]
                for lane in range(len(diffs)//8):
                    num_diffs=0   
                    for b in range(8):
                        num_diffs += (0,1)[diffs[8*lane+b] != 0]
                    lane_diffs.append(num_diffs)
                if quiet <3:
                    print ("%d ? %d : %s"%(dqs_idly0,dqs_idly1,lane_diffs))

                return lane_diffs
            def get_lane_adiffs(dqs_idly0,dqs_idly1,branch): # Assuming all 8 bits differ in the read data - check it in a single block? Write pattern?
                diffs=get_lane_diffs(dqs_idly0,dqs_idly1,branch)
                    
                return ((diffs[0]-4)/4.0,(diffs[1]-4)/4.0)
            # Set phase
            phase_ok=self.set_phase_with_refresh( # check result for not None
                               phase,
                               quiet)
            if not phase_ok:
1558
                return None # no valid CMDA ODELAY exists for this phase 
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664
            # try branches (will exit on first match)
            for branch in dqsi_lohi.keys():
                low=dqsi_lohi[branch][0]
                high=dqsi_lohi[branch][1]
                # start with low dqs idelay and increase it by 1 primary step until getting 2 results with no bit differences
                # (using both byte lanes now)
                for idly1 in range(low+NUM_FINE_STEPS,high,NUM_FINE_STEPS):
                    diffs=get_lane_diffs(idly1-NUM_FINE_STEPS,idly1,branch)
                    if diffs == [0,0]: # no bit diffs in both byte lanes
                        low=idly1
                        break
                else: #failed to find two delays to get the same read results (no bit differences in both lanes)
                    continue
                # got both byte lanes with no difference, now try to find dqs_idelay delay where both bytes differ
                for idly in range(low,high,dly_step):
                    idly1=min(idly+dly_step,high)
                    diffs=get_lane_diffs(low,idly1,branch)
                    if (diffs[0] != 0) and (diffs[1] != 0):
                        high=idly1
                        break
                    elif (diffs[0] == 0) and (diffs[1] == 0):
                        low=idly1 # move low higher
                else: #failed to find another delay to get different read results (both myte lanes have bit differences
                    continue
                if quiet <3:
                    print ("0: low=%d, high=%d"%(low,high))
                low_safe=low # safe low
                # now find marginal dqs idelay for each byte lane by dividing (low,high) interval
                #reduce low,high range for combined lanes
                dly = high
                while low < dly: # first adjust low
                    dly_next = (low+dly) // 2
                    diffs=get_lane_diffs(low,dly_next,branch)
                    if (diffs[0] != 0) and (diffs[1] != 0):
                        dly = dly_next
                        high= dly
                    elif (diffs[0] == 0) and (diffs[1] == 0):
                        if low == dly_next:
                            break
                        low = dly_next # move low higher
                    else: # one byte matches, other - not (uncertain)
                        dly = dly_next
                dly = low
                while dly < high: # now adjust high
                    dly_next = (high+dly) // 2
                    diffs=get_lane_diffs(low_safe,dly_next,branch)
                    if (diffs[0] != 0) and (diffs[1] != 0):
                        high= dly_next
                    else: 
                        if dly == dly_next:
                            break
                        dly = dly_next # move low higher
                #low, high are now closer, now scan and store (delay,num_bits) for each lane
                #May be check maximal number of bits that mismatch for each lane? Now assuming that it can be up to all 8
#                low -= NUM_FINE_STEPS
#                low =  max(dqsi_lohi[branch][0], low - NUM_FINE_STEPS ) # try to move lower by the fine steps interval, if possible
#                high = min(dqsi_lohi[branch][1], high+ NUM_FINE_STEPS ) # try to move higher by the fine steps interval, if possible
                if quiet <3:
                    print ("1: low=%d(%d), high=%d"%(low,low_safe,high))
                high = min(dqsi_lohi[branch][1], high+ NUM_FINE_STEPS ) # try to move higher by the fine steps interval, if possible
                if quiet <3:
                    print ("2: low=%d(%d), high=%d"%(low,low_safe,high))
                rslt=[]
                bestDly=[None]*2 # [low_safe]*2 # otherwise may fail - check it?
                bestDiffs=[None]*2
                comp_step=(1,NUM_FINE_STEPS)[compare_prim_steps]
                for dly in range (low, high+1):
                    ref_dly= dly-comp_step
                    if ref_dly < low_safe:
                        continue
                    if quiet <2:
                        print ("dly=%d, ref_dly=%d"%(dly, ref_dly),end=" ")
                    adiffs= get_lane_adiffs(low_safe,dly,branch)
                    adiffs_ref=get_lane_adiffs(low_safe,ref_dly,branch)
                    
                    for lane in range(len(adiffs)):
                        diffs_prev_this=(adiffs_ref[lane],adiffs[lane])
                        if (diffs_prev_this[0] <= 0) and (diffs_prev_this[1] >= 0): 
                            if abs(diffs_prev_this[0]) <= abs(diffs_prev_this[1]): # store previos sample
                                if (bestDiffs[lane] is None) or (abs (diffs_prev_this[0]) < abs(bestDiffs[lane])):
                                    bestDly[lane]=ref_dly # dly-1/dly-NUM_FINE_STEPS
                                    bestDiffs[lane]=diffs_prev_this[0]
                            else:
                                if (bestDiffs[lane] is None) or (abs (diffs_prev_this[1])<abs(bestDiffs[lane])):
                                    bestDly[lane]=dly # dly-1
                                    bestDiffs[lane]=diffs_prev_this[1]
                    if (adiffs[0] > 0) and (adiffs[1] > 0):
                        break # no need to continue, data got already 
                for lane in range(len(adiffs)):
                    if bestDiffs[lane] == -1.0:
                        bestDiffs[lane] = None # single step jumps from none to all            
                    rslt.append((bestDly[lane],bestDiffs[lane],branch[0])) # adding first letter of branch name
                    if quiet <3:
                        print ("bestDly[%d]=%s, bestDiffs[%d]=%s, branch=%s"%(lane,str(bestDly[lane]),lane,str(bestDiffs[lane]),branch))
                if quiet <3:
                    print ('dly=%d rslt=%s'%(dly,str(rslt)))                    
                        
                if quiet < 2:
                    for i,d in enumerate(dqsi_cache):
                        if d:
                            print ("%d %s  %d: %s"%(phase,branch,i,str(d)))
                return rslt
            return None # All Early/Nominal/Late variants were exhausted, did not find critical DQS inoput delay for this phase value 
        # body of the  measure_dqs_idly_phase()
        dqsi_vs_phase=[]
        for phase in range (numPhaseSteps):
1665
            if quiet <2:
1666 1667
                print ("====== PHASE=%d ======"%(phase))

1668
            elif quiet < 3:
1669 1670
                print ("%d:"%(phase),end=" ")
                sys.stdout.flush()
1671 1672 1673
            elif quiet < 5:
                print (".",end="")
                sys.stdout.flush()
1674 1675
            dqsi_vs_phase.append(dqsi_phase_step (phase))
                    
1676
        if quiet < 3 :
1677 1678 1679 1680 1681 1682 1683 1684
            print ("dqsi_vs_phase=%s"%(str(dqsi_vs_phase)))
            print("Phase DQSI0 DQSI1 diff0 diff1 branch0 branch1")
            for phase,v in enumerate(dqsi_vs_phase):
                print("%d"%(phase), end=" ")
                if v:
                    print ("%s %s %s %s %s %s"%(str(v[0][0]),str(v[1][0]),str(v[0][1]),str(v[1][1]), v[0][2], v[1][2]))
                else:
                    print()
1685 1686
        elif quiet < 5:
            print ()
1687 1688 1689 1690 1691
        self.adjustment_state['dqsi_vs_phase']=      dqsi_vs_phase
        self.adjustment_state['dqsi_vs_phase_steps']=compare_prim_steps            
        return dqsi_vs_phase        
                
                    
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
    def measure_dqo_dqso(self,
                               compare_prim_steps = True, # while scanning, compare this delay with 1 less by primary(not fine) step,
                                                # save None for fraction in unknown (previous -0.5, next +0.5) 
                               frac_step=0.125,
                               sel=1,
                               quiet=1,
                               start_dly=0): #just to check dependence
        """
        Scan dqs odelay (setting phase appropriately), write
        0x0000/0xffff/0x0000/0xffff (same as fixed pattern) data and read it with known dqsi/dqi
        values (maybe even set different phase for read?), discarding first and last 1.5 8-bursts
        Measure 4 different transitions for each data bit (rising DQS/rising DQ, falling DQS/falling DQ,
        rising DQS/falling DQ and falling DQS/rising DQ (that allows to measure duty cycles fro both
        DQS and DQ lines
1706
        @param quiet reduce output
1707
        """
1708
#        self.load_hardcoded_data() # TODO: REMOVE LATER
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
        try:
            dqi_dqsi=self.adjustment_state['dqi_dqsi']
        except:
            print ("No DQ IDELAY vs. DQS IDELAY data available, exiting")
            return
        dqsi_phase=self.adjustment_state['dqsi_phase']
        num_lanes=len(dqsi_phase)
        cmda_bspe=self.adjustment_state['cmda_bspe']
        wlev_dqs_bspe=self.adjustment_state['wlev_dqs_bspe']
        brc=(5,        # 3'h5,     # bank
             0x1234,   # 15'h1234, # row address
             0x100)     # 10'h100   # column address
        nrep=8 # number of 8-bursts to compare (actual will have 3 more, first/last will be discarded
        extraTgl=0 # data is repetitive,so extra toggle is not needed (an there is an extra 8-burst anyway)
        timing=self.x393_mcntrl_timing.get_dly_steps()
        dly_step=int(NUM_FINE_STEPS*frac_step*timing['SDCLK_PERIOD']/timing['DLY_STEP']+0.5)
        numPhaseSteps= int(timing['SDCLK_PERIOD']/timing['PHASE_STEP']+0.5)
        step180= int(NUM_FINE_STEPS*0.5* timing['SDCLK_PERIOD'] / timing['DLY_STEP'] +0.5)                                                                                                                                                                                                                 
        
        
        #Calculate phase for the best match for the DQS output delay (for both lanes - use average). If
        # solution for different lanes point to the opposite ends of the phase range - keep previous
        # do not look outside of +/- frac_step 
        def get_phase_for_dqso():
            phase_dqso=[]
            last_phase=0
            for dly in range(NUM_DLY_STEPS):
                best_phases= []
                for lane in range(num_lanes):
                    best_diff= frac_step*NUM_DLY_STEPS
                    best_phase=None
                    for phase in range(numPhaseSteps):
                        try:
                            dly_phase=wlev_dqs_bspe[lane][phase]['ldly']
                        except:
                            dly_phase=None
                        if (not dly_phase is None) and (cmda_bspe[phase % numPhaseSteps] is None): # check that CMDA odelay exists for this phase
                            dly_phase=None
                        """    
                        # Make sure that dqsi and dqi exist for the phase
                        if dqsi_dqi_for_phase[phase] is None:
                            dly_phase=None
                        if dly==65:
                            print("lane=%d dly=%d, dqsi_dqi_for_phase[%d]=%s (%s)"%(lane, dly,phase,str(dqsi_dqi_for_phase[phase]),str(dly_phase)))
                        """                            
                        if not dly_phase is None:
                            adiff=abs(dly_phase-dly)
                            if adiff < best_diff:
                                best_diff = adiff
                                best_phase = phase
                    if best_phase is None:
                        best_phases=None # At least one of the lanes does not have an acceptable solution (should not normally happen)
                        break
#                    print("lane=%d dly=%d, best_phase=%s best_diff=%s"%(lane, dly,str(best_phase),str(best_diff)))                        
                    best_phases.append(best_phase)
                if best_phases is None:
                    phase_dqso.append(None)
                    continue
                else:
                    diff_per= max(best_phases)-min(best_phases) > numPhaseSteps/2 # different ends
                        #find which one is closer to last_phase, modify the other one by +/- period
                    sp=0.0
                    for lane in range(num_lanes):
                        if diff_per and (best_phases[lane] >= numPhaseSteps/2):
                            best_phases[lane] -= numPhaseSteps
                        sp+=best_phases[lane]
                    sp /= num_lanes # average phase for all lanes
                    sp=int(round(sp))
                    # only if results for lanes are on the different ends - if they agree - just take an average
                    if diff_per and (abs(sp-last_phase) > abs(sp+numPhaseSteps-last_phase)):
                        sp += numPhaseSteps 
                    sp=max(sp,0)
                    # May be that both best phases were OK, but their average falls into the gap - find closest
                    if dqsi_dqi_for_phase[sp] is None:
                        best_dist=numPhaseSteps
                        best_phase=None
                        for phase in range(numPhaseSteps):
                            if not dqsi_dqi_for_phase[phase] is None:
                                dist = min(abs(phase-sp),abs(phase+numPhaseSteps-sp),abs(phase-numPhaseSteps-sp))
                                if dist < best_dist:
                                    best_dist=dist
                                    best_phase=phase
                        if best_dist >= frac_step*numPhaseSteps:
#                            print("Could not find phase substitute for %d, %s is too far "%(sp, str(best_phase)))
                            best_phase=None
#                        else:
#                            print("Using substitute %d for %d"%(best_phase,sp))
                        sp=  best_phase 

                    sp=min(sp,numPhaseSteps-1)
#                    print("dly=%d best_phases=%s"%(dly, str(best_phases)))    
                    phase_dqso.append(sp)
            return phase_dqso
        def get_dqsi_dqi_for_phase():
            # Mark DQS idelay values that have all DQ delays valid
            # for each phase check that DQS input delay value exists and store DQi varinat (early/nominal/late
            dqsi_dqi_phase=[None]*numPhaseSteps
            inv_vars=('early','late') 
            for phase in range (numPhaseSteps):
#                print (phase, end=" ")
                dqsi=[]
                for lane_data in dqsi_phase:
                    dqsi.append(lane_data[phase])
                if None in dqsi:
                    continue # Keep False
                for k, dqi_dqsi_v in dqi_dqsi.items():
#                    print (" k=%s"%(k), end=" ")
                    if not dqi_dqsi_v:
                        continue # need to continue with next phase
                    dqi=[]
                    for lane, dqsi_lane in enumerate(dqsi):
#                        print (" lane=%d"%(lane), end=" ")
                        dq_lane=dqi_dqsi_v[dqsi_lane] #list of 16 DQ values for dqsi_lane or None 
                        if (dq_lane is None) or (None in dq_lane[8*lane:8*(lane+1)]):
                            break
                        dqi += dq_lane[8*lane:8*(lane+1)]
                    else:
                        dqsi_dqi_phase[phase]={'dqsi':dqsi,
                                               'dqi':dqi,
                                               'invert':k in inv_vars,
                                               'variant':k } # dqsi - a pair of dqs input delays, dqi - dq delays for the same phase
                        break
#                print()
            return dqsi_dqi_phase
            
        def dqs_step(dqs_lin):
            patt_cache=[None]*NUM_DLY_STEPS # cache for holding already measured delays
            def measure_block(dly,invert_patt, force_meas=False):
                if (patt_cache[dly] is None) or force_meas:
1838
                    self.x393_mcntrl_timing.axi_set_dq_odelay(combine_delay(dly),quiet=quiet)
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850