shorne in japan

blog about contact

Debugging GDB in GDB

19 May 2017

For the last year or so I have been working on getting a gdb port upstreamed for OpenRISC. One thing one sometimes has to do when working on gdb is to debug it. Debugging gdb with gdb could be a bit confusing; hopefully these tips will help.

Setting the Prompt

Setting the prompt of the parent gdb will help so you know which gdb you are in by looking at the command line. I do that with set prompt (master:gdb) , (having space after the (master:gdb) is recommended).

Handling SIGINT

Handling ctrl-c is another thing we need to consider. If you are in your inferior gdb and you press ctrl-c which gdb will you stop? The parent gdb or the inferior gdb?

The parent gdb will be stopped. If we then continue the inferior will continue. If we want to have the inferior stop as well we can set handle SIGINT pass.

All together

An example session may look like the following

$ gdb or1k-elf-gdb

(gdb) set prompt (master:gdb)

(master:gdb) handle SIGINT
SIGINT is used by the debugger.
Are you sure you want to change it? (y or n) y
Signal        Stop      Print   Pass to program Description
SIGINT        Yes       Yes     No              Interrupt

(master:gdb) handle SIGINT pass
SIGINT is used by the debugger.
Are you sure you want to change it? (y or n) y
Signal        Stop      Print   Pass to program Description
SIGINT        Yes       Yes     Yes             Interrupt

(master:gdb) run
Starting program: /usr/local/or1k/bin/or1k-elf-gdb
(gdb) file loop.nelib
Reading symbols from loop.nelib...done.

(gdb) target sim
Connected to the simulator.

(gdb) load
Loading section .vectors, size 0x2000 lma 0x0
Loading section .init, size 0x28 lma 0x2000
Loading section .text, size 0x4f88 lma 0x2028
Loading section .fini, size 0x1c lma 0x6fb0
Loading section .rodata, size 0x18 lma 0x6fcc
Loading section .eh_frame, size 0x4 lma 0x8fe4
Loading section .ctors, size 0x8 lma 0x8fe8
Loading section .dtors, size 0x8 lma 0x8ff0
Loading section .jcr, size 0x4 lma 0x8ff8
Loading section .data, size 0xc74 lma 0x8ffc
Start address 0x100
Transfer rate: 254848 bits in <1 sec.

(gdb) run
Starting program: /home/shorne/work/openrisc/loop.nelib
loop
^C
Program received signal SIGINT, Interrupt.
or1k32bf_engine_run_fast (current_cpu=0x7fffee59c010) at mloop.c:577
577       if (! CPU_IDESC_SEM_INIT_P (current_cpu))
Missing separate debuginfos, use: dnf debuginfo-install expat-2.2.0-1.fc25.x86_64 libgcc-6.3.1-1.fc25.x86_64 libstdc++-6.3.1-1.fc25.x86_64 ncurses-libs-6.0-6.20160709.fc25.x86_64 python-libs-2.7.13-1.fc25.x86_64 xz-libs-5.2.2-2.fc24.x86_64 zlib-1.2.8-10.fc24.x86_64

(master:gdb) bt
#0  or1k32bf_engine_run_fast (current_cpu=0x7fffee59c010) at mloop.c:577
#1  0x0000000000654395 in engine_run_1 (fast_p=1, max_insns=<optimized out>, sd=0xd68a60) at ../../../binutils-gdb/sim/or1k/../common/cgen-run.c:191
#2  sim_resume (sd=0xd68a60, step=0, siggnal=<optimized out>) at ../../../binutils-gdb/sim/or1k/../common/cgen-run.c:108
#3  0x00000000004392d1 in gdbsim_wait (ops=<optimized out>, ptid=..., status=0x7fffffffc910, options=<optimized out>) at ../../binutils-gdb/gdb/remote-sim.c:1015
#4  0x0000000000600c6d in delegate_wait (self=<optimized out>, arg1=..., arg2=<optimized out>, arg3=<optimized out>) at ../../binutils-gdb/gdb/target-delegates.c:138
#5  0x000000000060ff64 in target_wait (ptid=..., status=status@entry=0x7fffffffc910, options=options@entry=0) at ../../binutils-gdb/gdb/target.c:2292
#6  0x000000000057e9d9 in do_target_wait (ptid=..., status=status@entry=0x7fffffffc910, options=0) at ../../binutils-gdb/gdb/infrun.c:3618
#7  0x0000000000589658 in fetch_inferior_event (client_data=<optimized out>) at ../../binutils-gdb/gdb/infrun.c:3910
#8  0x0000000000548b1c in check_async_event_handlers () at ../../binutils-gdb/gdb/event-loop.c:1064
#9  gdb_do_one_event () at ../../binutils-gdb/gdb/event-loop.c:326
#10 0x0000000000548c05 in gdb_do_one_event () at ../../binutils-gdb/gdb/common/common-exceptions.h:221
#11 start_event_loop () at ../../binutils-gdb/gdb/event-loop.c:371
#12 0x000000000059be78 in captured_command_loop (data=data@entry=0x0) at ../../binutils-gdb/gdb/main.c:325
#13 0x000000000054ab73 in catch_errors (func=func@entry=0x59be50 <captured_command_loop(void*)>, func_args=func_args@entry=0x0, errstring=errstring@entry=0x711a00 "", mask=mask@entry=RETURN_MASK_ALL)
    at ../../binutils-gdb/gdb/exceptions.c:236
#14 0x000000000059cda6 in captured_main (data=0x7fffffffca60) at ../../binutils-gdb/gdb/main.c:1150
#15 gdb_main (args=args@entry=0x7fffffffcb90) at ../../binutils-gdb/gdb/main.c:1160
#16 0x000000000040c265 in main (argc=<optimized out>, argv=<optimized out>) at ../../binutils-gdb/gdb/gdb.c:32

(master:gdb) c
Continuing.

Program received signal SIGINT, Interrupt.
main () at loop.c:22
22          while (1) { ; }

(gdb) bt
#0  main () at loop.c:22

(gdb) l
17        tdata.str = "loop";
18        foo(tdata);
19
20        while (1) {
21          printf("%s\n", tdata.str);
22          while (1) { ; }
23        }
24        return 0;
25      }

(gdb) q
A debugging session is active.

        Inferior 1 [process 42000] will be killed.

Quit anyway? (y or n) y
[Inferior 1 (process 24876) exited normally]
(master:gdb) q

Other Options

You could also remote debug gdb from a different terminal by using attach to attach to and debug the secondary. But I find having everything in one terminal nice.

Further References


Simulating KiCad Schematics in Spice

28 Apr 2015

KiCad is a great tool for taking your electronics design from schematic to PCB, but circuit simulation is secondary feature.

As we will see here KiCad does contain the ability to generate netlists which can be used with simulators like ngspice to perform circuit verification and analysis.

To get started we will need to decide on a design. I will choose a circuit which will show us how to do following:

  • Use vendor spice components
  • Perform Transient Analysis
  • Simulate an input signal
  • Measure frequency responce

Layout Circuit and Generate Netlist

For this demo let us pick a simple inverting op amp circuit. We can use the spice models from vendors like Texas Instruments and Linear Technology to provide the op amp. This also means we can easily, virtually, swap out components to see how they perform in our design.

Below we can see the completed schematic for a non-inverting op amp with a dual power supply. The 50K ohm feedback and 2K ohm input resistors mean our signal will be amplified 25 times. For more details on drawing schematics in kicad refer to the getting started tutorials.

kicad amp for demo

Image 1: The completed inverting op amp schematic

Once our circuit is complete we can generate a spice netlist by navigating to Tools > Generate Netlist.

Generating a netlist in kicad

Image 2: Generating the spice netlist

Some comments on the Netlist options:

  • The Default format option does not seem to do anything
  • I have selected Prefix references ‘U’ and ‘IC’ with ‘X’, this is needed for ngspice as it recognizes ‘X’ components as subcircuits. However for the Jack and Power interfaces annotated with J* and P* it would be nice to prefix with X as we will implement these with subcircuits as well.

Once the options are selected click Netlist to save your netlist. This will generate a netlist like the following:

* EESchema Netlist Version 1.1 (Spice format) creation date: Sat 25 Apr 2015 07:04:41 AM JST

* To exclude a component from the Spice Netlist add [Spice_Netlist_Enabled] user FIELD set to: N
* To reorder the component spice node sequence add [Spice_Node_Sequence] user FIELD and define sequence: 2,1,0

*Sheet Name:/
XU1  7 6 0 4 1 OPAMP            
J1  2 0 0 JACK_IN              
J2  7 3 0 JACK_OUT             
R2  6 7 50K             
R1  2 6 2K              
R3  0 3 2K              
P1  4 0 1 PWR_IN               

.end

Setup Inputs and Outputs for Simulation

In order to simulate the circuit we need to plug in our virtual power supplies, signal generators and oscilloscope probes. To do this I have chosen to use subcircuits to contain each or these test components.

Create a components.cir like the following:

* Components and subcircuits for use in spicedemo.cir

.INCLUDE LMV981.MOD

* 4 0 1 PWR_IN
*              + g -     
.subckt PWR_IN 1 2 3
  Vneg 1 2  3.3V
  Vpos 2 3 3.3V
.ends PWR_IN

* 7 6 0 4 1 OPAMP
*             o - + p n
.subckt OPAMP 1 2 3 4 5
  * PINOUT ORDER  1   3   6  2  4   5
  * PINOUT ORDER +IN -IN +V -V OUT NSD
  Xopamp 3 2 4 5 1 NSD LMV981
.ends OPAMP

*               s x g
.subckt JACK_IN 1 2 3
  *** Simulate mic input A-note
  Vmic  3 1 ac SIN(0 0.02 440)
.ends JACK_IN

*                s x g
.subckt JACK_OUT 1 2 3
  Rwire  1 2   10ohm
.ends JACK_OUT

PWR_IN : Connecting Power

This first subcircuit is the PWR_IN connector in our kicad circuit. This is a 3pin connector with a positive rail, negative rail and ground. Here we use two DC power supplies to generate the positive and negative rails. Be sure to double check pin numbers with your generated netlist.

OPAMP : The IC

Next we have the OPAMP subcircuit. For this we just provide a wrapper for the component included with .INCLUDE LMV981.MOD. This spice model from Texas Instruments and was selected as it provides a 6 pin low power solution. Many vendors provide models like this which can be used.

TI Spice Model Download

Image 3: Here we can see how to download spice models from Texas Instruments

JACK_IN : Simulating Microphone Input

The JACK_IN and JACK_OUT interfaces are typical mono audo jack interface with 3 pins (called jack 2-pole). The 3 pins are ‘signal’ (tip), ‘ground’ (sleeve) and ‘normally closed (NC)’. When the jack has nothing plugged into it the ‘signal’ and ‘normally closed’ pins will be shorted. When the jack has something plugged in (like a microphone) then the ‘signal’ and ‘ground’ pins will be connected to the microphone and ‘normally closed’ is disconnected. The reason for this is to protect from having floating inputs or outputs or use for jack plug-in detection.

Note: For details on jacks read the wiki and manufacturer documents from Schurter, Adam Tech and Farnell

For JACK_IN we simulate a microphone plugged in by providing a 440hz (a-note) sine wave of 20mV, a typical microphone signal.

JACK_OUT : Simulating a Load

For JACK_OUT we use the dummy load resistor R3 to provide some load to the op amp output. To wire together ‘signal’ and ‘unplugged’ pins we just add a dummy 10ohm resistor. It could have been 0 or 1 ohm, but I just set it to 10.

Update the Generated Netlist

Next, we need to go back and modify the generated netlist slightly to include the components.cir and perform the analysis we wish to do. Also, because we are using subcircuits we add X’s to the J and P components.

Note: Instead of manually adding .include and analysis lines we could add -PSPICE and +PSPICE text blocks anywhere to our kicad schematic and it will include the text before and after the netlist respectively.

.include components.cir

*Sheet Name:/
XU1  7 6 0 4 1 OPAMP
XJ1  2 0 0 JACK_IN
XJ2  7 3 0 JACK_OUT
R2  6 7 50K
R1  2 6 2K
R3  0 3 2K
XP1  4 0 1 PWR_IN

.op

.tran 0.1m 3m
.plot tran V(7) V(2)

.ac dec 10 1 100K
.plot ac V(7)

.end 

Simulation

Running OP Analysis

First its always good to run the dc operating, OP, analsysis to make sure nothing is shorted.

Because we have included the op amp spice model the full analsysis results in more than a thousand lines for dc analysis. The main things to look at our our voltages and currents.

We can check the important voldages with grep as below. Here we can see relatively low voltages other than our supplies which looks normal.

$ ngspice -b spicedemo.cir | grep V\(

        V(3)                             -2.85334e-02
        V(2)                             0.000000e+00
        V(7)                             -2.86760e-02
        V(6)                             -1.13177e-03
        V(1)                             -3.30000e+00
        V(4)                             3.300000e+00

To view the currents we can run a similar grep and see similar low values (less than 1 milliamp). Its good to look at the entire output to understand how these greps work.

$ ngspice -b spicedemo.cir | grep v\\.x

        v.xj1.vmic#branch                5.658851e-07
        v.xp1.vneg#branch                -1.37178e-04
        v.xp1.vpos#branch                -1.51996e-04

Running TRAN Analysis.

Next we can run the TRAN analsysis (oscilloscope mode), to make sure it works. Here we can see that the input signal is amplified from 20mV to 500mV resulting in our expected 25 times gain. The result is also inverted as we are using an inverting amp configuration.

# In interactive mode
$ ngspice spicedemo.cir

> tran 0.3m 1m
> plot V(2) V(7)

TRAN analysis results

Image 4: Transient analysis, shows the input signal in blue and output in red

Running AC Analysis

Finally running AC analysis we can measure the frequency responce (bandwidth) of the circuit. Below we can see that after about 10,000 Hz the gain starts to drop off.

# In interactive mode
$ ngspice spicedemo.cir

> ac dec 10 1 100K
No. of Data Rows : 51
> plot V(2) V(7)

Ac analysis results

Image 5: Shows performance drop off after 10K hz

Further Reading


Spice Essentials

21 Apr 2015

Did you ever get stuck figuring out how to run spice? These essential spice tips will get you on your way.

Recently I have been searching for good linux tools to simulate circuits. Spice is widely known in circuit simulation. This short guide should help you get started; including how to perform graphical plotting with nutmeg. All the below demos are using ngspice and ngnutmeg. In this post I assume you know the basics of writing or generating spice netlists.

We will cover the basics of:

  • Analysis with OP and TRAN
  • Controlling spice output
  • Running ngspice and ngnutmeg

Analysis

When analyzing a circuit we need to use spice analysis commands. These are usually placed at the end of your netlist.

Using OP

The first and most simple analysis command you should know is the OP command. It provides the dc operating point voltage dump of all nodes with capacitors fully charged (no current) and inductors fully inducting (shorted).

Usage

.op

Example

Download op.cir

* OP analysis of Voltage divider 
V1 2 0 DC 10V
R1  2 1 50K             
R2  1 0 20K             
.op
.end

When running we can see that the voltage and current of each node is displayed.

$ ngspice -b op.cir

No. of Data Rows : 1
        Node                                  Voltage
        ----                                  -------
        ----    -------
        V(1)                             2.857143e+00
        V(2)                             1.000000e+01

        Source  Current
        ------  -------

        v1#branch                        -1.42857e-04

Using TRAN

The next analysis command to know is the TRAN command.

TRAN will run the circuit for a fixed time and take interval measurements. The below .tran 0.1m 5m will measure for 5 milliseconds and output every 0.1 milliseconds. It should print 50 readings. You should choose your measurements based on the frequency of the input source to allow you to see the full wave,

Usage

.tran STEP END <START> <MAX>

  • STEP - is the time interval of how often a measurement is taken
  • END - is the time when spice will end measurement
  • START - (default 0) is the time when spice will start measurement
  • MAX - is used to define a STEP smaller than STEP (yeah confusing)

Note: spice manuals mention the step time of TRAN is not always used by spice. If END-START/50 is less than STEP spice will set step to the smaller value. I haven’t seen this affect my simulations yet.

Example

Download tran.cir

* TRAN analysis of RC circuit
Vin  2 0 AC SIN(0 0.02 440)
R5  2 1 1K
C1  1 0 4.7uF
.tran 0.1m 3m
.plot tran v(2), v(1)
.end

When running we can see a plot printed of our analysis.

$ ngspice -b tran.cir

No. of Data Rows : 63
--------------------------------------------------------------------------
                       * ac analysis of rc circuit
               Transient Analysis Tue Apr 21 22:55:08  2015

Legend:  + = v(2)             * = v(1)             
--------------------------------------------------------------------------
 time       v(2)    -2.00e-02   -1.00e-02    0.00e+00    1.00e-02    2.00e-02   
----------------------|-----------|-----------|-----------|-----------|
 0.000e+00  0.000e+00 .           .           X           .           .   
 1.000e-04  5.456e-03 .           .           *     +     .           .   
 2.000e-04  1.047e-02 .           .           *           +           .   
 3.000e-04  1.471e-02 .           .           *           .    +      .   
 4.000e-04  1.786e-02 .           .           *           .        +  .   
 5.000e-04  1.958e-02 .           .           .*          .          +.   
 6.000e-04  1.987e-02 .           .           .*          .          +.   
 7.000e-04  1.867e-02 .           .           . *         .         + .   
 8.000e-04  1.598e-02 .           .           . *         .      +    .   
 9.000e-04  1.213e-02 .           .           .  *        . +         .   
 1.000e-03  7.356e-03 .           .           .  *    +   .           .   
 1.100e-03  2.000e-03 .           .           . +*        .           .   
 1.200e-03 -3.490e-03 .           .      +    .  *        .           .   
 1.300e-03 -8.736e-03 .           .+          . *         .           .   
 1.400e-03 -1.328e-02 .       +   .           . *         .           .   
 1.500e-03 -1.684e-02 .  +        .           . *         .           .   
 1.600e-03 -1.916e-02 .+          .           .*          .           .   
 1.700e-03 -1.993e-02 +           .           .*          .           .   
 1.800e-03 -1.926e-02 +           .           *           .           .   
 1.900e-03 -1.714e-02 .  +        .           *           .           .   
 2.000e-03 -1.365e-02 .      +    .          *.           .           .   
 2.100e-03 -9.168e-03 .           +          *.           .           .   
 2.200e-03 -3.990e-03 .           .      +   *.           .           .   
 2.300e-03  1.502e-03 .           .          *.+          .           .   
 2.400e-03  6.873e-03 .           .          *.       +   .           .   
 2.500e-03  1.175e-02 .           .          *.           . +         .   
 2.600e-03  1.567e-02 .           .           *           .     +     .   
 2.700e-03  1.845e-02 .           .           *           .         + .   
 2.800e-03  1.986e-02 .           .           *           .          +.   
 2.900e-03  1.967e-02 .           .           .*          .          +.   
 3.000e-03  1.810e-02 .           .           .*          .        +  .   
----------------------|-----------|-----------|-----------|-----------|
 time       v(2)    -2.00e-02   -1.00e-02    0.00e+00    1.00e-02    2.00e-02   

elapsed time since last call: 0.018 seconds.

Controlling Output

To output data during simulation we use the PLOT and PRINT commands. These commands work together with dynamic analysis commands like TRAN to output analysis data points.

The plot command will plot a ascii chart of analysis.

.plot tran v(1), v(8)

The print command will print the value of the analysis.

.print tran v(1), v(8)

Running Spice

When simulating a circuit we have a few options.

# Running in batch mode
$ ngspice -b op.cir
# Running in interactive move
$ ngspice
> source op.cir
> run
# will display output as above
> edit
# Will allow editing of your circuit

Another option is to output the analysis data in raw format. This data can then be loaded up in ngnutmeg for further analysis.

# This commands runs the analysis in preamp.cir and outputs raw data to
# tran.raw
ngspice -b tran.cir -r tran.raw
# The below command loads the raw file into ngnutmeg and then displays the
# ngnutmeg prompt. The `plot v(1)` command will bring up a view of the wave form
ngnutmeg tran.raw
> plot v(2) v(1)

NGNutmeg Analysis

Further Reading

Keep an eye on this stack exchange discussion which mentions other tools for simulating circuits in linux.

These guides have been very help:


Compiling Verilog on the Command Line with ModelSim

05 Apr 2015

Lately I have been working on some projects using verilog. My main development environment has been Altera Quartus II which works fine. However, when compiling in quartus we don’t always need to go through all of the sythesis and timing steps, instead one may just need to verify their source code is compilable.

The vlog compiler included with ModelSim can be used to quickly compile your HDL.

 # Add module sim onto your path
 $ PATH=$PATH:/usr/share/altera/14.0/modelsim_ase/bin

 # Create a library directory used by 'vlog', by default it looks for 
 # the 'work' library
 $ vlib work

 # Perform the verilog compile
 $ vlog dram_controller.v

 Model Technology ModelSim ALTERA vlog 10.1e Compiler 2013.06 Jun 12 2013
 -- Compiling module dram_controller

 Top level modules:
    dram_controller

You can find more details on using ModelSim’s command line utilties at the ncsu modelsim tutorial.


Setting up USB-Blaster in Linux

30 Jul 2014

Today I got my DE0-Nano FPGA development board. The first thing I wanted to do was get the linux connectivity setup; so I plugged it in. The device was recognized as character devide by linux right away.

Next, I checked Altera to see if anything special was needed for getting USB-Blaster setup in linux. They recommend some udev example rules to make the device file world writable, I guess that is ok. I dropped the udev rules into /etc/udev/rules.d/51-usbblaster.rules and unplugged then replugged the device but nothing happened.

I havent setup udev rules for a while, so right away I wasn’t able to spot the problem. I was able to test the rules using udevadm as below.

    udevadm test /bus/usb/devices/3-1

It complained that BUS and SYSFS matchers were not valid. They were removed in 2011 according to the udev changelog.

Using udevadm we are also able to see the proper attributes that we should be matching. Below is what I have come up with to properly setup USB-Blaster in linux. I am using Fedora 18.

    udevadm info -a --path=/sys/bus/usb/devices/3-1

My USB-Blaster udev Rules

    # USB-Blaster
    SUBSYSTEM=="usb", ATTRS{idVendor}=="09fb", ATTRS{idProduct}=="6001", MODE="0666", SYMLINK="usbblaster%n"
    SUBSYSTEM=="usb", ATTRS{idVendor}=="09fb", ATTRS{idProduct}=="6002", MODE="0666"
    SUBSYSTEM=="usb", ATTRS{idVendor}=="09fb", ATTRS{idProduct}=="6003", MODE="0666"
    #
    # # USB-Blaster II
    SUBSYSTEM=="usb", ATTRS{idVendor}=="09fb", ATTRS{idProduct}=="6010", MODE="0666"
    SUBSYSTEM=="usb", ATTRS{idVendor}=="09fb", ATTRS{idProduct}=="6810", MODE="0666"

Note, since my device is a 6001 I setup a symlink which will make it easily accessable at /dev/usbblaster1.

Hopefully this will be helpful to other people.