x393_mem.py 18.7 KB
Newer Older
1
from __future__ import print_function
2 3 4 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 31 32 33
'''
# Copyright (C) 2015, Elphel.inc.
# Memory read/write functions 
# 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"
import mmap
#import sys
import struct
34
import os
35
import sys
Andrey Filippov's avatar
Andrey Filippov committed
36
#import traceback
37 38 39 40 41 42 43

sys.path.append(os.path.abspath(os.path.dirname(sys.argv[0])+'/../cocotb'))
from socket_command import x393Client

DBG_CNTR=0
X393_CLIENT = None

44 45 46 47
class X393Mem(object):
    '''
    classdocs
    '''
48
    DRY_MODE= True # True
49 50 51
    PAGE_SIZE=4096
    DEBUG_MODE=1
    ENDIAN="<" # little, ">" for big
52 53 54 55 56
    MAXI0_BASE=0x40000000
    MAXI1_BASE=0x80000000
    MAXI_BASE = MAXI0_BASE
    USE_NEGATIVE = True # Old versions of Python (2.7.3) required mmap offset to fit into 32 bits, so upper half had to be negative
                        # 2.7.11 does not need subtraction(and reports error if negative)
57

58
    def __init__(self, debug_mode=1,dry_mode=False, maxi_port=0):
59 60 61 62 63 64
        global DBG_CNTR
        global X393_CLIENT
        """
        print('dry_mode = ',dry_mode,', DBG_CNTR=',DBG_CNTR)
        traceback.print_stack()
        """
65 66 67 68
        if not dry_mode:
            if not os.path.exists("/dev/xdevcfg"):
                dry_mode=True
                print("Program is forced to run in SIMULATED mode as '/dev/xdevcfg' does not exist (not a camera)")
69
        self.DRY_MODE=dry_mode
70
        if (dry_mode) and (X393_CLIENT is None):
Andrey Filippov's avatar
Andrey Filippov committed
71 72 73 74 75 76 77 78 79 80
            if ":" in dry_mode:
                print("Creating X393_CLIENT")
                try:
                    X393_CLIENT= x393Client(host=dry_mode.split(":")[0], port=int(dry_mode.split(":")[1]))
                    print("Created X393_CLIENT")
                except:
                    X393_CLIENT= True
                    print("Failed to create X393_CLIENT")
            else:
                X393_CLIENT= True # just will not complain "Failed to create..."
81 82 83 84 85
            if not X393_CLIENT is True:
                print("Starting X393_CLIENT")
                try:
                    X393_CLIENT.start()
                except:
Andrey Filippov's avatar
Andrey Filippov committed
86
                    print ("Failed to communicate to the server. Is it started? Switching to dry run mode")
87 88 89 90 91 92 93 94 95
                    X393_CLIENT = True
                    
                
        DBG_CNTR+=1
        if maxi_port:
            self.MAXI_BASE=self.MAXI1_BASE
        else:    
            self.MAXI_BASE=self.MAXI0_BASE;
        self.DEBUG_MODE=debug_mode
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    def maxi_base(self, maxi_port=None):
        if not maxi_port is None:
            if maxi_port:
                self.MAXI_BASE=self.MAXI1_BASE
            else:    
                self.MAXI_BASE=self.MAXI0_BASE;
        else:
            maxi_port = (0,1)[self.MAXI_BASE == self.MAXI1_BASE]
        print ("MAXI port = %d (0x%08x)"%(maxi_port, self.MAXI_BASE))       

    def wrap_mm (self, f, page_addr):
        if page_addr>=0x80000000:
            if (self.USE_NEGATIVE):
                try:
                    return mmap.mmap(f.fileno(), self.PAGE_SIZE, offset = page_addr - (1<<32))
                except:
                    self.USE_NEGATIVE = False
                    if self.DEBUG_MODE:
                        print ("Turning OFF use of negative offsets in mmap")
                    return mmap.mmap(f.fileno(), self.PAGE_SIZE, offset = page_addr)
            else:
                try:
                    return mmap.mmap(f.fileno(), self.PAGE_SIZE, offset = page_addr)
                except:
                    print ("Turning ON use of negative offsets in mmap")
                    self.USE_NEGATIVE = True
                    return mmap.mmap(f.fileno(), self.PAGE_SIZE, offset = page_addr - (1<<32))
        else:
124
            return mmap.mmap(f.fileno(), self.PAGE_SIZE, offset = page_addr)
125 126 127 128 129 130 131 132 133 134 135 136 137 138
    def finish(self):
        """
        Finish simulation, if server is opened
        """
        global X393_CLIENT
        if X393_CLIENT is None:
            print ("Not running in simulated mode")
            return
        elif X393_CLIENT is True:
            print ("Not running as a client to x393 simulation server")
            return
        else:
            X393_CLIENT.stop()
            X393_CLIENT = True # just simulated mode
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
    def flush_simulation(self):
        """
        Flush simulation 'system memory" file
        """
        global X393_CLIENT
        if X393_CLIENT is None:
            print ("flush_simulation(): Not running in simulated mode")
            return
        elif X393_CLIENT is True:
            print ("flush_simulation(): Not running as a client to x393 simulation server")
            return
        else:
            X393_CLIENT.flush()
    def wait_irq(self,irq_mask= 0, wait_ns = 1000):
        """
154
        Wait simulation certain time (in ns), interruptible
155 156 157 158 159 160 161 162 163 164 165 166 167
        @param irq_mask - mask to be AND-ed with interrupt vector
        @param wait_ns - timeout in nanoseconds
        """
        global X393_CLIENT
        if X393_CLIENT is None:
            print ("wait_irq(): Not running in simulated mode")
            return
        elif X393_CLIENT is True:
            print ("wait_irq(): Not running as a client to x393 simulation server")
            return
        else:
            X393_CLIENT.waitIrq(irq_mask, wait_ns)

168
    def write_mem (self,addr, data,quiet=1):
169 170
        """
        Write 32-bit word to physical memory
171 172 173
        @param addr - physical byte address
        @param data - 32-bit data to write
        @param quiet - reduce output
174
        """
175
        if X393_CLIENT is True:
176
            print ("simulated: write_mem(0x%x,0x%x)"%(addr,data))
177
            return
178 179 180 181
        elif not X393_CLIENT is None:
            if quiet < 1:
                print ("remote: write_mem(0x%x,0x%x)"%(addr,data))
            X393_CLIENT.write(addr, [data])
182
            if quiet < 1:
183 184
                print ("remote: write_mem done" )
            return
185 186 187
        with open("/dev/mem", "r+b") as f:
            page_addr=addr & (~(self.PAGE_SIZE-1))
            page_offs=addr-page_addr
188
            mm = self.wrap_mm(f, page_addr)
189 190 191
            packedData=struct.pack(self.ENDIAN+"L",data)
            d=struct.unpack(self.ENDIAN+"L",packedData)[0]
            mm[page_offs:page_offs+4]=packedData
192
            if quiet < 1:
193
                print ("0x%08x <== 0x%08x (%d)"%(addr,d,d))
194

195
    def read_mem (self,addr,quiet=1):
196
        '''
197 198 199
        Read 32-bit word from physical memory
        @param addr  physical byte address
        @param quiet - reduce output
200 201 202 203 204 205 206 207 208 209 210 211 212
        '''  
        if X393_CLIENT is True:
#        if self.DRY_MODE:
            print ("simulated: read_mem(0x%x)"%(addr))
            return addr # just some data
        elif not X393_CLIENT is None:
            if quiet < 1:
                print ("remote: read_mem(0x%x)"%(addr))
            data= X393_CLIENT.read(addr)
            if quiet < 1:
                print ("remote: read_mem done: 0x%08x"%(data[0]))
            return data[0]
          
213
        if self.DRY_MODE:
214
            print ("simulated: read_mem(0x%x)"%(addr))
215
            return addr # just some data
216 217 218
        with open("/dev/mem", "r+b") as f:
            page_addr=addr & (~(self.PAGE_SIZE-1))
            page_offs=addr-page_addr
219
            mm = self.wrap_mm(f, page_addr)
220 221
#            if (page_addr>=0x80000000):
#                page_addr-= (1<<32)
222
#            mm = mmap.mmap(f.fileno(), self.PAGE_SIZE, offset=page_addr)
223 224
            data=struct.unpack(self.ENDIAN+"L",mm[page_offs:page_offs+4])
            d=data[0]
225
            if quiet < 1:
226 227
                print ("0x%08x ==> 0x%08x (%d)"%(addr,d,d))
            return d
228 229

    def mem_dump (self, start_addr, end_addr=1, byte_mode=4):
230 231
        '''
         Read and print memory range from physical memory
232 233 234 235
         @param start_addr physical byte start address
         @param end_addr  physical byte end address (inclusive), if negative/less than start_addr - number of items
         @param byte_mode number of bytes per item (1,2,4,8)
         @return list of read values
236
        '''
237 238 239 240 241 242 243 244 245 246 247 248 249 250
        frmt_bytes={1:'B',2:'H',4:'L',8:'Q'}
        bytes_per_line_mask={1:0x1f,2:0x1f,4:0x3f,8:0x3f}
        default_byte_mode=4
        if not byte_mode in frmt_bytes.keys():
            print ("Invalid byte mode: '%s'. Only %s are supported. Using %d"%(str(byte_mode),str(frmt_bytes.keys()),default_byte_mode))
            byte_mode=default_byte_mode
        data_frmt=  "%%0%dx"%(2*byte_mode)
        simul_mask= (1 << (8*byte_mode)) -1
        addr_mask=0xffffffff ^ (byte_mode-1)
        start_addr &= addr_mask
        if end_addr < start_addr:
            end_addr=start_addr + abs(end_addr*byte_mode) -1
        end_addr  &= addr_mask
#       align start address to 32-bit word even if the mode is byte/short        
251
        start_addr &= 0xfffffffc
252
        print_mask=bytes_per_line_mask[byte_mode]
253 254
        rslt=[]
        if self.DRY_MODE:
255
            rslt=[d & simul_mask for d in range(start_addr,end_addr+byte_mode,byte_mode)]
256 257
        else:
            with open("/dev/mem", "r+b") as f:
258
                for addr in range (start_addr,end_addr+byte_mode,byte_mode):
259 260
                    page_addr=addr & (~(self.PAGE_SIZE-1))
                    page_offs=addr-page_addr
261 262 263 264
                    mm = self.wrap_mm(f, page_addr)
        #            if (page_addr>=0x80000000):
        #                page_addr-= (1<<32)
        #            mm = mmap.mmap(f.fileno(), self.PAGE_SIZE, offset=page_addr)
265
                    data=struct.unpack_from(self.ENDIAN+frmt_bytes[byte_mode],mm, page_offs)
266 267
                    rslt.append(data[0])
                    
268 269
        for addr in range (start_addr,end_addr+byte_mode,byte_mode):
            if (addr == start_addr) or ((addr & print_mask) == 0):
270 271 272 273
                if self.DRY_MODE:
                    print ("\nsimulated: 0x%08x:"%addr,end="")
                else:     
                    print ("\n0x%08x:"%addr,end="")
274 275
            d=rslt[(addr-start_addr) // byte_mode]
            print (data_frmt%(d),end=" ")
276 277
        print("")
        return rslt    
278

279 280 281 282 283 284 285 286 287 288
    def mem_save (self, filename, start_addr, length):
        '''
         Save physical memory content to a file
         @param filename - path to a file
         @param start_addr physical byte start address
         @param length - number of bytes to save
        '''
        if self.DRY_MODE:
            print ("Write memory to file is not implemented in non-target mode")
            return
289 290 291 292 293 294 295 296 297 298 299 300
        with open(filename, "w+b") as bf:
            self._mem_write_to_file (bf =         bf,
                                     start_addr = start_addr,
                                     length =     length)

    def _mem_write_to_file (self, bf, start_addr, length):
        '''
         Save physical memory content to a file
         @param bf - file open in write mode
         @param start_addr physical byte start address
         @param length - number of bytes to save
        '''
301
        if self.DRY_MODE == True:
302 303
            print ("Write memory to file is not implemented in non-target mode")
            return
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
        elif self.DRY_MODE: # Cocotb over socket
            first_page = start_addr // self.PAGE_SIZE
            last_page = (start_addr + length - 1) // self.PAGE_SIZE
            for page_num in range(first_page, last_page+1):
                start_offset = 0
                if page_num == first_page:
                    start_offset = start_addr - self.PAGE_SIZE * page_num
                end_offset =  self.PAGE_SIZE
                if page_num == last_page:
                    end_offset = start_addr + length - self.PAGE_SIZE * page_num
                page_addr = page_num * self.PAGE_SIZE
                page_data= X393_CLIENT.read((page_addr, self.PAGE_SIZE//4)) # always read memory page (as in mmap)
                mm = struct.pack("<"+("L"*(self.PAGE_SIZE//4)),*page_data)
                bf.write(mm[start_offset:end_offset])
#                mm = self.wrap_mm(f, page_addr)
#                bf.write(mm[start_offset:end_offset])
            return    
321 322 323 324 325 326 327 328 329 330 331
        with open("/dev/mem", "r+b") as f:
            first_page = start_addr // self.PAGE_SIZE
            last_page = (start_addr + length - 1) // self.PAGE_SIZE
            for page_num in range(first_page, last_page+1):
                start_offset = 0
                if page_num == first_page:
                    start_offset = start_addr - self.PAGE_SIZE * page_num
                end_offset =  self.PAGE_SIZE
                if page_num == last_page:
                    end_offset = start_addr + length - self.PAGE_SIZE * page_num
                page_addr = page_num * self.PAGE_SIZE 
332 333 334 335
                mm = self.wrap_mm(f, page_addr)
    #            if (page_addr>=0x80000000):
    #                page_addr-= (1<<32)
    #            mm = mmap.mmap(f.fileno(), self.PAGE_SIZE, offset=page_addr)
336
                bf.write(mm[start_offset:end_offset])
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359

    def mem_clear (self, start_addr, length, word32):
        '''
         Fill physical memory range with a repetitive 32-bit word
         @param start_addr physical byte start address
         @param length - number of bytes to save
         @param word32 - 32-bit pattern
        '''
        if self.DRY_MODE:
            print ("Write memory to file is not implemented in non-target mode")
            return
        patt=str(bytearray(((word32 & 0xff), ((word32 >> 8) & 0xff), ((word32 >> 16) & 0xff), ((word32 >> 24) & 0xff)))*(self.PAGE_SIZE/4))
        with open("/dev/mem", "r+b") as f:
            first_page = start_addr // self.PAGE_SIZE
            last_page = (start_addr + length - 1) // self.PAGE_SIZE
            for page_num in range(first_page, last_page+1):
                start_offset = 0
                if page_num == first_page:
                    start_offset = start_addr - self.PAGE_SIZE * page_num
                end_offset =  self.PAGE_SIZE
                if page_num == last_page:
                    end_offset = start_addr + length - self.PAGE_SIZE * page_num
                page_addr = page_num * self.PAGE_SIZE 
360 361 362 363
                mm = self.wrap_mm(f, page_addr)
    #            if (page_addr>=0x80000000):
    #                page_addr-= (1<<32)
    #            mm = mmap.mmap(f.fileno(), self.PAGE_SIZE, offset=page_addr)
364 365 366
                mm[start_offset:end_offset] = patt[start_offset:end_offset]


367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
    def mem_fill (self, start_addr, start_data=0, end_addr=1, inc_data=0, byte_mode=4):
        '''
         Read and print memory range from physical memory
         @param start_addr physical byte start address
         @param start_data data/start data to write
         @param end_addr  physical byte end address (inclusive), if negative/less than start_addr - number of items
         @param inc_data increment each next item by this value
         @param byte_mode number of bytes per item (1,2,4,8)
        '''
        frmt_bytes={1:'B',2:'H',4:'L',8:'Q'}
        default_byte_mode=4
        if not byte_mode in frmt_bytes.keys():
            print ("Invalid byte mode: '%s'. Only %s are supported. Using %d"%(str(byte_mode),str(frmt_bytes.keys()),default_byte_mode))
            byte_mode=default_byte_mode
        data_mask= (1 << (8*byte_mode)) -1
        addr_mask=0xffffffff ^ (byte_mode-1)
        start_addr &= addr_mask
        if end_addr < start_addr:
            end_addr=start_addr + abs(end_addr*byte_mode) -1
        end_addr  &= addr_mask
#       align start address to 32-bit word even if the mode is byte/short        
        start_addr &= 0xfffffffc
        if self.DRY_MODE:
            print ("Simulated mem_fill(0x%x, 0x%x, 0x%x, 0x%x, %d)"%(start_addr, start_data, end_addr, inc_data, byte_mode))
            data_frmt=  "%%0%dx"%(2*byte_mode)
            for addr in range (start_addr,end_addr+byte_mode,byte_mode):
                data = (start_data + ((addr-start_addr) // byte_mode)*inc_data) & data_mask
                page_addr=addr & (~(self.PAGE_SIZE-1))
                page_offs=addr-page_addr
396 397
                if (page_addr>=0x80000000):
                    page_addr-= (1<<32)
398 399 400 401 402 403 404
                print (("0x%08x: "+ data_frmt)%(addr,data))
        else:
            with open("/dev/mem", "r+b") as f:
                for addr in range (start_addr,end_addr+byte_mode,byte_mode):
                    data = (start_data + ((addr-start_addr) // byte_mode)*inc_data) & data_mask
                    page_addr=addr & (~(self.PAGE_SIZE-1))
                    page_offs=addr-page_addr
405 406 407 408
                    mm = self.wrap_mm(f, page_addr)
        #            if (page_addr>=0x80000000):
        #                page_addr-= (1<<32)
        #            mm = mmap.mmap(f.fileno(), self.PAGE_SIZE, offset=page_addr)
409 410
                    struct.pack_into(self.ENDIAN+frmt_bytes[byte_mode],mm, page_offs, data)
    
411
    '''
412
    Read/write slave AXI using byte addresses relative to the AXI memory region
413 414
    '''
    def axi_write_single(self,addr,data):
415 416 417 418 419
        """
        Write 32-bit word to the slave AXI address range
        <addr> - physical byte address relative to the slave AXI memory region
        <data> - 32-bit data to write
        """
420
        self.write_mem(self.MAXI_BASE+addr,data)
421 422

    def axi_read_addr(self,addr):
423 424 425 426
        """
        Read 32-bit word from the  slave AXI address range
        <addr> - physical byte address relative to slave AXI AXI memory region
        """
427
        return self.read_mem(self.MAXI_BASE+addr)
428 429 430
    '''
    Read/write slave AXI using 32-bit word addresses (same as in Verilog code)
    '''
431
    def axi_write_single_w(self,addr,data,verbose=0):
432 433 434 435
        """
        Write 32-bit word to the slave AXI address range, using 32-word address
        <addr> - 32-bit word (register) address relative to the slave AXI memory region
        <data> - 32-bit data to write
436
        <verbose> print data being written (default: 0)
437
        """
438
        if verbose or self.DEBUG_MODE:
439
            print("axi_write_single_w(0x%x,0x%08x)"%(addr,data))
440 441 442
        self.axi_write_single(addr<<2,data)

    def axi_read_addr_w(self,addr):
443 444 445 446
        """
        Read 32-bit word from the slave AXI address range, using 32-word address
        <addr> - 32-bit word (register) address relative to the slave AXI memory region
        """
447
        return self.axi_read_addr(addr<<2)