x393_mcntrl_adjust.py 314 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
#from x393_utils              import X393Utils
import x393_utils
45 46 47

import get_test_dq_dqs_data # temporary to test processing            
import x393_lma
48
import time
49 50
import vrlg
#NUM_FINE_STEPS=    5
51 52 53
NUM_DLY_STEPS =NUM_FINE_STEPS * 32 # =160
DQI_KEY='dqi'
DQO_KEY='dqo'
54 55 56
DQSI_KEY='dqsi'
DQSO_KEY='dqso'
CMDA_KEY='cmda'
57
ODD_KEY='odd'
58 59
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 
60 61 62 63 64 65 66 67 68

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
Andrey Filippov's avatar
Andrey Filippov committed
69
    x393_utils=None
70
    verbose=1
71
    adjustment_state={}
72
    def __init__(self, debug_mode=1,dry_mode=True, saveFileName=None):
73 74 75
        self.DEBUG_MODE=  debug_mode
        self.DRY_MODE=    dry_mode
        self.x393_mem=            X393Mem(debug_mode,dry_mode)
76 77
#        self.x393_axi_tasks=      X393AxiControlStatus(debug_mode,dry_mode)
        self.x393_axi_tasks=      x393_axi_control_status.X393AxiControlStatus(debug_mode,dry_mode)
78 79 80
        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)
81 82
#        print("x393_utils.SAVE_FILE_NAME=",x393_utils.SAVE_FILE_NAME)
        self.x393_utils=          x393_utils.X393Utils(debug_mode,dry_mode, saveFileName) # should not overwrite save file path
83
#        self.__dict__.update(VerilogParameters.__dict__["_VerilogParameters__shared_state"]) # Add verilog parameters to the class namespace
84
        try:
85
            self.verbose=vrlg.VERBOSE
86 87
        except:
            pass
88 89
#keep as command        

90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
    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()
107

108
    def missing_dqs_notused(self,
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
                     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
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
        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):
183
        """
184
        @param outmode False - dqi/dqsi, True - dgo/dqso, None - both
185
        """
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
        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):
214
        """
215 216 217 218 219 220 221 222 223
        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!
224
        """
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
        #
#        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
244
            except:
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 318 319 320 321 322
                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)
    
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 364 365 366 367 368
    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
369
        try:
370 371 372
            if list_branches.upper()[0]=='E':
                return_error=True
                list_branches=False
373
        except:
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 411 412 413 414 415
            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)
416
        
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
        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
441
        else:
442 443 444
            raise Exception("Unrecognized mode option, valid are: 'DQSI','DQSO' and CMDA'")
        if common_branches:
            numPhaseSteps= len(delays)
445
        else:
446 447 448 449 450 451
            numPhaseSteps= len(delays[0])
        def single_phase(phase):
            if common_branches:
                phaseData=delays[phase]
                phaseErrs=errors[phase]
                if quiet <1:
452 453
                    print(phase,"--phaseData=",phaseData," ... highDelay=",highDelay," lowDelay=",lowDelay," list_branches=",list_branches)                

454
#                print("phaseErrs=",phaseErrs)
455
            else:
456
                try:
457 458 459 460 461 462 463 464 465
                    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:
466
                    print(phase,"phaseData=",phaseData," ... highDelay=",highDelay," lowDelay=",lowDelay," list_branches=",list_branches)                
467
                
468 469
            if phaseData is None:
                return None
470 471 472
            
#            print ("target=",target," phaseData=",phaseData )
            """
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
            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)
488 489 490 491 492 493 494 495 496 497 498 499 500 501
            """    
            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)
502
                        
503 504 505
            periods=list(periods)
            periods.sort() # can compare tuples (1-st is "more important")

506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
                       
            # 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
529
            if len(periods)>1:
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
                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)))
545
        else:
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
            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,
Andrey Filippov's avatar
Andrey Filippov committed
564
                   maxPhaseErrorsPS=None,
565 566 567 568 569 570 571 572 573 574 575 576
                   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
Andrey Filippov's avatar
Andrey Filippov committed
577
        @param maxPhaseErrorsPS - if present, specifies maximal phase errors (in ps) for cmda, dqsi and dqso (each can be None)
578 579 580 581
        @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
582 583 584 585 586 587 588 589 590 591 592
        if quiet < 2:
            print ("set_delays (",
                   phase,',',
                   filter_cmda,',', 
                   filter_dqsi, ',', 
                   filter_dqi, ',', 
                   filter_dqso, ',', 
                   filter_dqo, ',', 
                   cost, ',', 
                   refresh, ',', 
                   forgive_missing, ',',
Andrey Filippov's avatar
Andrey Filippov committed
593
                   maxPhaseErrorsPS,',',
Andrey Filippov's avatar
Andrey Filippov committed
594
                   quiet,")")
595
        if phase is None:
596
            try:
597
                phase= self.adjustment_state['optimal_phase']
598
            except:
599
                raise Exception("Phase value is not provided and global optimal phase is not defined")
600 601 602 603 604 605 606 607 608 609 610 611 612 613
        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,
Andrey Filippov's avatar
Andrey Filippov committed
614
                                   maxPhaseErrorsPS=maxPhaseErrorsPS,
615 616 617 618
                                   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
619
        if quiet < 3:
620 621
            print ("Going to set:")
            print ("phase=",phase)
622 623 624 625 626
            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]))) 
627
            print ('Memory refresh will %sbe controlled'%(('NOT ','')[refresh]))
628
            
629 630 631
        if refresh:
            self.x393_axi_tasks.enable_refresh(0)
        self.x393_mcntrl_timing.axi_set_phase(phase,quiet=quiet)
632 633 634 635 636 637 638 639 640 641
        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)
642 643
        if refresh:
            self.x393_axi_tasks.enable_refresh(1)
644 645 646 647 648 649 650 651
        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)
652
        return True
653 654 655 656 657 658 659 660 661 662 663
        

    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,
Andrey Filippov's avatar
Andrey Filippov committed
664
                        maxPhaseErrorsPS=None,
665 666 667 668 669 670 671 672 673 674 675
                        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
Andrey Filippov's avatar
Andrey Filippov committed
676 677 678
        @param cost - cost of switching to a higher(lower) delay branch as a fraction of a period
        @param maxPhaseErrorsPS - if present, specifies maximal phase errors (in ps) for cmda, dqsi and dqso (each can be None)

679 680 681 682 683 684
        @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]))
Andrey Filippov's avatar
Andrey Filippov committed
685 686 687 688 689 690
        dly_steps=self.x393_mcntrl_timing.get_dly_steps()
        numPhaseSteps= int(dly_steps['SDCLK_PERIOD']/dly_steps['PHASE_STEP']+0.5)
        phaseStep=1000.0*dly_steps['PHASE_STEP']
        if quiet < 3:
            print ("get_all_delays(): maxPhaseErrorsPS=",maxPhaseErrorsPS)
#            assert (not maxPhaseErrorsPS is None)
691 692 693 694 695 696 697 698 699 700
        if phase is None:
            all_delays=[]
            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,
                                                      forgive_missing = forgive_missing,
Andrey Filippov's avatar
Andrey Filippov committed
701 702
                                                      cost=             cost,
                                                      maxPhaseErrorsPS=maxPhaseErrorsPS,
703 704 705 706 707
                                                      quiet=            quiet))
            return all_delays
            
            
        delays={}
Andrey Filippov's avatar
Andrey Filippov committed
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
        phaseTolerances={}
        if quiet < 2:                     
            print("maxPhaseErrorsPS=",maxPhaseErrorsPS)
        if maxPhaseErrorsPS:
            if isinstance (maxPhaseErrorsPS, (float, int,long)):
                maxPhaseErrorsPS=(maxPhaseErrorsPS,maxPhaseErrorsPS,maxPhaseErrorsPS)
            if maxPhaseErrorsPS[0]:
                phaseTolerances[CMDA_KEY]= int(round(maxPhaseErrorsPS[0]/phaseStep))
            if maxPhaseErrorsPS[1]:
                phaseTolerances[DQSI_KEY]= int(round(maxPhaseErrorsPS[1]/phaseStep))
            if maxPhaseErrorsPS[2]:
                phaseTolerances[DQSO_KEY]= int(round(maxPhaseErrorsPS[2]/phaseStep))
            if (quiet <2):
                print ("phaseTolerances=",phaseTolerances)
        all_good=True    
        for k in SIG_LIST: #CMDA first, DQS before DQ
724 725 726 727
            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'))):
Andrey Filippov's avatar
Andrey Filippov committed
728
                    # not processing phaseTolerances in this mode
729
                    if quiet < 3:                     
730
                        print ("\n------ processing '%s' using self.adjustment_state['cmda_bspe'], filter= %s"%(k,str(filters[k])))
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
                    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:                     
750
                        print ("\n------ processing '%s', filter= %s"%(k,str(filters[k])))
751 752 753 754 755 756 757 758 759 760
                    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
Andrey Filippov's avatar
Andrey Filippov committed
761 762 763 764 765 766 767 768
                    else:
                        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)
                    
769
                if delays[k] is None:
Andrey Filippov's avatar
Andrey Filippov committed
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
                    if quiet < 3:                     
                        print ("delays[%s]=%s,phaseTolerances=%s"%(k,str(delays[k]),str(phaseTolerances)))
                    if phaseTolerances:
                        all_good=False
                    else:
                        if quiet < 3:                     
                            print ("%s: return None"%(k))
                        return None
        if not all_good: # try to fix - see if the solutions exist for slightly different phases
            if quiet < 3:                     
                print ("phase= %d, delays= %s"%(phase,str(delays)))

            for pair in ((CMDA_KEY,CMDA_KEY,),(DQSI_KEY,DQI_KEY),(DQSO_KEY,DQO_KEY)): # will do some double work for CMDA_KEY
                if (pair[0] in phaseTolerances) and phaseTolerances[pair[0]] and (pair[0] in delays) and (pair[1] in delays): # so not to process forgive_missing again
                    if quiet < 3:                     
                        print ("pair= ",pair)
                    
                    if (not (delays[pair[0]]) is None) and (not (delays[pair[1]]) is None):
                        continue #nothing to fix for this pair
                    phase_var=1
                    while abs(phase_var) <= phaseTolerances[pair[0]]:
                        other_phase=(phase+phase_var) % numPhaseSteps
                        if quiet < 2:                     
                            print ("phase_var=%d, other_phase=%d"%(phase_var,other_phase))
                        
                        dlys=[]
                        dlys.append(self.get_delays_for_phase(phase =     other_phase,
                                                            list_branches=False, # just get one set of filtered delay
                                                            target=       pair[0],
                                                            b_filter=     filters[pair[0]],
                                                            cost=         cost,
                                                            quiet =       quiet+2))
                        dlys.append(self.get_delays_for_phase(phase =      other_phase,
                                                            list_branches=False, # just get one set of filtered delay
                                                            target=       pair[1],
                                                            b_filter=     filters[pair[1]],
                                                            cost=         cost,
                                                            quiet =       quiet+2))
                        if quiet < 2:                     
                            print ("dlys=",dlys)
                        if not None in dlys:
                            if quiet <3:
                                print ("Found replacement phase=%d (for %d) for the signal pair:%s"%(other_phase,phase,str(pair)))
                            delays[pair[0]]=dlys[0]
                            delays[pair[1]]=dlys[1]
                            break
                        phase_var=-phase_var
                        if phase_var > 0:
                            phase_var += +1
            # See if there are still some None in the delays
            if None in delays:
                if quiet <2:
                    print ("Some delays are still missing for phase %d :%s"%(phase,str(delays)))
823 824 825
        return delays
    
    def show_all_delays(self,
Andrey Filippov's avatar
Andrey Filippov committed
826 827 828 829 830 831 832
                        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):
833 834
        """
        Print all optionally filtered delays, the results can be copied to a spreadsheet program to create graph
Andrey Filippov's avatar
Andrey Filippov committed
835
        @param filter_variants optional list of 3-tuples (cmda_variant, (dqso_variant,dqo-dqso), (dqsi_variant,dqi-dqsi))
Andrey Filippov's avatar
Andrey Filippov committed
836 837
               Alternatively if this parameter is a string (currently any), only phase values that have all signals valid
               will be shown 
838 839 840 841 842 843 844 845
        @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
        """
846
        """
847 848 849 850 851 852 853 854 855
        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')
856 857
        """
        #temporarily:
Andrey Filippov's avatar
Andrey Filippov committed
858 859 860 861 862 863 864 865 866 867 868 869
#        self.load_mcntrl('dbg/x393_mcntrl.pickle')
        if quiet < 5:
            print("\n\nCopy the table below to a spreadsheet program to plot graphs)")
            print("show_all_delays(",
                  filter_variants,",",
                  filter_cmda,",",
                  filter_dqsi,",",
                  filter_dqi,",",
                  filter_dqso,",",
                  filter_dqo ,",",
                  quiet,")")

870 871 872 873 874
        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

875 876 877 878 879
        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]))
        periods_phase={}
        periods_all={}
        for k in SIG_LIST:
Andrey Filippov's avatar
Andrey Filippov committed
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
            if not filters[k] is None:
                if quiet < 2:                     
                    print ("\n===== processing '%s', filter= %s"%(k,str(filters[k])))
                periods_phase[k]=self.get_delays_for_phase(phase =       None,
                                                           list_branches=True,
                                                           target=k,
                                                           b_filter=filters[k],
                                                           #cost=NUM_FINE_STEPS,
                                                           quiet = quiet+1)
    #                                                       quiet = quiet+0)
#        numPhases=len(periods_phase[CMDA_KEY])
        try:
            numPhases=len(periods_phase[periods_phase.keys()[0]])
        except:
            print ("show_all_delays(): Nothing selected, exiting")
            return
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
        #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
939 940 941 942 943 944
        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):
945 946
                #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
947 948 949 950 951 952 953
                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]:
954 955
                                if quiet < 3:
                                    print("phase=%d, (cmda,dqo,dqi)=%s"%(phase,str((cmda,dqo,dqi))))
Andrey Filippov's avatar
Andrey Filippov committed
956 957 958 959 960
                                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
961 962
                    if quiet < 2:
                        print("phase=%d, key_vars=%s"%(phase,str(key_vars))) # OK
Andrey Filippov's avatar
Andrey Filippov committed
963 964 965
                    for k in SIG_LIST:
                        for variant in periods_phase[k][phase]:
                            if not variant in  key_vars[k]:
966 967 968 969 970 971
                                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
972
                                periods_phase[k][phase].pop(variant) # remove variants that do not fit in one of the combinations in filter_variants
973 974 975
                        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
976 977
                except:
                    for k in SIG_LIST:
978 979
                        if quiet <2:
                            print("except %s"%str(k))
Andrey Filippov's avatar
Andrey Filippov committed
980
                        periods_phase[k][phase]=None
981 982 983 984 985 986
            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
987
        for k in SIG_LIST:
Andrey Filippov's avatar
Andrey Filippov committed
988 989 990 991 992 993 994 995 996 997
            if k in periods_phase:
                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()    
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
        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=" ")
Andrey Filippov's avatar
Andrey Filippov committed
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
        if CMDA_KEY in periods_all:
            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
        if DQSI_KEY in periods_all:
            for period in periods_all[DQSI_KEY]:
                for lane in range(num_lanes):
                    print("DQSI_%d_%d"%(lane,period),end=" ")
        if DQI_KEY in periods_all:
            for period in periods_all[DQI_KEY]:
                for line in range(num_lines):
                    print("DQI_%d_%d/%d"%(line,period[0],period[1]),end=" ")
        if DQSO_KEY in periods_all:
            for period in periods_all[DQSO_KEY]:
                for lane in range(num_lanes):
                    print("DQSO_%d_%d"%(lane,period),end=" ")
        if DQO_KEY in periods_all:
            for period in periods_all[DQO_KEY]:
                for line in range(num_lines):
                    print("DQO_%d_%d/%d"%(line,period[0],period[1]),end=" ")
1032 1033 1034
                
        #TODO - add errors print
#        """       
Andrey Filippov's avatar
Andrey Filippov committed
1035 1036 1037 1038 1039 1040 1041 1042 1043
        if CMDA_KEY in periods_all:
            for period in periods_all[CMDA_KEY]:
                print("ERR_CMDA_%d"%(period),end=" ")
        if DQSI_KEY in periods_all:
            for period in periods_all[DQSI_KEY]:
                print("ERR_DQSI_%d"%(period),end=" ")
        if DQSO_KEY in periods_all:
            for period in periods_all[DQSO_KEY]:
                print("ERR_DQSO_%d"%(period),end=" ")
1044 1045 1046
#        """
        print()
        #print body
Andrey Filippov's avatar
Andrey Filippov committed
1047
        for phase in range(numPhases):
1048
            print ("%d"%(phase),end=" ")
Andrey Filippov's avatar
Andrey Filippov committed
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
            for k in SIG_LIST:
                if k in periods_all:               
                    for period in periods_all[k]:
                        if (not periods_phase[k][phase] is None) and (period in periods_phase[k][phase]):
    #                        print("<<",k,"::",periods_phase[k][phase],":",period,">>>")
                            data_group=self.get_delays_for_phase(phase = phase,
                                                            list_branches=False,
                                                            target=k,
                                                            b_filter=[period,"A"],
                                                           #cost=NUM_FINE_STEPS, only used with 'B'
                                                            quiet = quiet+2)
                        else:
                            data_group=None
                        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]:               
                if k in periods_all:               
                    for period in periods_all[k]:
                        if (not periods_phase[k][phase] is None) and (period in periods_phase[k][phase]):
                            err_ps=self.get_delays_for_phase(phase = phase,
                                                         list_branches='Err',
                                                         target=k,
                                                         b_filter=[period,"A"],
                                                         #cost=NUM_FINE_STEPS, only used with 'B'
                                                         quiet = quiet+2)
                        else:
                            err_ps=None
1080
                        try:
Andrey Filippov's avatar
Andrey Filippov committed
1081
                            print("%.1f"%(err_ps/tSDQS), end=" ")
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
                        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
1111 1112
            print ("phase=",phase)
            print (self.adjustment_state['cmda_bspe'])
1113 1114 1115 1116 1117 1118 1119
            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
1120

1121 1122 1123 1124 1125 1126 1127
    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
                           ):
        """
1128 1129 1130 1131 1132 1133 1134 1135 1136
        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
1137
        """
1138
        nbursts=16
1139 1140 1141 1142
        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)
1143
        max_lin_dly=NUM_DLY_STEPS-1
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
        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
            """
1154
            cmda_dly_lin=split_delay(cmda_dly)
1155 1156
            self.x393_mcntrl_timing.axi_set_phase(phase,quiet=quiet)
            self.x393_mcntrl_timing.axi_set_cmda_odelay(cmda_dly,quiet=quiet)
1157
            wlev_rslt=self.x393_pio_sequences.write_levelling(1, nbursts, quiet+1)
1158 1159 1160 1161 1162
            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()
1163
                wlev_rslt=self.x393_pio_sequences.write_levelling(1,nbursts, quiet)
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
                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()
1175
                    wlev_rslt=self.x393_pio_sequences.write_levelling(1, nbursts, quiet)
1176 1177 1178 1179 1180 1181
                    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(
1182
                                                           combine_delay(d_high),
1183 1184
                                                           wlev_address_bit,
                                                           quiet=quiet)
1185
            wlev_rslt=self.x393_pio_sequences.write_levelling(1, nbursts, quiet+1)
1186
            if not wlev_rslt[2]>wlev_max_bad:
1187
                return  (split_delay(cmda_dly),-1) # even maximal delay is not enough to make rising sdclk separate command from A7
1188 1189 1190 1191 1192
            # 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
1193
                self.x393_mcntrl_timing.axi_set_address_odelay(combine_delay(dly),wlev_address_bit,quiet=quiet)
1194
                wlev_rslt=self.x393_pio_sequences.write_levelling(1, nbursts, quiet+1)
1195 1196 1197 1198 1199 1200 1201
                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)
1202
            return (split_delay(cmda_dly),d_low)
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
               
        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
1217
        safe_early=split_delay(recover_cmda_dly_step)/2
1218 1219 1220
#        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()
1221 1222
        else:
            self.x393_axi_tasks.enable_refresh(0) # if not init, at least turn refresh off!
1223 1224 1225 1226 1227

        for phase in range(start_phase,start_phase+numPhaseSteps):
            if quiet <3:
                print ("%d:"%(phase),end=" ")
                sys.stdout.flush()
1228 1229 1230
            elif quiet < 5:
                print (".",end="")
                sys.stdout.flush()
1231 1232 1233
            phase_mod=phase % numPhaseSteps
            dlys= phase_step(phase,cmda_dly)
            cmda_marg_dly[phase_mod]=dlys # [1] # Marginal delay or -1
1234
            cmda_dly = combine_delay(dlys[0]) # update if it was modified during recover
1235 1236 1237 1238 1239
            # 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()
1240 1241 1242
                elif quiet < 5:
                    print (".",end="")
                    sys.stdout.flush()
1243 1244 1245 1246 1247 1248 1249 1250 1251
                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()
1252 1253 1254
                elif quiet < 5:
                    print (".",end="")
                    sys.stdout.flush()
1255
                lin_dly=split_delay(cmda_dly)
1256 1257 1258 1259 1260 1261
                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]?
                
1262 1263
                if lin_dly != split_delay(cmda_dly):   
                    cmda_dly=combine_delay(lin_dly)
1264 1265 1266 1267 1268
                    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()
1269
            
1270 1271 1272 1273

        if quiet <2:
            for i,d in enumerate(cmda_marg_dly):
                print ("%d %d %d"%(i, d[0], d[1]))
1274 1275
        elif quiet < 5:
                print ()
1276 1277 1278 1279 1280 1281
        #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:
1282
            raise Exception("Too few points with measured marginal CMDA odelay: %d"%numValid)
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
        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))
1333
            
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
        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))
1350

1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
        # 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)) )
1397
            
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
            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]
1420 1421 1422 1423 1424 1425 1426
#            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 

1427 1428 1429 1430
            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
1431 1432 1433
                                         'err':bspe[2],
                                         'zerr':err_for_zero
                                         })
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
            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']))
1447
            print("\nPhase DLY0 MARG_A7 CMDA PERIODS*10 ERR*10 ZERR*100")
1448 1449 1450 1451
            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]):
1452 1453 1454 1455 1456 1457 1458
                    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))
1459 1460 1461
                else:
                    print()
#TODO: Add 180 shift to get center, not marginal cmda_odelay        
1462
        self.adjustment_state.update(rdict)
1463 1464 1465 1466 1467
        if (quiet <3):
            print ("rdict={")
            for k,v in rdict.items():
                print("'%s':%s,"%(k,str(v)))
            print ("}")
1468 1469
        return rdict
        
1470 1471
    def measure_write_levelling(self,
                               compare_prim_steps = True, # while scanning, compare this delay with 1 less by primary(not fine) step,
1472 1473 1474
                               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)
1475
                               dqs_patt=None,
1476 1477
                               quiet=1
                               ):
1478
        """
1479
        Find DQS output delay for each phase value
1480
        Depends on adjust_cmda_odelay results
1481 1482 1483 1484 1485 1486
        @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
1487
        """
1488
        nbursts=16
1489
        numLanes=2
1490 1491 1492
        try:
            self.adjustment_state['cmda_bspe']
        except:
1493 1494 1495 1496
            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
1497
        max_lin_dly=NUM_DLY_STEPS-1
1498 1499 1500 1501 1502
        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))
1503 1504
            
        self.x393_pio_sequences.set_write_lev(nbursts) # write leveling, 16 times   (full buffer - 128)
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
        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)
1515
        def wlev_phase_step (phase):
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
            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))
1531
                else:
1532 1533 1534 1535 1536 1537 1538 1539 1540
                    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)
1541 1542 1543 1544 1545 1546
            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)
1547
            self.x393_mcntrl_timing.axi_set_cmda_odelay(combine_delay(cmda_odly_lin),quiet=quiet)
1548 1549
            d_low=0
            while d_low <= max_lin_dly:
1550
                wlev_rslt=measure_dqso(d_low)
1551 1552 1553
                if (wlev_rslt[0] <= wlev_max_bad) and (wlev_rslt[1] <= wlev_max_bad):
                    break
                d_low+=dly90
1554
            else:
1555 1556 1557 1558 1559 1560
                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:
1561
                wlev_rslt=measure_dqso(d_high)
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
                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
1575
                wlev_rslt=measure_dqso(dly)
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
                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]
1589
            for i in range(numLanes):
1590 1591 1592 1593
                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))
1594
                    wlev_rslt=measure_dqso(dly)
1595 1596 1597 1598 1599 1600
                    if wlev_rslt[i] <= wlev_max_bad:
                        if d_low[i] == dly:
                            break
                        d_low[i]=dly
                    else:
                        d_high[i]=dly
1601
            #return d_low
1602

1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
            # 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
        
1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
        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()
1671 1672 1673
            elif quiet < 5:
                print (".",end="")
                sys.stdout.flush()
1674 1675 1676 1677 1678
            dlys=wlev_phase_step(phase)
            wlev_dqs_delays[phase_mod]=dlys
            if quiet <3:
                print ("%s"%str(dlys),end=" ")
                sys.stdout.flush()
1679 1680 1681 1682
            elif quiet < 5:
                print (".",end="")
                sys.stdout.flush()
            if quiet< 2:
1683 1684
                print()
                
1685 1686 1687 1688
        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")
1689 1690
            for i,d in enumerate(wlev_dqs_delays):
                if d:
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
                    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()        
1703 1704
                else:
                    print ("%d"%(i))
1705 1706
        elif quiet < 5:
            print ()
1707
            
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738
        #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)

1739 1740 1741 1742 1743 1744 1745
        #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)
1746 1747 1748
        
        print("wlev_dqs_delays=",wlev_dqs_delays)
        
1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
        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
1821
            while (b[lane] >= NUM_DLY_STEPS):