x393_mcntrl_adjust.py 299 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
NUM_DLY_STEPS =NUM_FINE_STEPS * 32 # =160
DQI_KEY='dqi'
DQO_KEY='dqo'
52 53 54
DQSI_KEY='dqsi'
DQSO_KEY='dqso'
CMDA_KEY='cmda'
55
ODD_KEY='odd'
56 57
SIG_LIST=[CMDA_KEY,DQSI_KEY,DQI_KEY,DQSO_KEY,DQO_KEY]
DFLT_DLY_FILT=['Best','Early'] # default non-None filter setting to select a single "best" delay/delay set 
58 59 60 61 62 63 64 65 66 67

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
68
    adjustment_state={}
69 70 71 72
    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)
73 74
#        self.x393_axi_tasks=      X393AxiControlStatus(debug_mode,dry_mode)
        self.x393_axi_tasks=      x393_axi_control_status.X393AxiControlStatus(debug_mode,dry_mode)
75 76 77
        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)
78
#        self.__dict__.update(VerilogParameters.__dict__["_VerilogParameters__shared_state"]) # Add verilog parameters to the class namespace
79
        try:
80
            self.verbose=vrlg.VERBOSE
81 82
        except:
            pass
83 84
#keep as command        

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    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()
102

103
    def missing_dqs_notused(self,
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
                     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
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
        return False
    
    def _get_dqs_dly_err(self,
                         phase,
                         delays,
                         errors):
        '''
        extract dqsi/dqso data for a single phase as a dictionary with keys - signed integer period branches,
        values - list of 2 lane delays
        Returns either this dictionary or a tuple of this one and corresponding worst errors. Or None!
        '''
        periods=None # needed just for PyDev?
        for linedata in delays:
            try:
                periods &= set(linedata[phase].keys())
            except:
                try:
                    periods = set(linedata[phase].keys())
                except:
                    pass
        if not periods:
            return None # no branch has all lines
        phaseData={}
        #Errors may be common for the whole 8-bit lane
        if not errors is None:
            phaseErrs={}
            if len(delays)==8*len(errors):
                errors=[errors[i//8] for i in range(len(delays))]
        for branch in periods:
            phaseData[branch]=[]
            if not errors is None:
                phaseErrs[branch]=0.0
                for lineData,lineErr in zip(delays,errors):
                    try:
                        phaseData[branch].append(lineData[phase][branch])
                    except:
                        phaseData[branch].append(None)
                    try:
                        phaseErrs[branch]=max(phaseErrs[branch],abs(lineErr[phase][branch]))
                    except:
                        pass
                        
            else:
                for lineData in delays:
                    phaseData[branch].append(lineData[phase][branch])
        if errors is None:
            return phaseData
        else:
            return (phaseData,phaseErrs)
    '''    
    def combine_dq_dqs(self,
                       outMode=None,
                       quiet=1):
178
        """
179
        @param outmode False - dqi/dqsi, True - dgo/dqso, None - both
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 207 208
        if outMode is None:
            self.combine_dq_dqs(False)
            self.combine_dq_dqs(True)
        elif outMode:
            delays, errors= self._combine_dq_dqs(dqs_data=self.adjustment_state['dqso_phase_multi'],
                                                 dq_enl_data=self.adjustment_state["dqo_dqso"],
                                                 dq_enl_err = self.adjustment_state["maxErrDqso"],
                                                 quiet=quiet)
            self.adjustment_state['dqo_phase_multi'] = delays
            self.adjustment_state["dqo_phase_err"] =   errors
        elif outMode:
            delays, errors= self._combine_dq_dqs(dqs_data=self.adjustment_state['dqsi_phase_multi'],
                                                 dq_enl_data=self.adjustment_state["dqi_dqsi"],
                                                 dq_enl_err = self.adjustment_state["maxErrDqsi"],
                                                 quiet=quiet)
            self.adjustment_state['dqi_phase_multi'] = delays
            self.adjustment_state["dqi_phase_err"] =   errors
        else:
            self.combine_dq_dqs(False)
            self.combine_dq_dqs(True)
    '''
                
    def _combine_dq_dqs(self,
                       dqs_data,
                       dq_enl_data,
                       dq_enl_err,
#                       target="dqsi",
                       quiet=1):
209
        """
210 211 212 213 214 215 216 217 218
        Create possibly overlapping branches of delay/error data vs phase for dqi or dqo
        @param dqs_data     self.adjustment_state['dqs?_phase_multi'] (dqs errors are not used here)
        @param dq_enl_data  self.adjustment_state["dq?_dqs?"]  delay[ENL-branch][dqs_dly][bit] ('None' may be at any level)
        @param dq_enl_err   self.adjustment_state["maxErrDqs?"] errorPS[ENL-branch][dqs_dly][bit] ('None' may be at any level)
#        @param target - one of "dqsi" or "dqso"
        @param quiet reduce output
        @return dqi/dqo object compatible with the input of get_delays_for_phase():
        (data[line][phase]{(p_dqs,p_dq):delay, ...}, err[lane][phase]{(p_dqs,p_dq):delay, ...}
        Errors are per-lane, not per line!
219
        """
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
        #
#        if quiet <2:
#            print("dq_enl_data=",dq_enl_data)
#            print("\ndqs_data=",dqs_data)
#           print("\ndqs_data[0]=",dqs_data[0])
#            print("\nlen(dqs_data[0])=",len(dqs_data[0]))
            
        enl_dict={'early':-1,'nominal':0,'late':1}
#        for enl_branch in 
        numPhaseSteps= len(dqs_data[0])
        for v in dq_enl_data.values():
            try: # branch data
                for p in v: # phase data
                    try:
                        numLines=len(p)
                        break
                    except:
                        pass
                break
239
            except:
240 241 242 243 244 245 246 247 248 249 250 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 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
                pass
#        numLanes=numLines//8
#                    for enl_branch in dq_enl_data:

        if quiet <2:
#            print ("numLines=",numLines," numLanes=",numLanes," numPhaseSteps=",numPhaseSteps)
            print ("numLines=",numLines," numPhaseSteps=",numPhaseSteps)
        data=[[] for _ in range(numLines)] # each element is a new instance of a list
        errs=[[] for _ in range(numLines//8)] # each element is a new instance of a list
        for phase in range(numPhaseSteps):
            
            line_data=[{} for _ in range(numLines)] # each element is a new instance of a dict
            line_errs=[{} for _ in range(numLines//8)] # each element is a new instance of a dict
            phaseData=self._get_dqs_dly_err(phase,
                                            dqs_data,
                                            None)
            if quiet <2:
                print ("===== phase=%d phaseData=%s"%(phase,str(phaseData)))
            if not phaseData is None:
                periods_dqs=phaseData.keys()
                periods_dqs.sort()

                for period_dqs in periods_dqs: # iterate through all dqs periods
                    dly_dqs=phaseData[period_dqs] # pair of lane delays
                    for enl_branch in dq_enl_data:
                        if not enl_branch is None: 
                            period_dq=enl_dict[enl_branch]
                            period_key=(period_dqs,period_dq)
                            if quiet <2:
                                print ("period_dqs=%d enl_branch=%s period_key=%s, dly_dqs=%s"%(period_dqs,enl_branch,str(period_key),str(dly_dqs)))
                                try:
                                    print ("dq_enl_data['%s][%d]=%s"%(enl_branch,dly_dqs[0], str(dq_enl_data[enl_branch][dly_dqs[0]])))
                                except:
                                    print ("dq_enl_data['%s]=%s"%(enl_branch, str(dq_enl_data[enl_branch])))
                                try:
                                    print ("dq_enl_data['%s][%d]=%s"%(enl_branch,dly_dqs[1], str(dq_enl_data[enl_branch][dly_dqs[0]])))
                                except:
                                    pass
                            for line in range(numLines):
                                try:
                                    line_data[line][period_key]=dq_enl_data[enl_branch][dly_dqs[line//8]][line]
                                except:
                                    pass
                            for lane in range(numLines//8):
                                try:
                                    line_errs[lane][period_key]=dq_enl_err [enl_branch][dly_dqs[lane]][lane]
                                except:
                                    pass
                            if quiet <2:
                                print ("line_data=",line_data)
                                print ("line_errs=",line_errs)
                                
                
            for line,d in zip(data,line_data):
                if d: # not empty dictionary
                    line.append(d)
                else:
                    line.append(None)        
            for line,d in zip(errs,line_errs):
                if d:
                    line.append(d)
                else:
                    line.append(None)
        if quiet <3:
            print ("\ndq_dqs_combined_data=",data)
            print ("\ndq_dqs_combined_errs=",errs)
            print('len(data)=',len(data),'len(data[0])=',len(data[0]))
            print('len(errs)=',len(errs),'len(errs[0])=',len(errs[0]))
            print("")
            for phase in range(len(data[0])):
                print ("%d"%(phase), end=" ")
                for line in range(len(data)):
                    print("%s"%(str(data[line][phase])), end=" ")
                for lane in range(len(errs)):
                    print("%s"%(str(errs[lane][phase])), end=" ")
                print()
        return (data,errs)
    
318
        
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
    def get_delays_for_phase(self,
                          phase = None,
                          list_branches=False,
                          target=DQSI_KEY,
                          b_filter=None, # will default to earliest (lowest delay) branch, same as 'e',
                          cost=None, # if None - will default to NUM_FINE_STEPS, if 0 - will keep it 
                          quiet = 1):
        """
        Get list of "optimal" per-bit delays for DQSI,dqso and cmda
        always use the same branch
        @param phase phase value, if None - return a list for all phases
        @parame list_branches - return (ordered) list of available branches, not delays. If it is a string starting with E<rr>,
                                return worst errors in ps instead of the data
        @param target - one of "dqsi","dqso", "dqi", "dqo" or "cmda"
        @param b_filter - filter to limit clock-period 'branches',  item or a list/tuple of items,
             consisting of any (or combination) of:
             a)word starting with 'E','B','L'  (E<arly> - branch with smallest delay,
             L<ate> - largest delay, B<best> (lowest error) - no EBL defaults to "early"
             If both Best and Late/Early are present, extra period adds cost*clk_period/NUM_DLY_STEPS
             a1) word starting with 'A' (A<ll>) - return results even if some lines are None
             b) float number - maximal allowed error in ps and
             c) one or several specific branches (signed integers)
             If b_filter is None, earliest (lowest delay) branch will be used
        @param cost TODO: check with multiple overlapping low-error branches. This parameter allows to select between
                    multiple "good" (low-error) branches that will become availble when clock period will be lower than
                    delay range. When selecting lowest error it adds cost for lower/higher delays, such that delay of the
                    full clock period will add/subtract cost/NUM_DLY_STEPS of the period to effective error. With default
                    cost==5 it will "punish" with 1/32 period for using "wrong" period branch 
        @param quiet  reduce output
        @return - a list of delays for a specific phase or None (if none available/match f_filter) or
                  a list of lists of delays/None-s for all phases (if phase is not specified) or
                  a list of period branches (signed integers) for a specific phase/None if list_branches is True or
                  a list of lists/None-s for all phases if phase is None and list_branches is True
        """
         
        """
        #TODO: REMOVE next temporary lines
        self.load_hardcoded_data()
        self.proc_addr_odelay(True, 200.0, 4)
        self.proc_dqsi_phase ('All', 50, 0, 0.0, 200, 3)
        self.proc_dqso_phase ('All', 50, 0, 0.0, 200, 3)
        """
        if cost is None:
            cost=NUM_FINE_STEPS
        return_error=False
364
        try:
365 366 367
            if list_branches.upper()[0]=='E':
                return_error=True
                list_branches=False
368
        except:
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
            pass

        if quiet < 2:
            print ("processing get_delays_for_phase(phase=%s,list_branches=%s,target='%s',b_filter=%s)"%(str(phase),
                                                                                                         str(list_branches),
                                                                                                         str(target),
                                                                                                         str(b_filter)))
        #parse b-filter
        if not isinstance (b_filter, (list,tuple)):
            b_filter=[b_filter]
        periods_set=set()
        highDelay=False
        lowDelay=False
        minError=False
        maxErrPS=0.0
        allGood=True
        for item in b_filter:
            if not item is None:
                if isinstance(item,float):
                    maxErrPS=item
                elif isinstance(item,(int,long,tuple)):
                    periods_set.add(item)
                elif isinstance(item,str) and (len(item)>0) and (item.upper()[0] in "EBLA"):
                    if item.upper()[0] == "L":
                        highDelay=True
                    elif item.upper()[0] == "B":
                        minError=True
                    elif item.upper()[0] == "E":
                        lowDelay=True
                    elif item.upper()[0] == "A":
                        allGood=False
                    else:
                        raise Exception("Unrecognized filter option %s - first letter should be one of 'EBLA'"%(item))
                else:
                        raise Exception("Unrecognized filter item %s - can be string (starting with E,L,B,A) float (max error in ps) or signed integer - number of clock periods"%(item))
        delay_cost=0
        clk_period=1000.0*self.x393_mcntrl_timing.get_dly_steps()['SDCLK_PERIOD'] # 2500.0, # clk_period,
        #Will add to error(ps) -delay_cost(steps) * delay_cost 
        if  lowDelay:
            delay_cost=clk_period*cost/(NUM_DLY_STEPS**2)
        elif highDelay:
            delay_cost=-clk_period*cost/(NUM_DLY_STEPS**2)
411
        
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
        if  target.upper() == 'DQI':
            delays=self.adjustment_state['dqi_phase_multi']
            errors=self.adjustment_state['dqi_phase_err']
            common_branches=False
        elif target.upper() == 'DQO':
            delays=self.adjustment_state['dqo_phase_multi']
            errors=self.adjustment_state['dqo_phase_err']
            common_branches=False
        elif  target.upper() == 'DQSI':
            delays=self.adjustment_state['dqsi_phase_multi']
            errors=self.adjustment_state['dqsi_phase_err']
            common_branches=False
        elif target.upper() == 'DQSO':
            delays=self.adjustment_state['dqso_phase_multi']
            errors=self.adjustment_state['dqso_phase_err']
            common_branches=False
        elif target.upper() == 'CMDA':
            delays=self.adjustment_state['addr_odelay']['dlys']
            errors=self.adjustment_state['addr_odelay']['err']
#            print("delays=",delays)
#            print("errors=",errors)
#            print("2:self.adjustment_state['addr_odelay']=",self.adjustment_state['addr_odelay'])                     
            
            common_branches=True
436
        else:
437 438 439
            raise Exception("Unrecognized mode option, valid are: 'DQSI','DQSO' and CMDA'")
        if common_branches:
            numPhaseSteps= len(delays)
440
        else:
441 442 443 444 445 446
            numPhaseSteps= len(delays[0])
        def single_phase(phase):
            if common_branches:
                phaseData=delays[phase]
                phaseErrs=errors[phase]
                if quiet <1:
447 448
                    print(phase,"--phaseData=",phaseData," ... highDelay=",highDelay," lowDelay=",lowDelay," list_branches=",list_branches)                

449
#                print("phaseErrs=",phaseErrs)
450
            else:
451
                try:
452 453 454 455 456 457 458 459 460
                    phaseData,phaseErrs=self._get_dqs_dly_err(phase,
                                                              delays,
                                                              errors)
                except: # _get_dqs_dly_err ==> None
                    if quiet <1:
                        print("phaseData=None")
                    
                    return None
                if quiet <1:
461
                    print(phase,"phaseData=",phaseData," ... highDelay=",highDelay," lowDelay=",lowDelay," list_branches=",list_branches)                
462
                
463 464
            if phaseData is None:
                return None
465 466 467
            
#            print ("target=",target," phaseData=",phaseData )
            """
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
            periods=phaseData.keys()
            
            periods.sort() # can compare tuples (1-st is "more important")
            if maxErrPS:
                for indx,branch in enumerate(periods):
                    if phaseErrs[branch] > maxErrPS:
                        periods.pop(indx)
            if allGood:
                for indx,branch in enumerate(periods):
                    if None in phaseData[branch]:
                        periods.pop(indx)
                        
            for indx,branch in enumerate(periods):  # if all elements are None
                if all(v is None for v in phaseData[branch]): 
                    periods.pop(indx)
483 484 485 486 487 488 489 490 491 492 493 494 495 496
            """    
            periods=set(phaseData.keys())
            if maxErrPS:
                for period in periods.copy():
                    if phaseErrs[period] > maxErrPS:
                        periods.remove(period)
            if allGood:
                for period in periods.copy():
                    if None in phaseData[period]:
                        periods.remove(period)
                        
            for period in periods.copy():  # if all elements are None
                if all(v is None for v in phaseData[period]): 
                    periods.remove(period)
497
                        
498 499 500
            periods=list(periods)
            periods.sort() # can compare tuples (1-st is "more important")

501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
                       
            # useBranch
            # filter results
            if periods_set:
                periods=[p for p in periods if p in periods_set]
            if not periods:
                return None
            if (len(periods) > 1) and minError:
                if delay_cost == 0:
                    """
                    merr=min(phaseErrs[b] for b in periods)
                    for branch in periods: # , e in phaseErrs.items():
                        if phaseErrs[branch] == merr:
                            periods=[branch]
                            break
                    """
                    #just list errors for the periods list
                    eff_errs=[phaseErrs[b] for b in periods]
                else:
                    #calculate "effective errors" by adding scaled (with +/-) average delay for branches
                    eff_errs=[phaseErrs[b]+(delay_cost*sum(d for d in phaseData[b] if not d is None)/sum(1 for d in phaseData[b] if not d is None)) for b in periods]
                periods=[periods[eff_errs.index(min(eff_errs))]]
            #Filter by low/high delays without minError mode
524
            if len(periods)>1:
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
                dl0_per=[phaseData[p][0] for p in periods] # only delay for line 0, but with same branch requirement this should be the same for all lines
                if highDelay or lowDelay or not list_branches or return_error: # in list_branches mode - filter by low/high only if requested, for delays use low if not highDelay
                    periods=[periods[dl0_per.index((min,max)[highDelay](dl0_per))]]
            if list_branches: # move to the almost very end, so filters apply
                return periods
            elif return_error:
                return phaseErrs[periods[0]]
            else:
                return phaseData[periods[0]]
            
        #main method body
        if not phase is None:
            rslt= single_phase(phase)
            if quiet < 3:
                print ("%d %s"%(phase,str(rslt)))
540
        else:
541 542 543 544 545 546 547 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
            rslt=[]
            for phase in range(numPhaseSteps):
                rslt.append(single_phase(phase))
            if quiet < 3:
                for phase, v in enumerate(rslt):
                    print ("%d %s"%(phase,str(v)))
        return rslt    
            
    def set_delays(self,
                   phase,
                   filter_cmda=None, # may be special case: 'S<safe_phase_as_float_number>
                   filter_dqsi=None,
                   filter_dqi= None,
                   filter_dqso=None,
                   filter_dqo= None,
                   cost=None,
                   refresh=True,
                   forgive_missing=False,
                   quiet=3):
        """
        Set phase and all relevant delays (ones with non None filters)
        @param phase value to calculate delays for or None to use globally set optimal_phase
        @param filter_cmda  filter clock period branches for command and addresses. See documentation for
        get_delays_for_phase() - b_filter
        @param filter_dqsi filter for DQS output delays
        @param filter_dqi  filter for DQS output delays
        @param filter_dqso filter for DQS output delays
        @param filter_dqo  filter for DQS output delays,
        @param refresh - turn refresh OFF before and ON after changing the delays and phase
        @param forgive_missing do not raise exceptions on missing data - just skip that delay group
        @param quiet Reduce output
        @return used delays dictionary on success, None on failure
        raises Exception() if any delays with non-None filters miss required data
        """
Andrey Filippov's avatar
Andrey Filippov committed
575 576 577 578 579 580 581 582 583 584 585 586
        if quiet < 2:
            print ("set_delays (",
                   phase,',',
                   filter_cmda,',', 
                   filter_dqsi, ',', 
                   filter_dqi, ',', 
                   filter_dqso, ',', 
                   filter_dqo, ',', 
                   cost, ',', 
                   refresh, ',', 
                   forgive_missing, ',',
                   quiet,")")
587
        if phase is None:
588
            try:
589
                phase= self.adjustment_state['optimal_phase']
590
            except:
591
                raise Exception("Phase value is not provided and global optimal phase is not defined")
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
        num_addr=vrlg.ADDRESS_NUMBER
        num_banks=3
        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)

        delays=self.get_all_delays(phase=phase,
                                   filter_cmda=     filter_cmda, # may be special case: 'S<safe_phase_as_float_number>
                                   filter_dqsi=     filter_dqsi,
                                   filter_dqi=      filter_dqi,
                                   filter_dqso=     filter_dqso,
                                   filter_dqo=      filter_dqo,
                                   cost=            cost,
                                   forgive_missing= forgive_missing,
                                   quiet=           quiet)
        if delays is None: #May also be an empty dictionary? 
            return None
        filters=dict(zip(SIG_LIST,[filter_cmda,filter_dqsi,filter_dqi,filter_dqso,filter_dqo]))
Andrey Filippov's avatar
Andrey Filippov committed
610
        if quiet < 3:
611 612
            print ("Going to set:")
            print ("phase=",phase)
613 614 615 616 617
            name_len=max(len(k) for k in SIG_LIST if filters[k] is not None)
            frmt="%%%ds = %%s"%(name_len+3)
            for k in SIG_LIST:
                if not filters[k] is None:
                    print(frmt%(k+" = "+" "*(name_len-len(k)), str(delays[k]))) 
618
            print ('Memory refresh will %sbe controlled'%(('NOT ','')[refresh]))
619
            
620 621 622
        if refresh:
            self.x393_axi_tasks.enable_refresh(0)
        self.x393_mcntrl_timing.axi_set_phase(phase,quiet=quiet)
623 624 625 626 627 628 629 630 631 632
        if CMDA_KEY in delays:
            if isinstance(delays[CMDA_KEY],(list,tuple)):
                self.x393_mcntrl_timing.axi_set_address_odelay(combine_delay(delays[CMDA_KEY][:num_addr]),quiet=quiet)
                self.x393_mcntrl_timing.axi_set_bank_odelay   (combine_delay(delays[CMDA_KEY][num_addr:num_addr+num_banks]),quiet=quiet)
                cmd_dly_data=delays[CMDA_KEY][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!
            else: # only data from 'cmda_bspe' is available - use it for all
                self.x393_mcntrl_timing.axi_set_cmda_odelay(combine_delay(delays[CMDA_KEY]),quiet=quiet)
633 634
        if refresh:
            self.x393_axi_tasks.enable_refresh(1)
635 636 637 638 639 640 641 642
        if DQSI_KEY in delays:
            self.x393_mcntrl_timing.axi_set_dqs_idelay(combine_delay(delays[DQSI_KEY]),quiet=quiet)
        if DQI_KEY in delays:
            self.x393_mcntrl_timing.axi_set_dq_idelay(combine_delay(delays[DQI_KEY]),quiet=quiet)
        if DQSO_KEY in delays:
            self.x393_mcntrl_timing.axi_set_dqs_odelay(combine_delay(delays[DQSO_KEY]),quiet=quiet)
        if DQO_KEY in delays:
            self.x393_mcntrl_timing.axi_set_dq_odelay(combine_delay(delays[DQO_KEY]),quiet=quiet)
643
        return True
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
        

    def get_all_delays(self,
                        phase,
                        filter_cmda=None, # may be special case: 'S<safe_phase_as_float_number>
                        filter_dqsi=None,
                        filter_dqi= None,
                        filter_dqso=None,
                        filter_dqo= None,
                        forgive_missing=False,
                        cost=None,
                        quiet=3):
        """
        Calculate dictionary of delays for specific phase. Only Non-None filters will generate items in the dictionary
        @param phase phase value to calculate delays for or None to calculate a list for all phases
        @param filter_cmda  filter clock period branches for command and addresses. See documentation for
        get_delays_for_phase() - b_filter
        @param filter_dqsi filter for DQS output delays
        @param filter_dqi  filter for DQS output delays
        @param filter_dqso filter for DQS output delays
        @param filter_dqo  filter for DQS output delays,
        @param forgive_missing do not raise exceptions on missing data - just skip that delay group
        @param quiet Reduce output
        @return None if not possible for at east one non-None filter, otherwise a dictionary of delay to set.
                Each value is either number set to all or a tuple/list (to set individual values)
        raises Exception if required data is missing
        """
        filters=dict(zip(SIG_LIST,[filter_cmda,filter_dqsi,filter_dqi,filter_dqso,filter_dqo]))
        if phase is None:
            all_delays=[]
            dly_steps=self.x393_mcntrl_timing.get_dly_steps()
            numPhaseSteps= int(dly_steps['SDCLK_PERIOD']/dly_steps['PHASE_STEP']+0.5)
            for phase in range(numPhaseSteps):
                all_delays.append(self.get_all_delays(phase=phase,
                                                      filter_cmda =     filter_cmda,
                                                      filter_dqsi =     filter_dqsi,
                                                      filter_dqi =      filter_dqi,
                                                      filter_dqso =     filter_dqso,
                                                      filter_dqo =      filter_dqo,
                                                      cost=             cost,
                                                      forgive_missing = forgive_missing,
                                                      quiet=            quiet))
            return all_delays
            
            
        delays={}
        for k in SIG_LIST:
            if  not filters[k] is None:
                #special case for cmda, and if self.adjustment_state['addr_odelay'] is not available
                if (k == CMDA_KEY) and ((not 'addr_odelay' in self.adjustment_state) or
                                        (isinstance (filter_cmda,str) and (len(filter_cmda)>1) and (filter_cmda.upper()[0]=='S'))):
                    if quiet < 3:                     
696
                        print ("\n------ processing '%s' using self.adjustment_state['cmda_bspe'], filter= %s"%(k,str(filters[k])))
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
                    try:
                        cmda_bspe=self.adjustment_state['cmda_bspe']
                    except:
                        raise Exception ('Data for filter_cmda is not available (self.adjustment_state["cmda_bspe"]')
                    try:
                        safe_phase=float(filter_cmda.upper()[1:])
                        if quiet <2:
                            print ("using safe phase=",safe_phase)
                    except:
                        safe_phase=0
                    if safe_phase >=0.5:
                        print ("Invalid 'safe range' (safe_phase). It is measured in clock cycles and should be < 0.5")
                        safe_phase=0
                    if safe_phase and (not cmda_bspe[phase]['zerr'] is None) and (cmda_bspe[phase]['zerr']< 0.5-safe_phase):
                        delays[k]=0 # set to minimal delay (==0)
                    else:
                        delays[k]=cmda_bspe[phase]['ldly']
                else:
                    if quiet < 3:                     
716
                        print ("\n------ processing '%s', filter= %s"%(k,str(filters[k])))
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
                    if forgive_missing:
                        try:
                            delays[k]=self.get_delays_for_phase(phase =       phase,
                                                                list_branches=False, # just get one set of filtered delay
                                                                target=       k,
                                                                b_filter=     filters[k],
                                                                cost=         cost,
                                                                quiet =       quiet+2)
                        except:
                            pass
                    delays[k]=self.get_delays_for_phase(phase =       phase,
                                                        list_branches=False, # just get one set of filtered delay
                                                        target=       k,
                                                        b_filter=     filters[k],
                                                        cost=         cost,
                                                        quiet =       quiet+2)
                if delays[k] is None:
                    return None
        return delays
    
    def show_all_delays(self,
Andrey Filippov's avatar
Andrey Filippov committed
738 739 740 741 742 743 744
                        filter_variants = None,
                        filter_cmda =    'A',#None,
                        filter_dqsi =    'A',#None,
                        filter_dqi =     'A',#None,
                        filter_dqso =    'A',#None,
                        filter_dqo =     'A',#None,
                        quiet =          3):
745 746
        """
        Print all optionally filtered delays, the results can be copied to a spreadsheet program to create graph
Andrey Filippov's avatar
Andrey Filippov committed
747
        @param filter_variants optional list of 3-tuples (cmda_variant, (dqso_variant,dqo-dqso), (dqsi_variant,dqi-dqsi))
748 749 750 751 752 753 754 755
        @param filter_cmda  filter clock period branches for command and addresses. See documentation for
        get_delays_for_phase() - b_filter
        @param filter_dqsi filter for DQS output delays
        @param filter_dqi  filter for DQS output delays
        @param filter_dqso filter for DQS output delays
        @param filter_dqo  filter for DQS output delays,
        @param quiet Reduce output
        """
756
        """
757 758 759 760 761 762 763 764 765
        required_keys=('addr_odelay',
                       'dqi_phase_multi',
                       'dqi_phase_err',
                       'dqo_phase_multi',
                       'dqo_phase_err',
                       'dqsi_phase_multi',
                       'dqsi_phase_err',
                       'dqso_phase_multi',
                       'dqso_phase_err')
766 767 768 769 770 771 772 773 774 775 776
        """
        #temporarily:
        self.load_mcntrl('dbg/x393_mcntrl.pickle')
        
        
#        if not all (k in self.adjustment_state for k in required_keys):
#            print ("Running in simulation mode, using hardcoded data")
#            self.load_hardcoded_data()
#            self.proc_addr_odelay(True, 200.0, 4)
#            self.proc_dqsi_phase ('All', 50, 0, 0.0, 200, 3)
#            self.proc_dqso_phase ('All', 50, 0, 0.0, 200, 3)
777
        #datasheet step per average delay per finedelay step    
778 779 780 781 782
        all_groups_valid_only=False
        if (isinstance(filter_variants,str)) : # currently - any string means "keep only phases that have all groups valid)
            all_groups_valid_only=True
            filter_variants=None

783 784 785 786 787 788
        tSDQS=1000.0*self.x393_mcntrl_timing.get_dly_steps()['DLY_STEP']/NUM_FINE_STEPS
        filters=dict(zip(SIG_LIST,[filter_cmda,filter_dqsi,filter_dqi,filter_dqso,filter_dqo]))
#        filters={CMDA_KEY:filter_cmda,DQSI_KEY:filter_dqsi,DQI_KEY:filter_dqi,DQSO_KEY:filter_dqso,DQO_KEY:filter_dqo}
        periods_phase={}
        periods_all={}
        for k in SIG_LIST:
789 790
            if quiet < 2:                     
                print ("\n===== processing '%s', filter= %s"%(k,str(filters[k])))
791 792 793 794 795
            periods_phase[k]=self.get_delays_for_phase(phase =       None,
                                                       list_branches=True,
                                                       target=k,
                                                       b_filter=filters[k],
                                                       #cost=NUM_FINE_STEPS,
796 797
#                                                       quiet = quiet+2)
                                                       quiet = quiet+0)
Andrey Filippov's avatar
Andrey Filippov committed
798
        numPhases=len(periods_phase[CMDA_KEY])
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 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
        #Remove DQI and DQO branches that are referenced to non-existing (filtered out) DQSI/DQI
        for phase in range (numPhases):# ,cmda,dqso,dqo, in zip(range(numPhases),cmda_vars,dqso_vars,dqo_vars):
            if (DQI_KEY in periods_phase) and (DQSI_KEY in periods_phase):
                fl=[]
                if periods_phase[DQI_KEY][phase] is not None:
                    for variant in periods_phase[DQI_KEY][phase]:
                        if (not periods_phase[DQSI_KEY][phase] is None) and (variant[0] in periods_phase[DQSI_KEY][phase]):
                            fl.append(variant)
                    if fl:
                        periods_phase[DQI_KEY][phase]=fl
                    else:
                        periods_phase[DQI_KEY][phase]=None
                            
            if (DQO_KEY in periods_phase) and (DQSO_KEY in periods_phase):
                if periods_phase[DQO_KEY][phase] is not None:
                    fl=[]
                    for variant in periods_phase[DQO_KEY][phase]:
                        if (not periods_phase[DQSO_KEY][phase] is None) and (variant[0] in periods_phase[DQSO_KEY][phase]):
                            fl.append(variant)
                    if fl:
                        periods_phase[DQO_KEY][phase]=fl
                    else:
                        periods_phase[DQO_KEY][phase]=None
        if quiet < 2:                     
            print ("all_groups_valid_only=",all_groups_valid_only)
        if all_groups_valid_only:
            for phase in range (numPhases):
                for k in periods_phase:
                    if periods_phase[k][phase] is None:
                        for k in periods_phase:
                            periods_phase[k][phase]=None
                        break
                        
                        
        if quiet < 2:
            print("===== Filtered periods: =====")
            for phase in range (numPhases):
                print ("phase=%d"%(phase),end=" ")
                for k in periods_phase:
                    print ("'%s':%s"%(k,str(periods_phase[k][phase])),end=" ")
                print()    
        
        
Andrey Filippov's avatar
Andrey Filippov committed
842 843 844 845 846 847
        if not filter_variants is None:
            strict= not ('all' in filter_variants)
            if quiet < 3:
                print ("filter_variants=",filter_variants)                     

            for phase in range (numPhases):# ,cmda,dqso,dqo, in zip(range(numPhases),cmda_vars,dqso_vars,dqo_vars):
848 849
                #build variants for each group that are used in at least one permitted combination of cmda, dqso, dqo, dqsi, dqi
                # 'try' makes sure that all groups are not None (in that case just skip that phase value)
Andrey Filippov's avatar
Andrey Filippov committed
850 851 852 853 854 855 856
                key_vars={}
                for k in SIG_LIST:
                    key_vars[k]=set()
                try:
                    for cmda in periods_phase[CMDA_KEY][phase]:
                        for dqo in  periods_phase[DQO_KEY][phase]:
                            for dqi in  periods_phase[DQI_KEY][phase]:
857 858
                                if quiet < 3:
                                    print("phase=%d, (cmda,dqo,dqi)=%s"%(phase,str((cmda,dqo,dqi))))
Andrey Filippov's avatar
Andrey Filippov committed
859 860 861 862 863
                                if (((cmda,dqo,dqi) in filter_variants) and 
                                    (dqo[0] in periods_phase[DQSO_KEY][phase]) and
                                    (dqi[0] in periods_phase[DQSI_KEY][phase])):
                                    for i,k in enumerate(SIG_LIST):
                                        key_vars[k].add((cmda,dqi[0],dqi,dqo[0],dqo)[i]) #careful with the order
864 865
                    if quiet < 2:
                        print("phase=%d, key_vars=%s"%(phase,str(key_vars))) # OK
Andrey Filippov's avatar
Andrey Filippov committed
866 867 868
                    for k in SIG_LIST:
                        for variant in periods_phase[k][phase]:
                            if not variant in  key_vars[k]:
869 870 871 872 873 874
                                if quiet < 3:
                                    print ("phase=%d: variant %s is not in %s for %s, key_vars=%s . OK in when filtered by 'filter_variants'"%(phase,
                                                                                                                                               variant,
                                                                                                                                               str(key_vars[k]),
                                                                                                                                               str(k),
                                                                                                                                               str(key_vars)))
Andrey Filippov's avatar
Andrey Filippov committed
875
                                periods_phase[k][phase].pop(variant) # remove variants that do not fit in one of the combinations in filter_variants
876 877 878
                        if quiet <2:
                            print("periods_phase[%s][phase]=%s, strict=%s"%(str(k),str(periods_phase[k][phase]),str(strict)))
                        assert (periods_phase[k][phase] or (not strict))
Andrey Filippov's avatar
Andrey Filippov committed
879 880
                except:
                    for k in SIG_LIST:
881 882
                        if quiet <2:
                            print("except %s"%str(k))
Andrey Filippov's avatar
Andrey Filippov committed
883
                        periods_phase[k][phase]=None
884 885 886 887 888 889
            if quiet <2:
                for phase in range (numPhases):
                    print ("phase= %d"%(phase), end=" ")
                    for k in SIG_LIST:
                        print ("%s"%(periods_phase[k][phase]), end=" ")
                    print()
Andrey Filippov's avatar
Andrey Filippov committed
890
        for k in SIG_LIST:
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 928 929 930 931 932 933 934 935 936 937 938 939 940
            periods_all[k]=set()
            for lp in periods_phase[k]:
                try:
                    for p in lp:
                        periods_all[k].add(p)
                except:
                    pass # None
            periods_all[k]=list(periods_all[k])
            periods_all[k].sort()    
        if quiet <3:                     
            print ("periods_all=",periods_all)
        # Print the header
        num_addr=15
        num_banks=3
        num_lines=16
        num_cmda=num_addr+num_banks+3+1
        num_lanes=num_lines//8
        positions={CMDA_KEY:num_cmda,DQSI_KEY:num_lanes,DQI_KEY:num_lines,DQSO_KEY:num_lanes,DQO_KEY:num_lines}
        
        print ("phase",end=" ")
        for period in periods_all[CMDA_KEY]:
            for i in range(num_addr):
                print("A%d_%d"%(i,period),end=" ")
            for i in range(num_banks):
                print("BA%d_%d"%(i,period),end=" ")
            print ("WE_%d RAS_%d CAS_%d AVG_%d"%(period,period,period,period), end=" ") # AVG - average for address,  banks, RCW
        for period in periods_all[DQSI_KEY]:
            for lane in range(num_lanes):
                print("DQSI_%d_%d"%(lane,period),end=" ")
        for period in periods_all[DQI_KEY]:
            for line in range(num_lines):
                print("DQI_%d_%d/%d"%(line,period[0],period[1]),end=" ")
        for period in periods_all[DQSO_KEY]:
            for lane in range(num_lanes):
                print("DQSO_%d_%d"%(lane,period),end=" ")
        for period in periods_all[DQO_KEY]:
            for line in range(num_lines):
                print("DQO_%d_%d/%d"%(line,period[0],period[1]),end=" ")
                
        #TODO - add errors print
#        """       
        for period in periods_all[CMDA_KEY]:
            print("ERR_CMDA_%d"%(period),end=" ")
        for period in periods_all[DQSI_KEY]:
            print("ERR_DQSI_%d"%(period),end=" ")
        for period in periods_all[DQSO_KEY]:
            print("ERR_DQSO_%d"%(period),end=" ")
#        """
        print()
        #print body
Andrey Filippov's avatar
Andrey Filippov committed
941
        for phase in range(numPhases):
942 943 944
            print ("%d"%(phase),end=" ")
            for k in SIG_LIST:               
                for period in periods_all[k]:
945 946
                    if (not periods_phase[k][phase] is None) and (period in periods_phase[k][phase]):
#                        print("<<",k,"::",periods_phase[k][phase],":",period,">>>")
Andrey Filippov's avatar
Andrey Filippov committed
947
                        data_group=self.get_delays_for_phase(phase = phase,
948 949 950 951 952
                                                        list_branches=False,
                                                        target=k,
                                                        b_filter=[period,"A"],
                                                       #cost=NUM_FINE_STEPS, only used with 'B'
                                                        quiet = quiet+2)
Andrey Filippov's avatar
Andrey Filippov committed
953 954
                    else:
                        data_group=None
955 956 957 958 959 960 961 962
                    for i in range(positions[k]):
                        try:
                            print("%d"%(data_group[i]), end=" ")
                        except:
                            print("?",end=" ")

            for k in [CMDA_KEY,DQSI_KEY,DQSO_KEY]:               
                for period in periods_all[k]:
963
                    if (not periods_phase[k][phase] is None) and (period in periods_phase[k][phase]):
Andrey Filippov's avatar
Andrey Filippov committed
964
                        err_ps=self.get_delays_for_phase(phase = phase,
965 966 967 968 969
                                                     list_branches='Err',
                                                     target=k,
                                                     b_filter=[period,"A"],
                                                     #cost=NUM_FINE_STEPS, only used with 'B'
                                                     quiet = quiet+2)
Andrey Filippov's avatar
Andrey Filippov committed
970 971
                    else:
                        err_ps=None
972 973 974 975 976 977 978 979 980 981 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
                    try:
                        print("%.1f"%(err_ps/tSDQS), end=" ")
                    except:
                        print("?",end=" ")
                            
            print()
            
                
            
            
            
        
        
#numPhaseSteps= len(delays[0])        
                

    def set_phase_with_refresh(self, # check result for not None
                               phase,
                               quiet=1):
        """
        Set specified phase and matching cmda_odelay while temporarily turning off refresh
        @param phase phase to set, signed short
        @param quiet reduce output 
        @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)
        self.x393_mcntrl_timing.axi_set_cmda_odelay(combine_delay(cmda_odly_lin),quiet=quiet)
        self.x393_axi_tasks.enable_refresh(1)
        return cmda_odly_lin
1010

1011 1012 1013 1014 1015 1016 1017
    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
                           ):
        """
1018 1019 1020 1021 1022 1023 1024 1025 1026
        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
1027
        """
1028
        nbursts=16
1029 1030 1031 1032
        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)
1033
        max_lin_dly=NUM_DLY_STEPS-1
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
        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
            """
1044
            cmda_dly_lin=split_delay(cmda_dly)
1045 1046
            self.x393_mcntrl_timing.axi_set_phase(phase,quiet=quiet)
            self.x393_mcntrl_timing.axi_set_cmda_odelay(cmda_dly,quiet=quiet)
1047
            wlev_rslt=self.x393_pio_sequences.write_levelling(1, nbursts, quiet+1)
1048 1049 1050 1051 1052
            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()
1053
                wlev_rslt=self.x393_pio_sequences.write_levelling(1,nbursts, quiet)
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
                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()
1065
                    wlev_rslt=self.x393_pio_sequences.write_levelling(1, nbursts, quiet)
1066 1067 1068 1069 1070 1071
                    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(
1072
                                                           combine_delay(d_high),
1073 1074
                                                           wlev_address_bit,
                                                           quiet=quiet)
1075
            wlev_rslt=self.x393_pio_sequences.write_levelling(1, nbursts, quiet+1)
1076
            if not wlev_rslt[2]>wlev_max_bad:
1077
                return  (split_delay(cmda_dly),-1) # even maximal delay is not enough to make rising sdclk separate command from A7
1078 1079 1080 1081 1082
            # 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
1083
                self.x393_mcntrl_timing.axi_set_address_odelay(combine_delay(dly),wlev_address_bit,quiet=quiet)
1084
                wlev_rslt=self.x393_pio_sequences.write_levelling(1, nbursts, quiet+1)
1085 1086 1087 1088 1089 1090 1091
                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)
1092
            return (split_delay(cmda_dly),d_low)
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
               
        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
1107
        safe_early=split_delay(recover_cmda_dly_step)/2
1108 1109 1110
#        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()
1111 1112
        else:
            self.x393_axi_tasks.enable_refresh(0) # if not init, at least turn refresh off!
1113 1114 1115 1116 1117

        for phase in range(start_phase,start_phase+numPhaseSteps):
            if quiet <3:
                print ("%d:"%(phase),end=" ")
                sys.stdout.flush()
1118 1119 1120
            elif quiet < 5:
                print (".",end="")
                sys.stdout.flush()
1121 1122 1123
            phase_mod=phase % numPhaseSteps
            dlys= phase_step(phase,cmda_dly)
            cmda_marg_dly[phase_mod]=dlys # [1] # Marginal delay or -1
1124
            cmda_dly = combine_delay(dlys[0]) # update if it was modified during recover
1125 1126 1127 1128 1129
            # 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()
1130 1131 1132
                elif quiet < 5:
                    print (".",end="")
                    sys.stdout.flush()
1133 1134 1135 1136 1137 1138 1139 1140 1141
                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()
1142 1143 1144
                elif quiet < 5:
                    print (".",end="")
                    sys.stdout.flush()
1145
                lin_dly=split_delay(cmda_dly)
1146 1147 1148 1149 1150 1151
                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]?
                
1152 1153
                if lin_dly != split_delay(cmda_dly):   
                    cmda_dly=combine_delay(lin_dly)
1154 1155 1156 1157 1158
                    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()
1159
            
1160 1161 1162 1163

        if quiet <2:
            for i,d in enumerate(cmda_marg_dly):
                print ("%d %d %d"%(i, d[0], d[1]))
1164 1165
        elif quiet < 5:
                print ()
1166 1167 1168 1169 1170 1171
        #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:
1172
            raise Exception("Too few points with measured marginal CMDA odelay: %d"%numValid)
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 1220 1221 1222
        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))
1223
            
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
        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))
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 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
        # 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)) )
1287
            
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
            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]
1310 1311 1312 1313 1314 1315 1316
#            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 

1317 1318 1319 1320
            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
1321 1322 1323
                                         'err':bspe[2],
                                         'zerr':err_for_zero
                                         })
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
            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']))
1337
            print("\nPhase DLY0 MARG_A7 CMDA PERIODS*10 ERR*10 ZERR*100")
1338 1339 1340 1341
            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]):
1342 1343 1344 1345 1346 1347 1348
                    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))
1349 1350 1351
                else:
                    print()
#TODO: Add 180 shift to get center, not marginal cmda_odelay        
1352
        self.adjustment_state.update(rdict)
1353 1354 1355 1356 1357
        if (quiet <3):
            print ("rdict={")
            for k,v in rdict.items():
                print("'%s':%s,"%(k,str(v)))
            print ("}")
1358 1359
        return rdict
        
1360 1361
    def measure_write_levelling(self,
                               compare_prim_steps = True, # while scanning, compare this delay with 1 less by primary(not fine) step,
1362 1363 1364
                               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)
1365
                               dqs_patt=None,
1366 1367
                               quiet=1
                               ):
1368
        """
1369
        Find DQS output delay for each phase value
1370
        Depends on adjust_cmda_odelay results
1371 1372 1373 1374 1375 1376
        @param compare_prim_steps = True, # while scanning, compare this delay with 1 less by primary(not fine) step,
        @param start_phase=0,
        @param reinits=1, #higher the number - more re-inits are used (0 - only where absolutely necessary
        @param invert=0, # anti-align DQS (should be 180 degrees off from the normal one), can be used to find duty cycle of the clock
        @param dqs_patt set and store in global data DQS pattern to use during writes
        @param quiet=1
1377
        """
1378
        nbursts=16
1379
        numLanes=2
1380 1381 1382
        try:
            self.adjustment_state['cmda_bspe']
        except:
1383 1384 1385 1386
            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
1387
        max_lin_dly=NUM_DLY_STEPS-1
1388 1389 1390 1391 1392
        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))
1393 1394
            
        self.x393_pio_sequences.set_write_lev(nbursts) # write leveling, 16 times   (full buffer - 128)
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
        if dqs_patt is None:
            try:
                dqs_patt=self.adjustment_state["dqs_pattern"]
            except:
                print("Skipping DQS pattern (0x55/0xaa) control as it is not provided and not in gloabal data (dqs_patt=self.adjustment_state['dqs_pattern'])")

        if not dqs_patt is None: # may be just set
            self.x393_mcntrl_timing.axi_set_dqs_dqm_patterns(dqs_patt=dqs_patt,
                                                             dqm_patt=None,
                                                             quiet=quiet+2)
1405
        def wlev_phase_step (phase):
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
            dqso_cache=[None]*NUM_DLY_STEPS # cache for holding already measured delays. None - not measured, 0 - no data, [[]..[]]
            def measure_dqso(dly,force_meas=False):
                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
                if (dqso_cache[dly] is None) or force_meas:
                    self.x393_mcntrl_timing.axi_set_dqs_odelay(combine_delay(dly),quiet=quiet)
                    wlev_rslt=norm_wlev(self.x393_pio_sequences.write_levelling(1, nbursts, quiet+1))
                    if wlev_rslt[2]>wlev_max_bad: # should be 0 - otherwise wlev did not work (CMDA?)
                        raise Exception("Write levelling gave unexpected data, aborting (may be wrong command/address delay, incorrectly initialized")
                    dqso_cache[dly] = wlev_rslt
                    if quiet < 1:
                        print ('measure_dqso(%d) - new measurement'%(dly))
1421
                else:
1422 1423 1424 1425 1426 1427 1428 1429 1430
                    wlev_rslt = dqso_cache[dly]
                    if quiet < 1:
                        print ('measure_dqso(%d) - using cache'%(dly))
                return wlev_rslt
                     
                
            
            
            #currently looking for the lowest delay, may be multiple with higher frequency (full delay > period)
1431 1432 1433 1434 1435 1436
            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)
1437
            self.x393_mcntrl_timing.axi_set_cmda_odelay(combine_delay(cmda_odly_lin),quiet=quiet)
1438 1439
            d_low=0
            while d_low <= max_lin_dly:
1440
                wlev_rslt=measure_dqso(d_low)
1441 1442 1443
                if (wlev_rslt[0] <= wlev_max_bad) and (wlev_rslt[1] <= wlev_max_bad):
                    break
                d_low+=dly90
1444
            else:
1445 1446 1447 1448 1449 1450
                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:
1451
                wlev_rslt=measure_dqso(d_high)
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
                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
1465
                wlev_rslt=measure_dqso(dly)
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
                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]
1479
            for i in range(numLanes):
1480 1481 1482 1483
                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))
1484
                    wlev_rslt=measure_dqso(dly)
1485 1486 1487 1488 1489 1490
                    if wlev_rslt[i] <= wlev_max_bad:
                        if d_low[i] == dly:
                            break
                        d_low[i]=dly
                    else:
                        d_high[i]=dly
1491
            #return d_low
1492

1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 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
            # now scan in the range +/- NUM_FINE_STEPS for each lane, get (dly, err) for each, err=None if binary 
            rslt=[]
            bestDly=[None]*numLanes # [low_safe]*2 # otherwise may fail - check it?
            bestDiffs=[None]*numLanes
            comp_step=(1,NUM_FINE_STEPS)[compare_prim_steps]
            for lane in range (numLanes):
                lastPositive=0
                for dly in range (max(0,d_low[lane]-NUM_FINE_STEPS), min(NUM_DLY_STEPS,d_low[lane]+2*NUM_FINE_STEPS+1)):
                    ref_dly= dly-comp_step
                    if ref_dly <0:
                        continue
                    wlev_rslt_ref=measure_dqso(ref_dly)    
                    wlev_rslt=    measure_dqso(dly)    
                    diff=    wlev_rslt[lane]-0.5
                    diff_ref=wlev_rslt_ref[lane]-0.5
                    diffs_prev_this=(diff_ref,diff)
                    if diff > 0:
                        lastPositive+=1
                    else:
                        lastPositive=0
                    if quiet <2:
                        print ("lane=%d ref_dly=%d dly=%d, diffs_prev_this=%s"%(lane, ref_dly, dly, str(diffs_prev_this)))
                    if (diffs_prev_this[0] <= 0) and (diffs_prev_this[1] >= 0): 
                        if abs(diffs_prev_this[0]) <= abs(diffs_prev_this[1]): # store previous 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 (diff > 0):
                    if lastPositive > NUM_FINE_STEPS:
                        break # no need to continue, data got already - Wrong, better analog may still be ahead
                if bestDiffs[lane] == -0.5:
                    bestDiffs[lane] = None # single step jumps from none to all
                elif not bestDiffs[lane] is None:
                    bestDiffs[lane] *= 2
                rslt.append((bestDly[lane],bestDiffs[lane]))
                if quiet < 2:
                    print ("bestDly[%d]=%s, bestDiffs[%d]=%s"%(lane,str(bestDly[lane]),lane,str(bestDiffs[lane])))
            if quiet < 2:
                print ('dly=%d rslt=%s'%(dly,str(rslt)))
            if quiet < 2:
                print ("Cache for phase=%d:"%(phase))
                for i,d in enumerate(dqso_cache):
                    if d:
                        print ("%d %d: %s"%(phase,i,str(d)))
            return rslt

        # main method body
        
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
        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()
1561 1562 1563
            elif quiet < 5:
                print (".",end="")
                sys.stdout.flush()
1564 1565 1566 1567 1568
            dlys=wlev_phase_step(phase)
            wlev_dqs_delays[phase_mod]=dlys
            if quiet <3:
                print ("%s"%str(dlys),end=" ")
                sys.stdout.flush()
1569 1570 1571 1572
            elif quiet < 5:
                print (".",end="")
                sys.stdout.flush()
            if quiet< 2:
1573 1574
                print()
                
1575 1576 1577 1578
        if quiet < 4:
            print("\nMeasured wlev data, When error is None add 1/2 of compare_prim_steps to the estimated result")
            print("compare_prim_steps=",compare_prim_steps)
            print("Phase dly0 dly1 fdly0 fdly1 err0 err1")
1579 1580
            for i,d in enumerate(wlev_dqs_delays):
                if d:
1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
                    print ("%d %d %d"%(i, d[0][0], d[1][0]), end=" ")
                    for ld in d:
                        if not ld[1] is None:
                            print ("%d"%(ld[0]),end= " ")
                        else:
                            print ("?",end=" ")
                    for ld in d:
                        try:
                            print ("%.3f"%(ld[1]),end= " ")
                        except:
                            print ("?",end=" ")
                    print()        
1593 1594
                else:
                    print ("%d"%(i))
1595 1596
        elif quiet < 5:
            print ()
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
        #measurement done, now processing results. TODO: move to a separate function            
        if quiet < 4:
            print ("wlev_dqs_delays=",wlev_dqs_delays)
            print ("wlev_dqs_steps=", compare_prim_steps)
            
        self.adjustment_state["wlev_dqs_delays"]=wlev_dqs_delays    
        self.adjustment_state["wlev_dqs_steps"]=compare_prim_steps
        if not dqs_patt is None:
            self.adjustment_state["dqs_pattern"]=dqs_patt
        return wlev_dqs_delays
    

    def proc_write_levelling(self,
                             data_set_number=2,        # not number - use measured data
                             max_phase_err=0.1,
                             quiet=1):
        if isinstance (data_set_number,(int,long)) and (data_set_number>=0) :
            if quiet < 4:
                print("Using hard-coded data set ")
                wlev_dqs_delays=get_test_dq_dqs_data.get_wlev_dqs_delays()
        else:
            if quiet < 4:
                print("Using measured data set")
            try:
                wlev_dqs_delays=self.adjustment_state["wlev_dqs_delays"]
            except:
                print ("Write levelling measured data is not available, exiting")
                return
        dly_steps=self.x393_mcntrl_timing.get_dly_steps()
        numPhaseSteps= int(dly_steps['SDCLK_PERIOD']/dly_steps['PHASE_STEP']+0.5)

1629 1630 1631 1632 1633 1634 1635
        #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)
1636 1637 1638
        
        print("wlev_dqs_delays=",wlev_dqs_delays)
        
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 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
        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
1711
            while (b[lane] >= NUM_DLY_STEPS):
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
                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
1742
                dly_min= max(0,int(y0-4.5))
1743
                dly_max= min(NUM_DLY_STEPS-1,int(y0+5.5))
1744 1745 1746 1747 1748 1749 1750
                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))
1751
                    dly_max= min(NUM_DLY_STEPS-1,int(y0+5.5))
1752 1753
                    for d in range(dly_min,dly_max+1):
                        dly_to_try.append((d,periods))
1754 1755
                bestDly=None
                bestDiff=None
1756 1757 1758 1759
                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
1760 1761
                    if (bestDiff is None) or (abs(bestDiff) > abs(diff)):
                        bestDiff = diff
1762 1763 1764
                        bestDly =  dp[0]
                        bestPeriods= dp[1]
                phase_rslt=() #Default, if nothing was found
1765
                if not bestDiff is None:
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
                    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=" ")
1776
                else:
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793
                    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]})
1794
                else:
1795
                    wlev_bspe[lane].append({})
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
        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=" ")
1825 1826
                print()
                            
1827
        self.adjustment_state.update(rdict)
1828 1829 1830 1831 1832
        if (quiet <3):
            print ("rdict={")
            for k,v in rdict.items():
                print("'%s':%s