add internal-to-external bond number conversion
[pinmux.git] / src / spec / ifaceprint.py
index 5236a03e4f06985080e1d3999ae20663f9c126ae..f8ba09d4e2bc20aae985946699d895afb9059d5e 100644 (file)
 #!/usr/bin/env python
 
 from copy import deepcopy
-
-
-def display(pins):
-    print "| Pin | Mux0        | Mux1        | Mux2        | Mux3        |"
-    print "| --- | ----------- | ----------- | ----------- | ----------- |"
+from collections import OrderedDict
+from math import pi
+
+def bond_int_to_ext(pin, bank):
+    """ note that internal numbering is 0-31 whereas the DISPLAY internal
+        numbering is 1-32.  this uses the INTERNAL numbering.
+
+        side: N S E W
+
+        outer ring numbers: the python list order of the outer pads
+        middle numbers: the package number wires (plus side they are on)
+        inner numbers:  the IO pad *python internal (0-31)* numbers plus side
+
+       0     1   2      3   N  34     35   36   37
+      N102 N101 N100    99  N  68    N67  N66  N65
+      W29  W30  W31     N0  N N31    E29  E30  E31
+
+    25  103 W28                       E28  64 25
+     W    W  W                         E  E   E
+     0  128 W3                        E3  39  0
+
+      W2  W1   W0      S0   S S31    E0   E1   E2
+      S1  S2   S3       4   S  35    S36  S37  S38
+       0     1   2      3   S  34     35   36   37
+
+    """
+    # returns side, order-on-the-side, pin number
+    if bank == 'N':
+        return 'N', pin+3, 99-pin
+    if bank == 'S':
+        return 'S', pin+3, 4+pin
+    if bank == 'W':
+        if pin >= 29: # 29, 30, 31
+            return 'N', pin-29, 100+(31-pin)
+        if pin <= 2:
+            return 'S', 2-pin, 3-pin
+        return 'W', pin-3, 103+(28-pin)
+    if bank == 'E':
+        if pin >= 29:
+            return 'N', pin+6, 67-(pin-29)
+        if pin <= 2:
+            return 'S', pin+35, 36+pin
+        return 'E', pin-3, 39+(pin-3)
+
+
+def create_sv(fname, pins):
+    """unsophisticated drawer of an SVG
+    """
+
+    try:
+        import svgwrite
+    except ImportError:
+        print ("WARNING, no SVG image, not producing image %s" % fname)
+        return
+
+    # create internal to external map
+    bondmap = {'N': {}, 'S': {},  'E': {},  'W': {} }
+    padside = {'pads.north': 'N', 'pads.east': 'E', 'pads.south': 'S',
+               'pads.west': 'W'}
+    for pinpad, bank in padside.items():
+        for ipin in range(len(pins[pinpad])):
+            eside, enum, epinnum = bond_int_to_ext(ipin, bank)
+            bondmap[eside][enum] = (epinnum, ipin, bank)
+    with open("/tmp/bondmap.txt", "w") as f:
+        for k,v in bondmap.items():
+            f.write("%s\n" % k)
+            for enum, (epinnum, ipin, bank) in v.items():
+                f.write("    %d %d  -> %s %d\n" % (enum, epinnum, bank, ipin))
+
+    scale = 15
+    width = len(pins['pads.north']) * scale
+    height = len(pins['pads.east']) * scale
+    woffs = scale*40#-width/2
+    hoffs = scale*40#-height/2
+
+    dwg = svgwrite.Drawing(fname, profile='full',
+                           size=(width+scale*80, height+scale*80))
+    dwg.add(dwg.rect((woffs-scale*2, hoffs-scale*2),
+                        (woffs+width-scale*34, hoffs+height-scale*34),
+            stroke=svgwrite.rgb(16, 255, 16, '%'),
+            stroke_width=scale/10.0))
+
+    dwg.add(dwg.text("Libre-SOC ls180 QFP-128",
+                       insert=(woffs+width/2-scale*5, woffs+height/2),
+                     fill='white'))
+    dwg.add(dwg.text("In collaboration with LIP6.fr",
+                       insert=(woffs+width/2-scale*5, woffs+height/2+scale),
+                     fill='white'))
+    dwg.add(dwg.text("Cell Libraries by Chips4Makers",
+                       insert=(woffs+width/2-scale*5, woffs+height/2+scale*2),
+                     fill='white'))
+
+    outerpos = {'N': {}, 'S': {},  'E': {},  'W': {} }
+    for i, pin in enumerate(pins['pads.west']):
+        ht = hoffs + height - (i * scale) + scale*0.5
+        endline = (woffs-scale*4.5, ht-scale*0.5)
+        dwg.add(dwg.line((woffs-scale*2, ht-scale*0.5),
+                         endline,
+                         stroke=svgwrite.rgb(16, 255, 16, '%'),
+                         stroke_width=scale/10.0))
+        dwg.add(dwg.text(pin.upper(), insert=(woffs-scale*14, ht),
+                         fill='black'))
+        dwg.add(dwg.text("W%d" % (i+1), insert=(woffs-scale*1.5, ht),
+                            fill='white'))
+
+    for i, pin in enumerate(pins['pads.east']):
+        ht = hoffs + height - (i * scale) + scale*0.5
+        wd = width + woffs + scale*2
+        endline = (wd+scale*4.5, ht-scale*0.5)
+        dwg.add(dwg.line((wd+scale*2, ht-scale*0.5),
+                         endline,
+                         stroke=svgwrite.rgb(16, 255, 16, '%'),
+                         stroke_width=scale/10.0))
+        dwg.add(dwg.text(pin.upper(), insert=(wd+scale*5, ht-scale*0.25),
+                         fill='black'))
+        dwg.add(dwg.text("E%d" % (i+1), insert=(wd, ht-scale*0.25),
+                            fill='white'))
+
+    for i, pin in enumerate(pins['pads.north']):
+        wd = woffs + i * scale + scale*1.5
+        endline = (wd, hoffs-scale*4.5)
+        dwg.add(dwg.line((wd, hoffs-scale*2),
+                         endline,
+                         stroke=svgwrite.rgb(16, 255, 16, '%'),
+                         stroke_width=scale/10.0))
+        pos=(wd, hoffs-scale*5.0)
+        txt = dwg.text(pin.upper(), insert=pos, fill='black')
+        txt.rotate(-90, pos)
+        dwg.add(txt)
+        pos=(wd+scale*0.25, hoffs-scale*0.25)
+        txt = dwg.text("N%d" % (i+1), insert=pos, fill='white')
+        txt.rotate(-90, pos)
+        dwg.add(txt)
+
+    for i, pin in enumerate(pins['pads.south']):
+        wd = woffs + i * scale + scale*1.5
+        ht = hoffs + height + scale*2
+        endline = (wd, ht+scale*4.5)
+        dwg.add(dwg.line((wd, ht+scale*2),
+                         endline,
+                         stroke=svgwrite.rgb(16, 255, 16, '%'),
+                         stroke_width=scale/10.0))
+        pos=(wd-scale*0.25, ht+scale*5.0)
+        txt = dwg.text(pin.upper(), insert=pos, fill='black')
+        txt.rotate(90, pos)
+        dwg.add(txt)
+        pos=(wd-scale*0.25, ht+scale*0.25)
+        txt = dwg.text("S%d" % (i+1), insert=pos, fill='white')
+        txt.rotate(90, pos)
+        dwg.add(txt)
+
+    dwg.save()
+
+
+def display(of, pins, banksel=None, muxwidth=4):
+    of.write("""\
+| Pin | Mux0        | Mux1        | Mux2        | Mux3        |
+| --- | ----------- | ----------- | ----------- | ----------- |
+""")
     pinidx = sorted(pins.keys())
     for pin in pinidx:
         pdata = pins.get(pin)
+        if banksel:
+            skip = False
+            for mux in range(muxwidth):
+                if mux not in pdata:
+                    continue
+                name, bank = pdata[mux]
+                if banksel != bank:
+                    skip = True
+            if skip:
+                continue
         res = '| %3d |' % pin
-        for mux in range(4):
+        for mux in range(muxwidth):
             if mux not in pdata:
                 res += "             |"
                 continue
             name, bank = pdata[mux]
             res += " %s %-9s |" % (bank, name)
-        print res
+        of.write("%s\n" % res)
 
 
 def fnsplit(f):
@@ -49,12 +213,108 @@ def find_fn(fname, names):
         if fname.startswith(n):
             return n
 
+def map_name(pinmap, fn, fblower, pin, rename):
+    if not rename:
+        if pin[:-1].isdigit():
+            print "map name digit", pin, fn, fblower
+            if fn in ['PWM', 'EINT', 'VDD', 'VSS']:
+                return fn.lower() + pin.lower()
+        if fn == 'GPIO':
+            return 'gpio' + pin[1:].lower()
+        return pin.lower()
+    pin = pin.lower()
+    if fn == 'GPIO':
+        pk = '%s%s_%s' % (fblower, pin[0], pin[:-1])
+    elif pin[:-1].isdigit() and fn != 'EINT':
+        pk = '%s%s_out' % (fblower, pin[:-1])
+    else:
+        pk = '%s_%s' % (fblower, pin[:-1])
+    print "map name", pk, fblower, pinmap.has_key(pk)
+    if not pinmap.has_key(pk):
+        return pin.lower()
+    remapped = pinmap[pk]
+    uscore = remapped.find('_')
+    if uscore == -1:
+        return pin.lower()
+    fn, pin = remapped[:uscore], remapped[uscore+1:] + pin[-1]
+    return pin.lower()
+
+def python_pindict(of, pinmap, pins, function_names, dname, remap):
+
+    res = OrderedDict()
+    of.write("\n%s = OrderedDict()\n" % dname)
+
+    for k, pingroup in pins.byspec.items():
+        (a, n) = k.split(":")
+        if n.isdigit():
+            a = "%s%s" % (a, n)
+        fblower = a.lower()
+        of.write("%s['%s'] = [ " % (dname, fblower))
+        res[fblower] = []
+        count = 0
+        for i, p in enumerate(pingroup):
+            name = map_name(pinmap, k[0], fblower, p, remap)
+            res[fblower].append(name)
+            of.write("'%s', " % name)
+            count += 1
+            if count == 4 and i != len(pingroup)-1:
+                of.write("\n                ")
+                count = 0
+        of.write("]\n")
+        print "    dict %s" % dname, a, n, pingroup
+    of.write("\n\n")
+    return res
+
+def python_dict_fns(of, pinmap, pins, function_names):
+    of.write("# auto-generated by Libre-SOC pinmux program: do not edit\n")
+    of.write("# python src/pinmux_generator.py -v -s {spec} -o {output}\n")
+    of.write("# use OrderedDict to fix stable order for JTAG Boundary Scan\n")
+    of.write("from collections import OrderedDict\n")
+
+    fn_names = function_names.keys()
+    fns = {}
 
-def display_fns(bankspec, pins, function_names):
+    fnidx = list(fns.keys())
+    fnidx.sort(key=fnsplit)
+
+    print "python fnames", function_names
+    print "python speckeys", pins.byspec.keys()
+    print "python dict fns", dir(pins.gpio)
+    print pins.gpio.pinfn('', '')
+    print pins.pwm.pinfn('', '')
+    print pins.sdmmc.pinfn('', '')
+    print "by spec", pins.byspec
+    print pinmap
+
+    pd = python_pindict(of, {}, pins, function_names, 'pindict', False)
+    ld = python_pindict(of, pinmap, pins, function_names, 'litexdict', True)
+
+    print "pd", pd
+    print "ld", ld
+    # process results and create name map
+    litexmap = OrderedDict()
+    for k in pd.keys():
+        pl = pd[k]
+        ll = ld[k]
+        for pname, lname in zip(pl, ll):
+            pname = "%s_%s" % (k, pname[:-1]) # strip direction +/-/*
+            lname = lname[:-1] # strip direction +/-/*
+            if k in ['eint', 'pwm', 'gpio', 'vdd', 'vss']: # sigh
+                lname = "%s_%s" % (k, lname)
+            litexmap[pname] = lname
+    print "litexmap", litexmap
+    of.write("litexmap = {\n")
+    for k, v in litexmap.items():
+        of.write("\t'%s': '%s',\n" % (k, v))
+    of.write("}\n")
+    return litexmap
+
+
+def display_fns(of, bankspec, pins, function_names):
     fn_names = function_names.keys()
     fns = {}
     for (pin, pdata) in pins.items():
-        for mux in range(1, 4):  # skip GPIO for now
+        for mux in range(0, 4):  # skip GPIO for now
             if mux not in pdata:
                 continue
             name, bank = pdata[mux]
@@ -63,44 +323,49 @@ def display_fns(bankspec, pins, function_names):
                 fns[name] = []
             fns[name].append((pin - bankspec[bank], mux, bank))
 
-    fnidx = fns.keys()
-    fnidx.sort(fnsort)
+    fnidx = list(fns.keys())
+    fnidx.sort(key=fnsplit)
     current_fn = None
     for fname in fnidx:
         fnbase = find_fn(fname, fn_names)
+        #fblower = fnbase.lower()
+        assert fnbase in function_names, "fn %s not in descriptions %s" % \
+            (fname, str(function_names.keys()))
         #print "name", fname, fnbase
         if fnbase != current_fn:
             if current_fn is not None:
-                print
-            print "## %s" % fnbase
-            print
-            print function_names[fnbase]
-            print
+                of.write('\n')
+            of.write("## %s\n\n%s\n\n" % (fnbase, function_names[fnbase]))
             current_fn = fnbase
-        print "* %-9s :" % fname,
+        of.write("* %-9s :" % fname)
         for (pin, mux, bank) in fns[fname]:
-            print "%s%d/%d" % (bank, pin, mux),
-        print
+            of.write(" %s%d/%d" % (bank, pin, mux))
+        of.write('\n')
 
     return fns
 
 
-def check_functions(title, bankspec, fns, pins, required, eint, pwm,
+def check_functions(of, title, bankspec, fns, pins, required, eint, pwm,
                     descriptions=None):
     fns = deepcopy(fns)
     pins = deepcopy(pins)
     if descriptions is None:
         descriptions = {}
+    fnidx = fns.keys()
+
+    #print dir(fns)
+    #print dir(pins)
 
-    print "# Pinmap for %s" % title
-    print
+    of.write("# Pinmap for %s\n\n" % title)
 
+    print "fn_idx", fnidx
+    print "fns", fns
+    print "fnspec", pins.fnspec.keys()
+    print "required", required
     for name in required:
-        print "## %s" % name
-        print
+        of.write("## %s\n\n" % name)
         if descriptions and name in descriptions:
-            print descriptions[name]
-            print
+            of.write("%s\n\n" % descriptions[name])
 
         name = name.split(':')
         if len(name) == 2:
@@ -117,13 +382,21 @@ def check_functions(title, bankspec, fns, pins, required, eint, pwm,
         else:
             count = 100000
         name = name[0]
+        #print name
         found = set()
-        fnidx = fns.keys()
-        # fnidx.sort(fnsort)
         pinfound = {}
+        located = set()
         for fname in fnidx:
             if not fname.startswith(name):
                 continue
+            for k in pins.fnspec.keys():
+                if fname.startswith(k):
+                    fk = list(pins.fnspec[k].keys())
+                    fn = pins.fnspec[k]
+                    fn = fn[fk[0]]
+                    #print fname, fn, dir(fn)
+                    if count == 100000:
+                        count = len(fn.pingroup)
             for pin, mux, bank in fns[fname]:
                 if findbank is not None:
                     if findbank != bank:
@@ -136,6 +409,9 @@ def check_functions(title, bankspec, fns, pins, required, eint, pwm,
 
         pinidx = sorted(pinfound.keys())
 
+        fname = None
+        removedcount = 0
+        print ("pinidx", pinidx)
         for pin_ in pinidx:
             fname, pin_, bank, pin, mux = pinfound[pin_]
             if fname in found:
@@ -144,9 +420,20 @@ def check_functions(title, bankspec, fns, pins, required, eint, pwm,
             if len(found) > count:
                 continue
             del pins[pin_]
-            print "* %s %d %s%d/%d" % (fname, pin_, bank, pin, mux)
+            removedcount += 1
+            of.write("* %s %d %s%d/%d\n" % (fname, pin_, bank, pin, mux))
+
+        print fns
+        if removedcount != count:
+            if fname is None:
+                print "no match between required and available pins"
+            else:
+                print ("not all found", name, removedcount, count, title, found,
+                   fns[fname])
+            print ("pins found", pinfound)
 
-        print
+        # fnidx.sort(fnsort)
+        of.write('\n')
 
     # gpios
     gpios = []
@@ -159,8 +446,7 @@ def check_functions(title, bankspec, fns, pins, required, eint, pwm,
     gpios.sort()
 
     if gpios:
-        print "## GPIO"
-        print
+        of.write("## GPIO\n\n")
 
         for fname in gpios:
             if fname in found:
@@ -175,28 +461,25 @@ def check_functions(title, bankspec, fns, pins, required, eint, pwm,
                 continue
             del pins[pin_]
             found.add(fname)
-            print "* %-8s %d %s%-2d %s" % (fname, pin_, bank, pin, desc)
-        print
+            of.write("* %-8s %d %s%-2d %s\n" % (fname, pin_, bank, pin, desc))
+        of.write('\n')
 
     if eint:
-        display_group(bankspec, "EINT", eint, fns, pins, descriptions)
+        display_group(of, bankspec, "EINT", eint, fns, pins, descriptions)
     if pwm:
-        display_group(bankspec, "PWM", pwm, fns, pins, descriptions)
+        display_group(of, bankspec, "PWM", pwm, fns, pins, descriptions)
 
-    print "## Unused Pinouts (spare as GPIO) for '%s'" % title
-    print
+    of.write("## Unused Pinouts (spare as GPIO) for '%s'\n\n" % title)
     if descriptions and 'GPIO' in descriptions:
-        print descriptions['GPIO']
-        print
-    display(pins)
-    print
+        of.write("%s\n\n" % descriptions['GPIO'])
+    display(of, pins)
+    of.write('\n')
 
     return pins  # unused
 
 
-def display_group(bankspec, title, todisplay, fns, pins, descriptions):
-    print "## %s" % title
-    print
+def display_group(of, bankspec, title, todisplay, fns, pins, descriptions):
+    of.write("## %s\n\n" % title)
 
     found = set()
     for fname in todisplay:
@@ -225,38 +508,38 @@ def display_group(bankspec, title, todisplay, fns, pins, descriptions):
                 continue
             del pins[pin_]
             found.add(fname)
-            print "* %s %d %s%d/%d %s" % (fname, pin_, bank, pin, mux, desc)
-    print
+            of.write("* %s %d %s%d/%d %s\n" %
+                     (fname, pin_, bank, pin, mux, desc))
+    of.write('\n')
 
 
-def display_fixed(fixed, offs):
+def display_fixed(of, fixed, offs):
 
     fkeys = sorted(fixed.keys())
     pin_ = offs
     res = []
     for pin, k in enumerate(fkeys):
-        print "## %s" % k
-        print
+        of.write("## %s\n\n" % k)
         prevname = ''
         linecount = 0
         for name in fixed[k]:
             if linecount == 4:
                 linecount = 0
-                print
+                of.write('\n')
             if prevname[:2] == name[:2] and linecount != 0:
-                print name,
+                of.write(" %s" % name)
                 linecount += 1
             else:
                 if linecount != 0:
-                    print
-                print "* %d: %d %s" % (pin_, pin, name),
+                    of.write('\n')
+                of.write("* %d: %d %s" % (pin_, pin, name))
                 linecount = 1
                 res.append((pin_, name))
 
             prevname = name
             pin_ += 1
         if linecount != 0:
-            print
-        print
+            of.write('\n')
+        of.write('\n')
 
     return res