2025年12月6日星期六

AXI4 with pulp-platform axi

During use the pulp-axi component with AXI4 peripheral, the  parameter ATOP should be set to 0. 

Assign the atop signal of AXI4 master, slave to 0 especially in axi_width_converter, otherwise it will not work properly. 

Anyway, axi_atop_filter could also be used to filter the ATOP signal.

run linux/freebsd on qemu

Get the qemu, compiler tool-chain and below software package
  • qemu-system-riscv64
  • riscv64-linux-gnu-
  • busybox
  • linux
  • opensbi (optional)
  • u-boot (optional)

 

Reference:

https://risc-v-machines.readthedocs.io/en/latest/linux/simple/#pull

https://www.qemu.org/docs/master/system/riscv/virt.html

https://gitlab.inf.ethz.ch/project-openenzian/applications/risc-v/riscv-gnu-toolchain

 

Build the Linux 

export CROSS_COMPILE=riscv64-linux-gnu- 

make ARCH=riscv defconfig 

make ARCH=riscv -j 8 

the image will be generated at arch/riscv/boot/Image

 

Build the Busybox 

export CROSS_COMPILE=riscv64-linux-gnu-

make ARCH=riscv menuconfig

make it as static library

make ARCH=riscv

After fix the compile error (set CONFIG_SHA1_HWACCEL=0), busybox will be generated 


Build the initramfs

mkdir initramfs

cd initramfs

mkdir -p {bin,sbin,dev,etc,home,mnt,proc,sys,usr,tmp}

mkdir -p usr/{bin,sbin}

mkdir -p proc/sys/kernel

cd dev sudo mknod sda b 8 0

sudo mknod console c 5 1

cd ..

cp ../busybox/busybox ./bin/

 

vi init  #Change the init file as: 

#!/bin/busybox sh

# Make symlinks 

/bin/busybox --install -s

# Mount system

mount -t devtmpfs devtmpfs /dev

mount -t proc proc /proc

mount -t sysfs sysfs /sys

mount -t tmpfs tmpfs /tmp

# Busybox TTY fix

setsid cttyhack sh

# https://git.busybox.net/busybox/tree/docs/mdev.txt?h=1_32_stable

echo /sbin/mdev > /proc/sys/kernel/hotplug

mdev -s

sh

 

Quit the vi, add the +x permission 

chmod +x init

Pack as cpio.gz format 

find . -print0 | cpio --null -ov --format=newc | gzip -9 > initramfs.cpio.gz

 

Boot the Linux kernel

qemu-system-riscv64 -machine virt  -m 2G  -nographic  -kernel linux/arch/riscv/boot/Image -initrd initramfs/initramfs.cpio.gz


Compile u-boot

riscv64_smode_defconfig 


Boot the FreeBSD

Download the FreeBSD, choose zfs.raw.xz format

Uncompress the file by using xz command and convert to qcow2 format 

qemu-system-riscv64 -machine virt -m 2G -nographic -kernel u-boot.bin -drive file=freebsd-zfs.qcow2,format=qcow2,id=hd0 -device virtio-blk-device, drive=hd0 -netdev user,id=net0 -device virtio-net-device,netdev=net0

2024年12月14日星期六

mesi protocol

For any given pair of caches, the permitted states of a given cache line are as follows:

M E S I
M X X X O
E X X X O
S X X O O
I O O O O
Curstate Operation NextState SOther Core
INVALID Read case EXCLUSIVE if other core is INVALID INVALID (No operation)

case SHARED if other core contains data SHARED (no operation)
MODIFIED -> Flush -> SHARED
EXCLUSIVE -> SHARED
INVALID Write MODIFIED INVALID (no operation)
SHARED -> INVALID
MODIFIED -> Flush -> INVALID
EXCLUSIVE -> INVALID
EXCLUSIVE Read EXCLUSIVE INVALID (No operation)
EXCLUSIVE Write MODIFIED INVALID (No operation)
SHARED Read SHARED INVALID (no operation)
SHARED (no operation)
SHARED Write MODIFIED INVALID (no operation)
SHARED -> INVALID
MODIFIED Read MODIFIED INVALID (No operation)
MODIFIED Write MODIFIED INVALID (No operation)

Reference: https://github.com/Yefei100/Cache_coherence_protocol/blob/master/main.cc

2023年10月22日星期日

run riscv on qemu-system-riscv32

Sightly modify riscv.ld (download riscv.ld):

  1. Ensure the rom starts from 0x80000000. (matched with virt machine type)
  2. Set _init as entry function, place .text.init at 0x80000000.
  3. Add stack pointer initial location
In start.S, add _init function to setup sp and gp register:

.extern _start
.section .text.init
        .globl _init
_init:
        lui gp, %hi(ROM_START)     #_rom_start = 0x80000000 in linker script
        addi gp, gp, %lo(ROM_START)
        lui sp, %hi(init_sp)
        addi  sp, sp, %lo(init_sp)
        j  _start

riscv-none-elf-gcc -o helloworld.elf -march=rv32imad start.S helloworld.c -T riscv.ld

riscv-none-elf-objdump -D helloworld.elf > helloworld.S

qemu-system-riscv32 --machine virt -bios helloworld.elf -m 128M -nographic -singlestep -d exec,int,cpu 2>&1 | tee ins.log

Add cpu option above can dump the register value per step.

printf(...) require override _write() which could be found in newlib/libgross library.



2023年10月15日星期日

Increase swap size in WSL

In windows command prompt,

cd ~

notepad .wslconfig

[wsl2]
memory=16GB
swap=64GB
swapFile=D:\\swap.vhdx

Then, type

wsl --shutdown

to shutdown the Linux and wait for at least 8 seconds.

Remove Windows paths in WSL

In WSL,

sudo vi /etc/wsl.conf

[interop]
appendWindowsPath = false

In windows command prompt,

wsl --shutdown to restart the Linux

echo $PATH

to verify the path is correct


2021年12月30日星期四

aircrack-ng and hashcat

Mac changer:

sudo macchanger --mac=12:34:56:78:9a:bc wlan0   

 

Start monitor mode:

sudo airmon-ng start wlan0

 

Get bssid:

sudo airodump-ng wlan0mon

 

Dump handshake packet (channel = 7, bssid=aa:bb:cc:dd:ee):

sudo airodump-ng -c 7 --bssid aa:bb:cc:dd:ee:ff -w test wlan0mon

 

Deauth target:

sudo aireplay-ng -0 10 -a aa:bb:cc:dd:ee:ff -c 11:22:33:44:55:66 wlan0mon

 

Aircrack by dictionary:

sudo aircrack -w ~/pw/pw_list.txt ~/test.cap


Convert to hc22000 format

https://hashcat.net/cap2hashcat/


Hashcat by dictionary:

hashcat -m 22000 test.hc22000 ~/pw/pw_list.txt


Hashcat by brute force:

For example, 8 lowercase character,

increment rule:-i --increment-min 8 --increment-max 12

hashcat -a3 -m 22000 -i test.hc22000  ?l?l?l?l?l?l?l?l

 

Hashcat by custom pattern mixed with dictionary:

hashcat -m 22000 -i -a 6 test.hc22000 ~/pw/pw_list.txt ?d?d?d?d

2021年4月13日星期二

Generate function call-graph by valgrind

sudo apt install kcachegrind valgrind 


Build compiler flags:

CFLAGS / CPPFLAGS: -g (or -ggdb3 -O0)


# Generate a callgrind.out.<PID> file.
valgrind --tool=callgrind ./main


 # Generate the callgrind.out.<PID> files per thread.
valgrind --tool=callgrind --separate-threads=yes  ./main


# Open a GUI tool to visualize call graph
kcachegrind callgrind.out.<PID>


2021年4月12日星期一

Use lcov to view the coverage

Assume main.c and x.c are the source files.

1) Add CFLAGS / CPPFLAG -fprofile-arcs -ftest-coverage when build the project, .gcno is generated

2) Execute the program    #.gcda are generarted

3) gcov main.c    #main.c.gcov is generated (Optional)

4) gcov x.c    #x.c.gcov is generated (Optional)

5) Gen html report

lcov -c --directory . --output-file main_coverage.info
genhtml main_coverage.info --output-directory out


2021年3月19日星期五

Vitis HLS FIFO interface

Xilinx Example - proj_filter_scalar:

void filter(data_t &x, coef_t coef[TAP], sum_t &y)
{
#pragma HLS INTERFACE ap_fifo port=x
#pragma HLS INTERFACE ap_fifo port=y
#pragma HLS INTERFACE ap_fifo port=coef
#pragma HLS PIPELINE II=4

//.....

}


After csynth,

Latency (cycles) = 6

Top function Arguments

x in ap_int<165>&

coef in ap_int<16>*

y out ap_int<34>&

read_from_fifo:  x_read and x_dout change at the same clock edge

write_to_fifo: y_in delay 1 clock cycle after y_write 

ready_state:  ap_ready delay 1 cycle after ap_done



Xilinx Vitis HLS Tcl script

Run Tcl script by Vitis HLS

vitis_hls -f (example).tcl


run_hls.tcl

# Create a project
open_project -reset proj_filter_scalar

# Add design files
add_files filter_scalar.cpp
# Add test bench & files
add_files -tb filter_scalar_test.cpp
add_files -tb result.golden.dat

# Set the top-level function
set_top filter

# ########################################################
# Create a solution
open_solution -reset solution1
# Define technology and clock rate
set_part  {xcvu9p-flga2104-2-i}
create_clock -period 3

# Source x_hls.tcl to determine which steps to execute
source x_hls.tcl
csim_design

if {$hls_exec == 1} {
    # Run Synthesis and Exit
    csynth_design
    
} elseif {$hls_exec == 2} {
    # Run Synthesis, RTL Simulation and Exit
    csynth_design
    
    cosim_design
} elseif {$hls_exec == 3} {
    # Run Synthesis, RTL Simulation, RTL implementation and Exit
    csynth_design
    cosim_design
    export_design -rtl verilog -flow impl
} else {
    # Default is to exit after setup
    csynth_design
}

exit


x_hls.tcl

#
# Copyright 2020 Xilinx, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Set to 0: to run setup
# Set to 1: to run setup and synthesis
# Set to 2: to run setup, synthesis and RTL simulation
# Set to 3: to run setup, synthesis, RTL simulation and RTL synthesis
# Any other value will run setup only
 
set hls_exec 1

2021年3月17日星期三

Zynq: Build Your Own Petalinux

Prerequisite

sudo apt install gcc git make net-tools libncurses5-dev tftpd zlib1g-dev libssl-dev flex bison libselinux1 gnupg wget diffstat chrpath socat xterm autoconf libtool tar unzip texinfo zlib1g-dev gcc-multilib build-essential libsdl1.2-dev libglib2.0-dev zlib1g:i386 screen pax gzip gawk
 

Install FTP server

sudo apt install tftpd-hpa
service tftpd-hpa restart
Service tftpd-hpa status


Download and Install Petalinux (v2020.2)

Download petalinux installer from official Xilinx web site

chmod +x (installer)

mkdir -p ~/petalinux/2020.2

(installer) -d ~/petalinux/2020.2


Change to Use Bash Shell Script

chsh -s /bin/bash

# Logout and log back in after to observe the sh is changed
 

Environment Check and Setup

source ~/petalinux/2020.2/setting.sh

# Ensure working environment has been set

echo $PETALINUX


Minimum Hardware Requirement

One TTC (Triple Timer Counter)

External Memory Controller with at least 32MB of memory

UART

QSPI / SD Card


System user dts location (connect with additional peripheral?)

my-petalinux/project-spec/meta-user/recipes-bsp/device-tree/files/system-user.dtsi


Create and Build the Project

cd ~

petalinux-create --type project --template zynq --name my-petalinux

cd my-petalinux

# Config from xsa

petalinux-config --get-hw-description=(path-containing-xsa)

# Build the package

petalinux-build

# Generate Boot Image

petalinux-package --boot --fsbl images/linux/zynq_fsbl.elf --fpga images/linux/system_wrapper.bit --u-boot

 

Prepare the SD Card

Use fdisk to assign

  • 1st partition as W95 FAT32 (Partition Code: b) primary partition, 2048-50000 = ~24MB
  • 2nd partition as EXT4, primary partition

sudo fdisk /dev/sd(?)

n = new partition

d = delete partition

t = change partition type (Code)

w = apply changes

a = active partition


mkfs.vfat -F32 vfat /dev/sd(?)1

mkfs.ext4 /dev/sd(?)2


Test U-Boot and Linux Kernel

Copy BOOT.BIN, image.ub and boot.scr into SD card FAT32 partition

Copy rootfs.cpio into EXT4 partition

Make sure the SD jumper is selected

Press reset button, output message will be shown on serial console

U-Boot 2020.01 (Mar 17 2021 - 16:35:57 +0000)                                   
                                                                                
CPU:   Zynq 7z010                                                               
Silicon: v3.1                                                                   
DRAM:  ECC disabled 512 MiB                                                     
Flash: 0 Bytes                                                                  
NAND:  0 MiB                                                                    
MMC:   mmc@e0100000: 0
=====================
Found U-Boot script /boot.scr                                                   
2010 bytes read in 12 ms (163.1 KiB/s)
===================== 
Starting kernel ...                                                             
                                                                                
Booting Linux on physical CPU 0x0                                               
Linux version 5.4.0-xilinx-v2020.2 (oe-user@oe-host) (gcc version 9.2.0 (GCC)) 1
CPU: ARMv7 Processor [413fc090] revision 0 (ARMv7), cr=18c5387d                 
CPU: PIPT / VIPT nonaliasing data cache, VIPT aliasing instruction cache        
OF: fdt: Machine model: xlnx,zynq-7000                                          
earlycon: cdns0 at MMIO 0xe0000000 (options '115200n8')                         
printk: bootconsole [cdns0] enabled                                             
Memory policy: Data cache writealloc                                            
cma: Reserved 16 MiB at 0x1f000000 


Remarks:

BOOT.BIN:

  • fsbl.elf (First stage bootloader)
  • u-boot.elf (Second stage bootloader)
  • design.bit (FPGA bitstream)

image.ub

  • system.dtb
  • uImage
  • rootfs

 



2021年3月15日星期一

Zynq Program the SPI Flash

Prerequisite

1) In Vivado, enable the UART component in "Zynq7 Processing System" to output the UART message

2) Ensure the DDR memory interface is setup correctly

3) Ensure the "Processor System Reset" Component is also included in the block design

4) Verify the wire connection in the block design


Export Hardware and Bitstream

1) In Vivado 2020, Select File > Export > Export Hardware...

2) Select 'Include bitstream'

3) Select 'Tools' > 'Launch Vitis IDE'

4) It will generates XSA file and bitstream file


Create Application Project FSBL (Optional)

1) In Vitis, Select 'File' > 'New' >'Application Project'

2) Select the XSA file

3) Named 'fsbl', select as standalone project, and choose FSBL

project example


Create Application Project Hello World

1) In Vitis, Select 'File' > 'New' > 'Application Project'

2) Select the XSA file

3) Named 'hello_world', select as standalone project, and choose Hello World project example


Build and Run the Hello World Project Example

1) Run the hello world project to ensure the UART message is shown correctly


Create Boot Image

1) Select 'Xilinx' > 'Create Boot Image'

2) Specify a destination folder in order to export the merged boot image file (.bin)

3) Select (Bootloader) and the fsbl file (.elf). The default fsbl is located at (application_project)/(project_name)/zynq_fsbl/fsbl.elf

4) Select (datafile) and the bit stream file (.bit) which is located at (xsa_dir)/.runs/impl_1/

5) Select (datafile) and the generated hello_world file (.elf)

Both in sequential order (FSBL -> bit stream -> hello_world)

6) Select 'Create Image'


Program Flash

1) Make sure all debugger breakpoints are removed because Vitis will switch to debug perspective to program the Flash

2) Select 'Xilinx' > 'Program Flash'

3) Select the boot image file (.bin)

4) Ensure the flash type is selected correctly (my evaluation board: qspi-x4-single)

5) Ensure the JTAG mode (jumper) is selected on board

6) Check 'Verify after flash' if necessary

7) Select 'Program'


Verify the program is running correctly

1) Ensure the SPI Flash jumper is selected

2) Press the reset button / Perform cold reset

3) The UART message should be shown in the serial console terminal




Microphase Z7-Lite (Zynq 7010) Configuration

FPGA: Xilinx XCZ7010 CLG400ABX1833

Spec: Dual-Core ARM Cortex-A9 MPCore Up to 866MHz

 

Series PL Equivalent: Artix-7

Logic Cells: 28K

LUTs: 17,600

Flip-Flops: 35200

Total Block RAM (# 36Kb Blocks): 2.1Mb (60)

DSP Slices: 80


1. PS sub-system

Crystal: 33.3333MHz

Reset: Low Active


DDR Interface

Memory: MT41K256M16

Data bus: 16bit

Row Address: 32K (A[14..0])

Bank Address: 8 (BA[2..0]) BA0:L5, BA1: R4, BA2: J5


SPI Flash: WinBond W25Q128JVSIQ 128M-bit  QUAD SP

Maximum Freq: 133MHz

QSPI_CS pin: A7 (MIO1)  CS

QSPI_DQ0 pin: B8 (MIO2) DI(IO0)

QSPI_DQ1 pin:D6 (MIO3) DO(IO1)

QSPI_DQ2 pin:B7 (MIO4) /WP (IO2)

QSPI_DQ3 pin: A6 (MIO5) /HOLD (IO3)

QSPI_CLK pin: A5 (MIO6) CLK


Micro-SD Interface:

No Card Detect, No Write Protect

SD_CLK pin: D14 (MIO40)

SD_CMD pin: C17 (MIO41)

SD_DATA0 pin: E12 (MIO42)

SD_DATA1 pin: A9 (MIO43)

SD_DATA2 pin: F13 (MIO44)

SD_DATA3 pin: B15 (MIO45)

 

UART_RX pin: C5(MIO14) - USB2UART CH340E

UART_TX pin: C8 (MIO15) - USB2UART CH340E

 

PS_KEY1 pin: B5 (MIO8) 

PS_LED1 pin: E6 (MIO0)


Extra peripheral:

USB OTG (USB3320C)


2. PL sub-system:

Crystal: 50MHz

PL_KEY1 pin: P16 (L24N)

PL_KEY2 pin: T12 (L2P)

PL_LED1 pin:  P15 (L24P)

PL_LED2 pin: U12 (L2N)


Extra peripheral:

HDMI, ETH

2021年3月14日星期日

Install driver in Xilinx Vivado

sudo /tools/Xilinx/Vivado/2020.2/data/xicom/cable_drivers/lin64/install_script/install_drivers

login again to apply the setting



2021年3月10日星期三

HLS Important Notes

Vivado CLI execute Tcl script

vivado_hls -f script.tcl


Vivado CLI interactive mode

vivado_hls -i [-l <logfile>]


if not specific the clock uncertainty, default value is 12.5% 


Tcl script example

## Tcl script example from Xilinx Introduction to High-Level Snthesis

open_project my.prj

set_top dct

add_files dct.cpp

add_files -tb dct_test.cpp

add_files -tb in.dat

add_files -tb out.golden.dat

open_solution "solution1"

set_part {xc7k160tfbg848-1}

create_clock -period 10


source "./my.prj/solution1/directives.tcl"

csynth_design

 

Unsupported C Language Constructs

system call (e.g. printf, system, time...etc)

dynamic memory & functions (.e.g. malloc, new)

virtual function

pointer casting

recursive function

Most of STL library which contains recursive and dynamic allocation


Important Notes

Use APCC to compile the intN data type, gcc doesn't support this data type

Must be care if use access pointer with the same function multiple time

 

 

 



2021年3月8日星期一

High Level Synthesis by using Xilinx Vitis

// Analyze the Xilinx Vitis example
 
// C General include header file
#include <ap_cint.h>

// C typedefs for top-level input and output int / fixed-point formats
// [u]int<precision> (1024 bits) 
typedef int7 in_data_t;
typedef uint7 in_data_t;

// C++ General include header file
// ap_[u]int<W> (1024 bits)
// ap_[u]fixed<W,I,Q,O,N> 
#include <ap_int.h>
#include <ap_fixed.h>
#include <hls_stream.h>

// C++ typedefs for top-level input and output int / fixed-point formats
typedef ap_ufixed<IN_BW,IN_IW> in_data_t;
typedef ap_ufixed<OUT_BW,OUT_IW> out_data_t;
typedef ap_uint<IN_BW> data_t;

typedef ap_int<18> dout1_t;
typedef ap_uint<13> dout2_t;

typedef ap_ufixed<10,8, AP_RND, AP_SAT> din1_t;
typedef ap_fixed<36,30> dout_t;

hls::stream<uint8_t> &bytes_in,

// Support array
typedef ap_int<7> din_t;
typedef ap_int<10> dout_t;
dout_t mem_bottleneck_resolved(din_t mem[N]) {
}

2021年3月3日星期三

vscode with cscope

vscode plugin required: scope4code


Build database

Press F1, enter Cscope: Build database to start building


Hotkey

  • Ctrl Alt -    go back
  • Ctrl Shift +    go forward

 

Solve "Visual Studio Code is unable to watch for file changes in this large workspace" (error ENOSPC)# 

Before adjusting platform limits, make sure that potentially large folders, such as Python .venv, are added to the files.watcherExclude setting.

The limit can be increased to its maximum by editing /etc/sysctl.conf (except on Arch Linux, read below) and adding this line to the end of the file:

fs.inotify.max_user_watches=524288

The new value can then be loaded in by running sudo sysctl -p.

Quoted from"https://code.visualstudio.com/docs/setup/linux#_visual-studio-code-is-unable-to-watch-for-file-changes-in-this-large-workspace-error-enospc"

2021年3月2日星期二

Test devmem in rpi2 by shell script

#!/bin/bash

#Test devmem (Toggle RED LED) in rpi2 by shell script

GPIO_BASE=$((0x3F200000))
LED_GPFSEL=4
LED_GPFBIT=21
LED_GPSET=8
LED_GPCLR=11
LED_GPIO_BIT=3

#addr=$(($GPIO_BASE + $LED_GPFSEL * 4))
#rvalue=$(devmem $(($addr)) 32)

addr=$(($GPIO_BASE + $LED_GPCLR * 4))
devmem $((addr)) 32 $((1 << $LED_GPIO_BIT))

sleep 5

addr=$(($GPIO_BASE + $LED_GPSET * 4))
devmem $((addr)) 32 $((1 << $LED_GPIO_BIT))

2021年3月1日星期一

List Device Tree in Linux (embedded system)

The device tree is located at

cd /proc/device-tree/

lrwxrwxrwx   device-tree -> /sys/firmware/devicetree/base


Install tree package to view the device tree hierarchy


further investigate the content

plain text file: cat (file)

hex file: hexdump -C (file)