x393_mcntrl_adjust.py 333 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
    wlev_all_bits = False # write leveling reported on allDQ lines
72
    adjustment_state={}
73
    def __init__(self, debug_mode=1,dry_mode=True, saveFileName=None):
74 75 76
        self.DEBUG_MODE=  debug_mode
        self.DRY_MODE=    dry_mode
        self.x393_mem=            X393Mem(debug_mode,dry_mode)
77 78
#        self.x393_axi_tasks=      X393AxiControlStatus(debug_mode,dry_mode)
        self.x393_axi_tasks=      x393_axi_control_status.X393AxiControlStatus(debug_mode,dry_mode)
79 80 81
        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)
82 83
#        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
84
#        self.__dict__.update(VerilogParameters.__dict__["_VerilogParameters__shared_state"]) # Add verilog parameters to the class namespace
85
        try:
86
            self.verbose=vrlg.VERBOSE
87 88
        except:
            pass
89 90
#keep as command        

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

109
    def missing_dqs_notused(self,
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
                     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
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 183
        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):
184
        """
185
        @param outmode False - dqi/dqsi, True - dgo/dqso, None - both
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 214
        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):
215
        """
216 217 218 219 220 221 222 223 224
        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!
225
        """
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
        #
#        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
245
            except:
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 323
                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)
    
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 369
    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
370
        try:
371 372 373
            if list_branches.upper()[0]=='E':
                return_error=True
                list_branches=False
374
        except:
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 416
            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)
417
        
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
        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
442
        else:
443 444 445
            raise Exception("Unrecognized mode option, valid are: 'DQSI','DQSO' and CMDA'")
        if common_branches:
            numPhaseSteps= len(delays)
446
        else:
447 448 449 450 451 452
            numPhaseSteps= len(delays[0])
        def single_phase(phase):
            if common_branches:
                phaseData=delays[phase]
                phaseErrs=errors[phase]
                if quiet <1:
453 454
                    print(phase,"--phaseData=",phaseData," ... highDelay=",highDelay," lowDelay=",lowDelay," list_branches=",list_branches)                

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

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

    def get_all_delays(self,
                        phase,
659 660 661 662 663 664 665 666 667
                        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,
                        allow_replace =    True,
                        cost =             None,
                        maxPhaseErrorsPS = None,
668 669 670 671 672 673 674 675 676 677 678
                        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
679
        @param allow_replace Try to find solutions fro close phases
Andrey Filippov's avatar
Andrey Filippov committed
680 681 682
        @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)

683 684 685 686 687 688
        @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
689 690 691 692 693 694
        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)
695 696 697 698 699 700 701 702 703 704
        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,
705
                                                      allow_replace =   allow_replace,
Andrey Filippov's avatar
Andrey Filippov committed
706 707
                                                      cost=             cost,
                                                      maxPhaseErrorsPS=maxPhaseErrorsPS,
708 709 710 711 712
                                                      quiet=            quiet))
            return all_delays
            
            
        delays={}
Andrey Filippov's avatar
Andrey Filippov committed
713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
        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
729 730 731 732
            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
733
                    # not processing phaseTolerances in this mode
734
                    if quiet < 3:                     
735
                        print ("\n------ processing '%s' using self.adjustment_state['cmda_bspe'], filter= %s"%(k,str(filters[k])))
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
                    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:                     
755
                        print ("\n------ processing '%s', filter= %s"%(k,str(filters[k])))
756 757 758 759 760 761 762 763 764 765
                    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
766 767 768 769 770 771 772 773
                    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)
                    
774
                if delays[k] is None:
Andrey Filippov's avatar
Andrey Filippov committed
775 776 777 778 779 780 781 782 783 784
                    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:                     
785 786 787
                print ("Not all good: allow_replace = %d, phase= %d, delays= %s"%(allow_replace, phase,str(delays)))
            if not allow_replace:
                raise Exception ("Not all good solutions for this phase")     
Andrey Filippov's avatar
Andrey Filippov committed
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 823 824 825 826 827 828 829

            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)))
830 831 832
        return delays
    
    def show_all_delays(self,
Andrey Filippov's avatar
Andrey Filippov committed
833 834 835 836 837 838 839
                        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):
840 841
        """
        Print all optionally filtered delays, the results can be copied to a spreadsheet program to create graph
Andrey Filippov's avatar
Andrey Filippov committed
842
        @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
843 844
               Alternatively if this parameter is a string (currently any), only phase values that have all signals valid
               will be shown 
845 846 847 848 849 850 851 852
        @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
        """
853
        """
854 855 856 857 858 859 860 861 862
        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')
863 864
        """
        #temporarily:
Andrey Filippov's avatar
Andrey Filippov committed
865 866 867 868 869 870 871 872 873 874 875 876
#        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,")")

877 878 879 880 881
        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

882 883 884 885 886
        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
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
            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
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
        #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
946 947 948 949 950 951
        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):
952 953
                #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
954 955 956 957 958 959 960
                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]:
961 962
                                if quiet < 3:
                                    print("phase=%d, (cmda,dqo,dqi)=%s"%(phase,str((cmda,dqo,dqi))))
Andrey Filippov's avatar
Andrey Filippov committed
963 964 965 966 967
                                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
968 969
                    if quiet < 2:
                        print("phase=%d, key_vars=%s"%(phase,str(key_vars))) # OK
Andrey Filippov's avatar
Andrey Filippov committed
970 971 972
                    for k in SIG_LIST:
                        for variant in periods_phase[k][phase]:
                            if not variant in  key_vars[k]:
973 974 975 976 977 978
                                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
979
                                periods_phase[k][phase].pop(variant) # remove variants that do not fit in one of the combinations in filter_variants
980 981 982
                        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
983 984
                except:
                    for k in SIG_LIST:
985 986
                        if quiet <2:
                            print("except %s"%str(k))
Andrey Filippov's avatar
Andrey Filippov committed
987
                        periods_phase[k][phase]=None
988 989 990 991 992 993
            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
994
        for k in SIG_LIST:
Andrey Filippov's avatar
Andrey Filippov committed
995 996 997 998 999 1000 1001 1002 1003 1004
            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()    
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
        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
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
        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=" ")
1039 1040 1041
                
        #TODO - add errors print
#        """       
Andrey Filippov's avatar
Andrey Filippov committed
1042 1043 1044 1045 1046 1047 1048 1049 1050
        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=" ")
1051 1052 1053
#        """
        print()
        #print body
Andrey Filippov's avatar
Andrey Filippov committed
1054
        for phase in range(numPhases):
1055
            print ("%d"%(phase),end=" ")
Andrey Filippov's avatar
Andrey Filippov committed
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
            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
1087
                        try:
Andrey Filippov's avatar
Andrey Filippov committed
1088
                            print("%.1f"%(err_ps/tSDQS), end=" ")
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
                        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
1118 1119
            print ("phase=",phase)
            print (self.adjustment_state['cmda_bspe'])
1120 1121
            return None
        cmda_odly_lin=cmda_odly_data['ldly']
1122 1123
        
        
1124 1125 1126 1127 1128
        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
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
    def write_levelling_allbits(self,
                        wait_complete=1, # Wait for operation to complete
                        nburst=16,
                        quiet=1):       
        """
        Use when result is on all bits. Data may be inconsistent (not 0/ff) if read phase is wrong, so try
        step to change it
        @param wait_complete wait write levelling operation to complete (0 - may initiate multiple PS PIO operations)
        @param nburst  number of 8-bursts written (should match sequence!) 
        @param quiet    reduce output
        @eturn a pair of ratios for getting "1" for 2 lanes and problem marker (should be 0), added 4-th value for LY
        """
        wlev_max_bad=0.01 # <= OK, > bad
        if quiet < 1:
            print("--- write_levelling_allbits--- ")
        delay_dflt=(split_delay(vrlg.get_default_field("DLY_LANE0_IDELAY",8)),
                    split_delay(vrlg.get_default_field("DLY_LANE1_IDELAY",8)))
        delay_up = ((delay_dflt[0]+(NUM_DLY_STEPS/4))%NUM_DLY_STEPS, (delay_dflt[1]+(NUM_DLY_STEPS/4))%NUM_DLY_STEPS)
        self.x393_mcntrl_timing.axi_set_dqs_idelay((combine_delay(delay_dflt[0]),combine_delay(delay_dflt[1])),quiet=quiet)
        wlev_rslt=self.x393_pio_sequences.write_levelling(wait_complete, nburst, quiet)
        if quiet < 1:
            print("wlev_rslt=",wlev_rslt)
        if wlev_rslt[3] > wlev_max_bad:
            if quiet < 1:
                print("Default dqs input delay (%d,%d) results in ambiguous wlev results, changing to (%d,%d)"%
                      (delay_dflt[0],delay_dflt[1],delay_up[0],delay_up[1]))
            self.x393_mcntrl_timing.axi_set_dqs_idelay((combine_delay(delay_up[0]),combine_delay(delay_up[1])),quiet=quiet)
            wlev_rslt1= self.x393_pio_sequences.write_levelling(wait_complete, nburst, quiet)
            #restore default delay
            self.x393_mcntrl_timing.axi_set_dqs_idelay((combine_delay(delay_dflt[0]),combine_delay(delay_dflt[1])),quiet=quiet)
            if wlev_rslt1[3] < wlev_rslt[3]:
                return wlev_rslt1
        return wlev_rslt    
1162

1163 1164 1165 1166
    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,
1167
                           allow_all_bits = True,
1168 1169 1170
                           quiet=1
                           ):
        """
1171 1172 1173 1174 1175 1176 1177 1178
        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
1179
        @parame allow_all_bits - allow write leveling to respond on all bits (normally - only on 1)
1180
        @param quiet reduce output
1181
        """
1182
        nbursts=16
1183 1184 1185 1186
        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)
1187
        max_lin_dly=NUM_DLY_STEPS-1
1188 1189
        wlev_address_bit=7
        wlev_max_bad=0.01 # <= OK, > bad
1190 1191 1192
        # for MT41K256M16LY-093 (0/ff) need higher threshold
#        wlev_max_bad=0.1
        #self.wlev_all_bits = False # needed here?      
1193 1194
        def phase_step(phase,cmda_dly):
            """
1195 1196
            Find marginal delay for address/command lines for particular clock phase
            Raises exception if failed to get write leveling data even after
1197 1198 1199
            changing cmda delay and restarting memory device
            Returns a tuple of the current cmda_odelay (hardware) and a marginal one for a7
            """
1200 1201 1202
            if quiet < 1:
                print("==phase_step(%d,%d),self.wlev_all_bits=%d"%(phase,cmda_dly,self.wlev_all_bits))

1203
            cmda_dly_lin=split_delay(cmda_dly)
1204 1205
            self.x393_mcntrl_timing.axi_set_phase(phase,quiet=quiet)
            self.x393_mcntrl_timing.axi_set_cmda_odelay(cmda_dly,quiet=quiet)
1206 1207 1208 1209 1210 1211 1212 1213
            if not self.wlev_all_bits:
                wlev_rslt=self.x393_pio_sequences.write_levelling(1, nbursts, quiet+1)
                if allow_all_bits and (wlev_rslt[3] < wlev_rslt[2]):
                    self.wlev_all_bits = True
            if self.wlev_all_bits: # maybe just set
                wlev_rslt=self.write_levelling_allbits(1, nbursts, quiet+1)        
            bad_wlev = wlev_rslt[2 + (0,1)[self.wlev_all_bits]]
            if bad_wlev > wlev_max_bad: # should be 0, if not - Try to recover
1214
                if quiet <4:
1215 1216 1217 1218
                    print("*** FAILED to read data in write leveling mode, restarting memory device")
                    print("    Retrying with the same cmda_odelay value = 0x%x, wlev_rslt[2] = %f, wlev_rslt[3] = %f"
                          %(cmda_dly,wlev_rslt[2],wlev_rslt[3]))
                    
1219
                self.x393_pio_sequences.restart_ddr3()
1220 1221 1222 1223 1224 1225 1226 1227
                if self.wlev_all_bits: # try to vary DQS input delay
                    wlev_rslt=self.write_levelling_allbits(1, nbursts, quiet+1)        
                else:        
#                   wlev_rslt=self.x393_pio_sequences.write_levelling(1,nbursts, quiet)
                    wlev_rslt=self.x393_pio_sequences.write_levelling(1,nbursts, quiet)
                bad_wlev = wlev_rslt[2 + (0,1)[self.wlev_all_bits]]
                   
                if bad_wlev > wlev_max_bad: # should be 0, if not - change delay and restart memory
1228 1229 1230 1231 1232 1233
                    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:
1234
                        print("*** FAILED to read data in write leveling mode, restarting memory device")
1235 1236 1237
                        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()
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248

                    if self.wlev_all_bits: # try to vary DQS input delay
                        wlev_rslt=self.write_levelling_allbits(1, nbursts, quiet+1)        
                    else:        
    #                   wlev_rslt=self.x393_pio_sequences.write_levelling(1,nbursts, quiet)
                        wlev_rslt=self.x393_pio_sequences.write_levelling(1,nbursts, -1)
                    bad_wlev = wlev_rslt[2 + (0,1)[self.wlev_all_bits]]
#                    wlev_rslt=self.x393_pio_sequences.write_levelling(1, nbursts, quiet)
                    bad_wlev = wlev_rslt[2 + (0,1)[self.wlev_all_bits]]
                    if bad_wlev > wlev_max_bad: # should be 0, if not - change delay and restart memory
                        raise Exception("Failed to read in write leveling mode after modifying cmda_odelay, aborting")
1249 1250 1251 1252
                    
# Try twice step before giving up (was not needed so far)                    
            d_high=max_lin_dly
            self.x393_mcntrl_timing.axi_set_address_odelay(
1253
                                                           combine_delay(d_high),
1254 1255
                                                           wlev_address_bit,
                                                           quiet=quiet)
1256 1257 1258 1259 1260 1261 1262
            if self.wlev_all_bits: # try to vary DQS input delay
                wlev_rslt=self.write_levelling_allbits(1, nbursts, quiet+1)        
            else:        
                wlev_rslt=self.x393_pio_sequences.write_levelling(1, nbursts, quiet+1)
            bad_wlev = wlev_rslt[2 + (0,1)[self.wlev_all_bits]]
                
            if not bad_wlev > wlev_max_bad:
1263
                return  (split_delay(cmda_dly),-1) # even maximal delay is not enough to make rising sdclk separate command from A7
1264 1265 1266 1267 1268
            # 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
1269
                self.x393_mcntrl_timing.axi_set_address_odelay(combine_delay(dly),wlev_address_bit,quiet=quiet)
1270 1271 1272 1273 1274 1275
                if self.wlev_all_bits: # try to vary DQS input delay
                    wlev_rslt=self.write_levelling_allbits(1, nbursts, quiet+1)        
                else:        
                    wlev_rslt=self.x393_pio_sequences.write_levelling(1, nbursts, quiet+1)
                bad_wlev = wlev_rslt[2 + (0,1)[self.wlev_all_bits]]
                if bad_wlev > wlev_max_bad:
1276 1277 1278 1279 1280 1281
                    d_high=dly
                else:
                    if d_low == dly:
                        break
                    d_low=dly
            self.x393_mcntrl_timing.axi_set_cmda_odelay(cmda_dly,quiet=quiet)
1282
            return (split_delay(cmda_dly),d_low)
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
               
        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
1297
        safe_early=split_delay(recover_cmda_dly_step)/2
1298 1299 1300
#        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()
1301 1302
        else:
            self.x393_axi_tasks.enable_refresh(0) # if not init, at least turn refresh off!
1303 1304 1305 1306 1307

        for phase in range(start_phase,start_phase+numPhaseSteps):
            if quiet <3:
                print ("%d:"%(phase),end=" ")
                sys.stdout.flush()
1308 1309 1310
            elif quiet < 5:
                print (".",end="")
                sys.stdout.flush()
1311 1312 1313
            phase_mod=phase % numPhaseSteps
            dlys= phase_step(phase,cmda_dly)
            cmda_marg_dly[phase_mod]=dlys # [1] # Marginal delay or -1
1314
            cmda_dly = combine_delay(dlys[0]) # update if it was modified during recover
1315 1316 1317 1318 1319
            # 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()
1320 1321 1322
                elif quiet < 5:
                    print (".",end="")
                    sys.stdout.flush()
1323 1324 1325 1326 1327 1328 1329 1330 1331
                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()
1332 1333 1334
                elif quiet < 5:
                    print (".",end="")
                    sys.stdout.flush()
1335
                lin_dly=split_delay(cmda_dly)
1336 1337 1338 1339 1340 1341
                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]?
                
1342 1343
                if lin_dly != split_delay(cmda_dly):   
                    cmda_dly=combine_delay(lin_dly)
1344 1345 1346 1347 1348
                    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()
1349
            
1350 1351 1352 1353

        if quiet <2:
            for i,d in enumerate(cmda_marg_dly):
                print ("%d %d %d"%(i, d[0], d[1]))
1354 1355
        elif quiet < 5:
                print ()
1356 1357 1358 1359 1360 1361
        #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:
1362
            raise Exception("Too few points with measured marginal CMDA odelay: %d"%numValid)
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 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
        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))
1413
            
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
        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))
1430

1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
        # 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
1442 1443
            if (quiet <2):
                print("phase= %d, y=%f, variantStep=%f"%(phase,y,variantStep))
1444 1445 1446 1447 1448 1449 1450 1451
            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
1452 1453
            if (quiet <2):
                print("y0=%f"%(y0))
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
            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)) )
1481
            
1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
            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]
1504 1505 1506 1507 1508 1509 1510
#            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 

1511 1512 1513 1514
            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
1515 1516 1517
                                         'err':bspe[2],
                                         'zerr':err_for_zero
                                         })
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
            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']))
1531
            print("\nPhase DLY0 MARG_A7 CMDA PERIODS*10 ERR*10 ZERR*100")
1532 1533 1534 1535
            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]):
1536 1537 1538 1539 1540 1541 1542
                    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))
1543 1544 1545
                else:
                    print()
#TODO: Add 180 shift to get center, not marginal cmda_odelay        
1546
        self.adjustment_state.update(rdict)
1547 1548 1549 1550 1551
        if (quiet <3):
            print ("rdict={")
            for k,v in rdict.items():
                print("'%s':%s,"%(k,str(v)))
            print ("}")
1552 1553
        return rdict
        
1554 1555
    def measure_write_levelling(self,
                               compare_prim_steps = True, # while scanning, compare this delay with 1 less by primary(not fine) step,
1556 1557 1558
                               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)
1559
                               dqs_patt=None,
1560
                               allow_all_bits = True,
1561 1562
                               quiet=1
                               ):
1563
        """
1564
        Find DQS output delay for each phase value
1565
        Depends on adjust_cmda_odelay results
1566 1567 1568 1569 1570
        @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
1571
        @parame allow_all_bits - allow write leveling to respond on all bits (normally - only on 1)
1572
        @param quiet=1
1573
        """
1574
        nbursts=16
1575
        numLanes=2
1576 1577 1578
        try:
            self.adjustment_state['cmda_bspe']
        except:
1579 1580 1581 1582
            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
1583
        max_lin_dly=NUM_DLY_STEPS-1
1584 1585 1586 1587
#        wlev_max_bad=0.01 # <= OK, > bad
        # for MT41K256M16LY-093 (0/ff) need higher threshold
        wlev_max_bad=0.1
        
1588 1589 1590 1591
        numPhaseSteps=len(self.adjustment_state['cmda_bspe'])
        if quiet < 2:
            print("cmda_bspe = %s"%str(self.adjustment_state['cmda_bspe']))
            print ("numPhaseSteps=%d"%(numPhaseSteps))
1592 1593
            
        self.x393_pio_sequences.set_write_lev(nbursts) # write leveling, 16 times   (full buffer - 128)
1594 1595 1596 1597
        if dqs_patt is None:
            try:
                dqs_patt=self.adjustment_state["dqs_pattern"]
            except:
1598
                print("Skipping DQS pattern (0x55/0xaa) control as it is not provided and not in global data (dqs_patt=self.adjustment_state['dqs_pattern'])")
1599 1600 1601 1602 1603

        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)
1604
        def wlev_phase_step (phase):
1605 1606 1607 1608
            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:
1609
                        return [1.0-wlev[0],1.0-wlev[1],wlev[2],wlev[3]]
1610 1611 1612 1613
                    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)
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
#                    wlev_rslt=norm_wlev(self.x393_pio_sequences.write_levelling(1, nbursts, quiet+1))

                    if not self.wlev_all_bits:
                        wlev_rslt=self.x393_pio_sequences.write_levelling(1, nbursts, quiet+1)
                        if allow_all_bits and (wlev_rslt[3] < wlev_rslt[2]):
                            self.wlev_all_bits = True
                    if self.wlev_all_bits: # maybe just set
                        wlev_rslt=self.write_levelling_allbits(1, nbursts, quiet+1)
                    wlev_rslt=norm_wlev(wlev_rslt)
                    bad_wlev = wlev_rslt[2 + (0,1)[self.wlev_all_bits]]
                    if bad_wlev > wlev_max_bad: # should be 0 - otherwise wlev did not work (CMDA?)
#                        raise Exception("Write leveling gave unexpected data, aborting (may be wrong command/address delay, incorrectly initialized")
Andrey Filippov's avatar
Andrey Filippov committed
1626
#disabling check 04.09.2016
1627
                        print ("raise Exception Write leveling gave unexpected data, aborting (may be wrong command/address delay, incorrectly initialized.  Phase: %d, cmda_odly_lin=%d"%(phase,cmda_odly_lin))
1628 1629
                        print ("=== resetting ===")
                        self.x393_pio_sequences.restart_ddr3()
1630 1631 1632 1633 1634 1635 1636 1637 1638
                        
#                        wlev_rslt = norm_wlev(self.x393_pio_sequences.write_levelling(1, nbursts, -1)) # quiet - 1))
                        if self.wlev_all_bits: # try to vary DQS input delay
                            wlev_rslt = norm_wlev(self.write_levelling_allbits(1, nbursts, quiet+1))        
                        else:        
                            wlev_rslt = norm_wlev(self.x393_pio_sequences.write_levelling(1, nbursts, quiet+1))
                        bad_wlev = wlev_rslt[2 + (0,1)[self.wlev_all_bits]]
                        if bad_wlev > wlev_max_bad: # should be 0 - otherwise wlev did not work (CMDA?)
                            print ("Second try: raise Exception Write leveling gave unexpected data, aborting (may be wrong command/address delay, incorrectly initialized.  Phase: %d, cmda_odly_lin=%d"%(phase,cmda_odly_lin))
1639
                            self.x393_pio_sequences.restart_ddr3()
1640 1641 1642
                    dqso_cache[dly] = wlev_rslt
                    if quiet < 1:
                        print ('measure_dqso(%d) - new measurement'%(dly))
1643
                else:
1644 1645 1646 1647 1648 1649 1650 1651 1652
                    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)
1653 1654 1655 1656 1657 1658
            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)
1659
            self.x393_mcntrl_timing.axi_set_cmda_odelay(combine_delay(cmda_odly_lin),quiet=quiet)
1660 1661
            d_low=0
            while d_low <= max_lin_dly:
1662
                wlev_rslt=measure_dqso(d_low)
1663 1664 1665
                if (wlev_rslt[0] <= wlev_max_bad) and (wlev_rslt[1] <= wlev_max_bad):
                    break
                d_low+=dly90
1666
            else:
1667 1668 1669 1670 1671 1672
                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:
1673
                wlev_rslt=measure_dqso(d_high)
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
                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
1687
                wlev_rslt=measure_dqso(dly)
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
                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]
1701
            for i in range(numLanes):
1702 1703 1704 1705
                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))
1706
                    wlev_rslt=measure_dqso(dly)
1707 1708 1709 1710 1711 1712
                    if wlev_rslt[i] <= wlev_max_bad:
                        if d_low[i] == dly:
                            break
                        d_low[i]=dly
                    else:
                        d_high[i]=dly
1713
            #return d_low
1714

1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
            # 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