<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Benedek Rácz on Medium]]></title>
        <description><![CDATA[Stories by Benedek Rácz on Medium]]></description>
        <link>https://medium.com/@betontalpfa?source=rss-b6f662e6241f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*z9qJfJboitFHsx4XzvpjTQ.jpeg</url>
            <title>Stories by Benedek Rácz on Medium</title>
            <link>https://medium.com/@betontalpfa?source=rss-b6f662e6241f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 02:04:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@betontalpfa/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Oh no! I need to write a PCI driver!]]></title>
            <link>https://betontalpfa.medium.com/oh-no-i-need-to-write-a-pci-driver-2b389720a9d0?source=rss-b6f662e6241f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b389720a9d0</guid>
            <category><![CDATA[kernel-module]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[pci]]></category>
            <category><![CDATA[lspci]]></category>
            <category><![CDATA[device-drivers]]></category>
            <dc:creator><![CDATA[Benedek Rácz]]></dc:creator>
            <pubDate>Thu, 22 Oct 2020 11:00:31 GMT</pubDate>
            <atom:updated>2020-10-22T13:33:07.603Z</atom:updated>
            <content:encoded><![CDATA[<p>Step by step debug guide for PCIe device drivers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Om7grCpC_DEvbp8s" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The despair is real when someone has to develop a PCI driver with no experience in driver development. I try to give a step by step guide for those who have gotten stuck among memory spaces and system calls.</p><p>Because driver development is a challenging issue, it shouldn’t be written from scratch. Download one or more example projects from your vendors, and cherry-pick the needed parts. But what if an error comes up during the merge of the example drivers? I’ll try to give you a step by step guide to help locate the bug in the code. This will lead you from “It’s not working” to “It’s not working because …”.</p><h3>Start with a working example</h3><p>Driver development requires spread knowledge of both software and hardware.</p><p>Yes, it requires hardware knowledge. The drivers are very close to the hardware, so you must know something about the hardware. More precisely, you need to know the endpoint’s registers, its behavior. You should know something about the physical interface (PCIe) standard.</p><p>Linux drivers are written in C. Hard, native C. You will be a C expert in a while during driver development. Functions, macros, pointers, structures, union, special data-types, etc…</p><p>The drivers are plugins (i.e., modules) of the operating system. So driver development requires deep understanding of the operating system. You will use native system calls, virtual and physical memory operation, address transformation, memory spaces.</p><p>Drivers are concurrent. Drivers are the glue of multiple user-space application’s threads and the asynchronous hardware. You have to be clear about what data-structures are accessible locally and what are globally. And you have to prevent incoherent access to data using mutex and locks. Thread safety is a challenging topic on its own. Common problems are deadlocks, data-loss, or crash of the whole system.</p><p>After all of these threatening facts, I recommend starting the development from a working example. Buy a dev-board, download the example driver code from their site, and iterate from that driver.</p><p>Sometimes you just can’t find any relevant thing, or something just doesn’t work. The following chapters will guide you through basic steps to find and point on errors in the driver, which I hope will save you hours and days of headache.</p><h3>Step by step debug guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-8vxSvnHoAvhzgh9" /><figcaption>Photo by <a href="https://unsplash.com/@ninjason?utm_source=medium&amp;utm_medium=referral">Jason Leung</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>OK, I connected my boards, loaded the driver, and it does nothing. What should I do? Help! Here are the necessary steps:</p><ol><li>Is the device visible in <em>lspci</em>? (Link-up — lspci)</li><li>Has the driver <em>compiled </em>successfully? (Build the driver)</li><li>Has the driver <em>insertion </em>completed faultlessly? (Driver insertion)</li><li>Has the <em>probing </em>passed successfully? (Probing)</li><li>Do file operations work? (File operations)</li><li>Does your driver access the required registers? (Control the hardware)</li></ol><p>I recommend checking these points if any error has occurred. Be sure that a former point is OK before you step to the next.</p><h4>Link-up — lspci</h4><p>The first question is: Is your PCI link up? Has the enumeration been passed successfully? Check it with <a href="https://www.thegeekstuff.com/2014/04/lspci-examples/">lspci</a>. Lspci is your best friend. It must be clear: Your driver won’t be loaded if the desired device is not listed in lspci (i.e., not visible by the Linux).</p><p>Running the lspci with no arguments will list all bridges and endpoints. Note: embedded Linux can have no PCI device at all (lspci won’t print anything), while desktop Linux has ~10 (or more) PCI devices (SATA-, USB-controller, video-, audio-card, etc.) Find your device in the list. How? Let’s see an example:</p><pre>user@mypc:~$ lspci<br>0001:00:00.0 PCI bridge: NVIDIA Corporation Device 1ad2 (rev a1)<br>0001:01:00.0 SATA controller: Marvell Technology Group Ltd. Device 9171 (rev 13)</pre><p>I suggest to use with -vm switches:</p><pre>user@mypc:~$ lspci -vmm<br>Slot:   0001:00:00.0<br>Class:  PCI bridge<br>Vendor: NVIDIA Corporation<br>Device: Device 1ad2<br>Rev:    a1</pre><pre>Slot:   0001:01:00.0<br>Class:  SATA controller<br>Vendor: Marvell Technology Group Ltd.<br>Device: Device 9171<br>SVendor:        Marvell Technology Group Ltd.<br>SDevice:        Device 9171<br>Rev:    13<br>ProgIf: 01</pre><p>The essential part is the <em>Vendor </em>and the <em>Device</em>. Your given PCI endpoint should have a fixed <em>Vendor- </em>and the <em>Device-ID </em>pair. Search for it in your endpoint-device’s documentation. If your endpoint is an FPGA design, the FPGA IP generator tool has to have an option to set it. Here is an example of setting the IDs in Xilinx’s XDMA IP:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*aHbDKG5zJ9WezH6eqvv9Lg.png" /><figcaption>Set Device and Vendor IDs in Xilinx’s XDMA IP</figcaption></figure><p>The lspci will fetch and print a human-readable string form of the vendor instead of printing it in hex form by default. Use <a href="https://www.pcilookup.com/">https://www.pcilookup.com/</a> page to see which hex ID belongs to which vendor. Or use the -n argument of the lspci:</p><pre>user@mypc:~$ lspci -vmn<br>Device: 0001:00:00.0<br>Class:  0604<br>Vendor: 10de<br>Device: 1ad2<br>Rev:    a1</pre><pre>Device: 0001:01:00.0<br>Class:  0106<br>Vendor: 1b4b<br>Device: 9171<br>SVendor:        1b4b<br>SDevice:        9171<br>Rev:    13<br>ProgIf: 01</pre><p>If you don&#39;t see your device here (i.e., desired vendor and device ID pair), unfortunately, you have to dive into hardware debugging...</p><p><strong><em>Debug tips:<br></em></strong>Note that if your system does not support PCI hotplugging, your PCI endpoint should be up and running <em>before </em>the host (i.e., the Linux) is powered. Power on the endpoint first, and then power on the host Linux.</p><p>Check connections! Basic PCI requires N number of lanes (N TX-, and RX-pairs), reference clock for both sides. Some require the PERSTN reset pin. But first of all, read the documentation of your device about the required PCI pins.</p><p>Try to read and dump endpoint’s internal registers. Check if it has locked to the reference clock, check if the PCI core is in a reset state, etc…</p><h4>Build the driver</h4><p>I want to encourage you again to start from an example driver. Open your favorite internet and find a driver for your device or a similar device. I encourage you to start with your host’s examples. I mean, if your host Linux runs on an NXP-ARM, and your endpoint is a Xilinx FPGA, you should start from an NXP driver, then merge it with your FPGA vendor’s driver. In this case, the build will be simpler. I mean, the NXP example driver will compile successfully on their device or with less pain than an Xilinx example driver.</p><p>So let’s download your driver and try to build. Note that building a driver will require special headers and a bit different settings. (The gcc -o mydriver, won’t be a success.) The example driver should contain a makefile for building it. If you are interested in more details of driver building, please check out <a href="https://www.oreilly.com/library/view/linux-device-drivers/0596005903/ch02.html">this article</a>.</p><h4>Driver insertion</h4><p>After a successful build, you have to see a *.ko file (kernel object) in the build folder, your fresh driver. You can insert it with the <a href="https://linux.die.net/man/8/insmod">insmod</a> command.</p><pre>user@mypc:~$ insmod mydriver.ko</pre><p>Then you should see it in the modules. List it with the lsmod:</p><pre>user@mypc:~$ lsmod<br>Module                  Size  Used by<br><strong>mydriver               28503  0</strong><br>fuse                  103841  3<br>nvgpu                1579891  21 picoevb_rdma<br>ip_tables              19441  0<br>x_tables               28951  1 ip_tables</pre><p>If your driver is not listed here, the module insertion has failed. Note that the driver should be listed here even if no related device is found in the system (when the lspci lists no relevant device.) Note that the <em>“Used by”</em> counts the applications that have opened that device, and not the number of handled devices. (So this “Used by” will be 0 even after your device is visible in lspci.)</p><p><strong><em>Debug tips:<br></em></strong>If you cannot see your driver, let’s debug it. The main entry point of a driver is the parameter of <a href="https://www.kernel.org/doc/htmldocs/kernel-hacking/routines-init-again.html">module_init()</a> macro. This function will be called after insmod-ing. This function must return 0 on success.</p><p>From this point, the <a href="https://www.kernel.org/doc/html/latest/core-api/printk-basics.html">printk()</a> and the <a href="https://man7.org/linux/man-pages/man1/dmesg.1.html">dmesg</a> will be your first debug tools. Place printk() to the first line and all return points of the initiator function. Check your prints in another window using dmesg -w to see new messages.</p><p>Some error crashes the system, which results in you can’t see all prints in dmesg. In this case, checkout the /var/log/ directory for the logs of the crashed system.</p><p>For more details, read the official guide about the <a href="https://static.lwn.net/images/pdf/LDD3/ch02.pdf">Building and Running Modules Chapter</a> of the LDD.</p><h4>Probing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L3V6RjYn3IZgUnnM" /><figcaption>Photo by <a href="https://unsplash.com/@kjarrett?utm_source=medium&amp;utm_medium=referral">Kevin Jarrett</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>While the module insertion has finished successfully, the <em>probing will </em>start. From <a href="https://www.kernel.org/doc/html/latest/PCI/pci.html">kernel.org</a>:</p><blockquote>Probing function gets called (during execution of pci_register_driver() for already existing devices or later if a new device gets inserted) for all PCI devices which match the ID table and are not “owned” by the other drivers yet. This function gets passed a “struct pci_dev *” for each device whose entry in the ID table matches the device. The probe function returns zero when the driver chooses to take “ownership” of the device or an error code (negative number) otherwise. The probe function always gets called from process context, so it can sleep.</blockquote><p>The probing function should be registered in the <a href="https://www.kernel.org/doc/htmldocs/kernel-hacking/routines-init-again.html">module_init()</a> by the pci_register_driver() call. It gets a parameter called <a href="https://elixir.bootlin.com/linux/latest/source/include/linux/pci.h#L821">pci_driver</a>, which holds all driver operations, as well as the probing function. This probing function will be called when a relevant device is available in the system. Note that at this point, our threads have joined. The module insertion can be done if our PCI device is not visible in the lspci, but the probing requires a relevant PCI device.</p><p>What does a relevant device mean? The device has a vendor/device ID pair (and some further identifier, which can be printed by the lspci), while the device driver has a pci_device_id structure with one or more vendor/device IDs. The driver’s IDs must match the device’s ID to be able to handle it.</p><p>So when our device is listed by the lspci (checkout<em> Link-up — lspci </em>section), and our driver is listed under the lsmod (checkout <em>Driver insertion</em> section), the probing function must be called, which results in the lspci verbose mode will list your driver as the used driver by the device:</p><pre>user@mypc:~$ lspci -v<br>0005:01:00.0 Memory controller: NVIDIA Corporation Device 8034<br>        Subsystem: NVIDIA Corporation Device 0001<br>        Flags: bus master, fast devsel, latency 0, IRQ 39<br>        Memory at 1f40000000 (32-bit, non-prefetchable) [size=512M]</pre><pre>        ...</pre><pre>        Capabilities: [300] #19<br>        <strong>Kernel driver in use: mydriver</strong></pre><p>If the last line is missing, the probing has failed.</p><p><strong><em>Debug tips:<br></em></strong>Trace the probing function using printk() and dmesg as above in the <em>Driver insertion</em> section. (The probing function must return 0 on success. Check it.) If you cannot see any print (or any relevant error) the pci_device_id should be wrong. Check if the vendor/device ID in that structure matches the vendor/device ID in the lspci -vm.</p><p>The iomap of the PCI BAR(s) usually takes place in the probing function. If your probing has failed around the iomap, you can just comment them out for a while, to fix later, or check out the related part in the <em>Control the hardware</em> section.</p><h4>File operation</h4><p>We have a device and a driver for it so far. But how can we communicate with the device? The probing function should create a character device using the cdev_init(), cdev_add()and the device_create() functions. The cdev_init() gets a <a href="https://www.oreilly.com/library/view/linux-device-drivers/0596000081/ch03s03.html">file_operations</a> structure, which describes the valid file operations and registers their handler function.</p><p>A driver usually (always) registers one or more character devices. So after probing (not inserting), a new file should appear under the /dev folder. The name of the file is defined as the last parameter of the device_create(). Find that filename in the /dev folder:</p><pre>user@mypc:~$ ls /dev/mydriver<br>/dev/mydriver</pre><p>If you cannot see your character device under the dev, be sure that previous points (insertion) have passed and you have registered and added the character device correctly.</p><p>The most important handlers of the file_operations are the open and release (the close). These two functions only allocate/release memory regions, and they don’t do any hardware operation on your device usually.</p><p>I suggest implementing the read operation (beside the open and close) by filling the given buffer with some useful information. Here is a basic example:</p><pre>static ssize_t fops_read(struct file *filep, char *buffer, size_t len, loff_t *offset_ptr){<br> int error_count = 0;<br> char kbuff[2048]; // kernel buffer<br> int kbuff_len = 2048;<br> loff_t offset = *offset_ptr;</pre><pre>printk(KERN_CRIT &quot;Open start&quot;);<br> <br> if(offset &gt; 0){<br>  // End of file Does not support to read more chuks, seek etc...<br>  return 0;<br> }</pre><pre>offset += snprintf(kbuff, kbuff_len, &quot;Hello from My driver\n&quot;);</pre><pre>error_count = copy_to_user(buffer, kbuff, offset);</pre><pre>if (error_count==0){            // if true then have success<br>  printk(KERN_CRIT &quot;Read success!\n&quot;);<br>  *offset_ptr = offset; // Increment the offset<br>  return offset;  // Return the count of the read character<br> }<br> else {<br>  printk(KERN_CRIT &quot;Failed to send %d characters\n&quot;, error_count);<br>  return -EFAULT;<br> }<br>}</pre><p>After that, you can cat your device:</p><pre>user@mypc:~$ cat /dev/mydriver<br>Hello from My driver<br>user@mypc:~$</pre><p>If the cat failed, one of the open, close, or read has failed. Locate the error with our favorite printk and dmesg.</p><h4>Control the hardware</h4><p>At this point, we have a driver with an attached hardware device. We have a basic knowledge of implementing the file operations. It’s time for controlling the hardware using our device driver.</p><p>The most elegant way to communicate with a driver from the user-space application is the <a href="https://man7.org/linux/man-pages/man2/ioctl.2.html">ioctl</a>. Let’s implement our ioctl beside the open, release, and read in the <a href="https://www.oreilly.com/library/view/linux-device-drivers/0596000081/ch03s03.html">file_operations</a>.</p><p>Define your hardware-specific commands and call them from the <em>main-ioctl</em> function. For example define LED_ON and LED_OFF operation, and call led_on() and led_off() function from a switch-case from the <em>main-ioctl</em>. These hardware-specific command-functions should implement the exact device access by reading and writing its registers.</p><p>At this point, you should open your device’s documentation, register map, or their example code, how to control their device. In an ideal word, no error would appear… but what should we do if the device won’t do what we want? How to debug at this point?</p><p><strong><em>Debug tips:<br></em></strong>Again, the printk, dmesg pair is a good debugging tools, but I suggest another mechanism beside them. A useful debug tool can be the <a href="https://www.commandlinux.com/man-page/man1/busybox.1.html">busybox </a>command (not the software suite). You can read/write to/from a physical address with this. For this, you will need the BAR of the PCI. But what is this?</p><p>The BAR <a href="https://en.wikipedia.org/wiki/PCI_configuration_space#Standardized_registers">(Base Address Register</a>) shows where the device memory region(s) has been mapped to in the Linux’s memory. The memory mapping is done during the bus enumeration, so when the device is visible in the lspci, the BAR(s) has been set already. Let’s see lspci:</p><pre>user@mypc:~$ lspci -v<br>0005:01:00.0 Memory controller: NVIDIA Corporation Device 8034<br>        Subsystem: NVIDIA Corporation Device 0001<br>        Flags: bus master, fast devsel, latency 0, IRQ 39<br><strong>        Memory at 1f40000000 (32-bit, non-prefetchable) [size=512M]<br>        Memory at 1f60000000 (32-bit, non-prefetchable) [size=64K]</strong><br>        Capabilities: [80] Power Management version 3</pre><pre>        ...</pre><p>In this case, we have two BARs that have been mapped to 0x1f40000000 and 0x1f60000000 respectively. Reading and writing the device registers have to be offset by these addresses. So take an arbitrary register address from the device’s documentation, and add to the proper BAR to access it:</p><pre>busybox devmem &lt;BAR + device_register&gt; # Read a register<br>busybox devmem &lt;BAR + device_register&gt; w &lt;value&gt; # Write a register</pre><p>This, busybox devmem can be a handy debug tool. You can check all of your registers after your faulty driver.</p><p>Note that using the busybox command, you can control your PCIe device without your device driver (right after that the device is visible in the lspci). Sure, this is not what we want, but it is a handy way of board bring-up.</p><h4>+1 Concurrency</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IqpgcT3MFH7GkTgR" /><figcaption>Photo by <a href="https://unsplash.com/@jon_chng?utm_source=medium&amp;utm_medium=referral">Jonathan Chng</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Concurrency is crucial and not a negligible part of device drivers. You can say that you will use the driver only in one application, which runs on only one thread (which seems a hard limitation), but what about the hardware interrupts? If you handle the interrupts from the hardware in your driver (i.e., <a href="https://www.kernel.org/doc/html/latest/core-api/genericirq.html">registering your callback</a> with request_irq()) you have to care about the data coherency and thread-safety.</p><p>There are many great descriptions about thread safety on the internet, so I won’t explain how to do it. I just want to highlight that concurrency is a real and challenging topic in device drivers. First, I suggest modeling your driver’s race conditions in any higher-level language (Java, Python), which can handle crash and deadlocks without the system crash. Then I would implement the same in C, but in a simple <em>hello_thread</em> application. Then when these models have passed, I would implement the locks and mutex in my driver.</p><p>Please check out the <a href="https://static.lwn.net/images/pdf/LDD3/ch05.pdf">Concurrency and Race Conditions</a> chapter of the LDD, which describes which lock has to be used and where to prevent deadlocks and incoherent data access..</p><h3>Sum</h3><p>However, Linux device driver development is not an easy task, but this article is not for threatening you. It just gives steps for developing. I highly recommend using this step by step methodology. And do not enter the next step if you have problems with a former one. What’s more, check what step you are in before posting your issues on forums. You will be able to ask the right question if you know what step has been failed.</p><p>So let’s develop device drivers step by step!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b389720a9d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Control the world from Python]]></title>
            <link>https://medium.com/analytics-vidhya/control-the-world-from-python-532c3ebb6266?source=rss-b6f662e6241f------2</link>
            <guid isPermaLink="false">https://medium.com/p/532c3ebb6266</guid>
            <category><![CDATA[spawn]]></category>
            <category><![CDATA[control]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[subprocess]]></category>
            <dc:creator><![CDATA[Benedek Rácz]]></dc:creator>
            <pubDate>Mon, 09 Dec 2019 13:09:38 GMT</pubDate>
            <atom:updated>2019-12-12T09:17:36.258Z</atom:updated>
            <content:encoded><![CDATA[<h4>Interacting with Windows applications from Python using wexpect</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iJIQ7TvxI2Jvb1uO" /><figcaption>Photo by <a href="https://unsplash.com/@casparrubin?utm_source=medium&amp;utm_medium=referral">Caspar Camille Rubin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A couple of months before, a sunny afternoon I wanted to control a Windows application from Python. It seemed an easy task for me, but I haven’t found any satisfying solution. Finally, I become a maintainer of a <a href="https://pypi.org/project/wexpect/">PyPI project</a> called <a href="https://github.com/raczben/wexpect">wexpect</a>…</p><p>If you want to launch an application and get its output, your friend is <a href="https://docs.python.org/3.7/library/subprocess.html#subprocess.Popen.communicate">subprocess.communicate()</a> method. But, this is not a real interaction. If your child process needs input (synchronized to its output) <a href="https://stackoverflow.com/a/4417735/2506522">subprocess.Popen.stdout.readline</a> can be used. (Pexpect’s <a href="https://github.com/pexpect/pexpect/blob/master/pexpect/popen_spawn.py">popen_spawn</a> class uses this technique.) But unfortunately, some application requires a terminal, at least a pseudo-terminal, and these applications won’t be interactive using subprocess.Popen.</p><p>This is where I have found wexpect, which had several variants on the web, with no documentation, no tests, lack of integration, etc… at that time. Now <a href="https://github.com/raczben/wexpect">wexpect</a> runs under Python 3.x, and uploaded to <a href="https://pypi.org/project/wexpect/">PyPi</a>, so it can be installed with pip.</p><h3>Wexpect</h3><p><a href="https://github.com/raczben/wexpect">Wexpect </a>has a pseudo-terminal implementation in Python for Windows. It uses the <a href="https://github.com/mhammond/pywin32">pywin32</a> package which gives great access to <a href="https://docs.microsoft.com/en-us/windows/win32/apiindex/windows-api-list">Win32 API</a>. Wexpect runs child applications in this pseudo-terminal. This is why all Windows applications can be interacted using Wexpect.</p><h4>Requirements</h4><p>To use wexpect you need the following stuffs:</p><ul><li>Windows PC. (On Linux you can use <a href="https://github.com/pexpect/pexpect">pexpect</a>)</li><li>Python 3.x, with pip.</li></ul><p>Unfortunately, IDEs (Pycharm, Spyder, etc…) are <a href="https://github.com/raczben/wexpect/issues/1">not supported</a>, so use a cmd command prompt.</p><h4>Installing</h4><p>To install wexpect run:</p><p>pip install wexpect</p><p>It will install wexpect itself, and the only required module pywin32. (For development usage run pip install wexpect[test])</p><h4>Hello World!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yXvGrfaihV-TnYBz" /><figcaption>Photo by <a href="https://unsplash.com/@2photopots?utm_source=medium&amp;utm_medium=referral">2Photo Pots</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s write our first script using wexpect:</p><pre>&#39;&#39;&#39;<br>hello_wexpect.py</pre><pre>This script lists the current directory and exits.<br>&#39;&#39;&#39;</pre><pre>import wexpect</pre><pre># Start dir as child process<br>child = wexpect.spawn(&#39;dir&#39;)</pre><pre># Waiting for dir termination.<br>child.expect(wexpect.EOF)</pre><pre># Prints the directory content<br>print(child.before)</pre><p>The script will print the output of the directory content:</p><pre>D:\medium&gt;python hello_wexpect.py<br>hello_wexpect.py</pre><pre>D:\medium&gt;</pre><p>Now we have learned, that the child application can be started with the spawn() method. The expect() method is for catching a given pattern in the child’s output, which is the end of the output now. (In the next example we will see a more complex example for expect()) The before field holds the child’s output before the expect-pattern.</p><h4>FTP wrapper</h4><p>The following example will spawn the FTP program, and all output will be printed to console, and all command will be sent to the child FTP application:</p><pre># ftp_wrapper</pre><pre>import sys<br>import os<br>import re<br>import wexpect</pre><pre># Path of ftp executable:<br>ftp_exe = &#39;ftp&#39;<br># The prompt should be more sophisticated than just a &#39;&gt;&#39;.<br>ftpPrompt = [&#39;ftp&gt; &#39;, &#39;: &#39;, &#39;To &#39;]</pre><pre># Start the child process<br>p = wexpect.spawn(ftp_exe, timeout=5)</pre><pre># Wait for prompt<br>p.expect(ftpPrompt, timeout = 5)</pre><pre># print the texts<br>print(p.before, end=&#39;&#39;)<br>print(&#39;wexpect-&#39; + p.after, end=&#39;&#39;)</pre><pre>while True:<br># Wait and run a command.<br>    command = input()<br>    p.sendline(command)<br>    <br>    try:<br>        # Wait for prompt<br>        p.expect(ftpPrompt)<br>        <br>        # print the texts<br>        print(p.before, end=&#39;&#39;)<br>        print(p.after, end=&#39;&#39;)<br>    <br>    except wexpect.EOF:<br>        # The program has exited<br>        print(&#39;The program has exied... BY!&#39;)<br>        break</pre><p>If you have run this code, you get a wexpect-ftp&gt; prompt. <a href="https://www.serv-u.com/features/file-transfer-protocol-server-linux/commands">All FTP commands</a> are accepted because all command is sent to the child FTP application. Try help or open. Exit with bye.</p><p>Note, that the parameter of the expect() is a list now because FTP uses different prompts in different commands. A new essential method has appeared, the sendline(). This sends commands to child. The last new thing is the after field, which holds the prompt itself.</p><h4>What’s next?</h4><p>We have learned the very basics of the wexpect module, however, this is enough in most of the cases. More examples of usages can be found under <a href="https://github.com/raczben/wexpect/tree/master/examples">examples</a> and <a href="https://github.com/raczben/wexpect/tree/master/tests">test </a>directories.</p><p>So, now Windows can be controlled from Python.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=532c3ebb6266" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/control-the-world-from-python-532c3ebb6266">Control the world from Python</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FPGA output timing constraints tips and tricks]]></title>
            <link>https://betontalpfa.medium.com/fpga-output-timing-constraints-tips-and-tricks-be4a1c56d973?source=rss-b6f662e6241f------2</link>
            <guid isPermaLink="false">https://medium.com/p/be4a1c56d973</guid>
            <category><![CDATA[timing]]></category>
            <category><![CDATA[constraints]]></category>
            <category><![CDATA[output]]></category>
            <category><![CDATA[multi-cycle]]></category>
            <category><![CDATA[fpga]]></category>
            <dc:creator><![CDATA[Benedek Rácz]]></dc:creator>
            <pubDate>Fri, 16 Aug 2019 16:36:01 GMT</pubDate>
            <atom:updated>2019-08-16T16:36:01.112Z</atom:updated>
            <content:encoded><![CDATA[<p>Today’s protocol are mostly <em>self synchronous</em>, which don’t need global synchronous behavior. However, in some cases we cannot avoid global synchronicity. Let’s assume that we want to build a <a href="https://en.wikipedia.org/wiki/Data_acquisition">DAQ</a> (Data-acquisition) unit, which requires precision trigger-timing. All modules need the trigger signal at the same time.</p><p>This story is based on the <a href="https://github.com/raczben/tco_study">tco_study </a>repository, which contains example project for this problem. The sample projects uses Xilinx’s Ultrascale architecture (more precisely the xcku040-ffva1156–2-i device), however the methodology is general and can be applied to any FPGA.</p><h3>Timing requirements</h3><p>This section is optional. You can skip to the next section, you only need to accept the minimum odelay_m = 3.0 and the maximum odelay_M = 8.0 output delays.</p><p>I recommend Altera’s <a href="https://www.intel.com/content/dam/www/programmable/us/en/pdfs/literature/manual/mnl_timequest_cookbook.pdf">cookbook</a> or the Xilinx’s <a href="https://www.xilinx.com/support/documentation/sw_manuals/xilinx2019_1/ug949-vivado-design-methodology.pdf">Ultrafast design methodology</a> to understand the system of the I/O timing constraints. The following picture is from the <a href="https://www.intel.com/content/dam/www/programmable/us/en/pdfs/literature/manual/mnl_timequest_cookbook.pdf">cookbook</a>.</p><figure><img alt="Block diagram of Chip-to-Chip Design with Virtual Clocks as Input/Output Ports" src="https://cdn-images-1.medium.com/max/693/0*N4oSravkW6W5yW3L.png" /><figcaption>Chip-to-Chip Design with Virtual Clocks as Input/Output Ports</figcaption></figure><p>This study only deals with the <em>B</em> side, where the FPGA is the signal driver.</p><p>Here are the output timing constraints with random values for the delays. (The *_m denotes the minimum, the *_M denotes the maximum values)</p><pre># create a 100MHz clock<br>create_clock -period 10.000 [get_ports i_clk_p]</pre><pre>#create the associated virtual input clock<br>create_clock -name clkB_virt -period 10</pre><pre>#create the input delay referencing the virtual clock<br>#specify the maximum external clock delay from the global oscillator towards the FPGA<br>set CLK_fpga_m 3.5<br>set CLK_fpga_M 4<br>#specify the maximum external clock delay from the global oscillator towards the DAQ module<br>set CLK_daq_m 5<br>set CLK_daq_M 6.5<br>#specify the maximum setup and minimum hold time of the DAQ module<br>set tSUb 2<br>set tHb 0.5<br>#Board delay from FPGA to DAQ module (on trigger)<br>set BD_trigger_m 6.5<br>set BD_trigger_M 7.0</pre><pre># odelay_M = 8.0<br># odelay_m = 3.0<br>set odelay_M [expr $CLK_fpga_M + $tSUb + $BD_trigger_M - $CLK_daq_m]<br>set odelay_m [expr $CLK_fpga_m - $tHb  + $BD_trigger_m - $CLK_daq_M]</pre><pre>#create the output maximum delay for the data output from the<br>#FPGA that accounts for all delays specified (odelay_M = 8.0)<br>set_output_delay -clock clkB_virt -max [expr $odelay_M] [get_ports {&lt;out_ports&gt;}]<br>#create the output minimum delay for the data output from the<br>#FPGA that accounts for all delays specified (odelay_m = 3.0)<br>set_output_delay -clock clkB_virt -min [expr $odelay_m] [get_ports {&lt;out_ports&gt;}]</pre><p>Finally the output timing includes only two numbers, the minimum and the maximum values of the output delay:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*UpD6otof_o_C_vpI2tFV0Q.png" /><figcaption>Interpretation of output delay</figcaption></figure><p>So the final numbers for this study are odelay_M = 8.0 and odelay_m = 3.0.</p><h3>Single-cycle failings</h3><p>First, let’s show some simple approaches, which don’t need deep FPGA knowledge. Although, we will see that these implementations cannot fulfill these challenging timing requirements. And finally we will use a multicycle constraint in the next chapter.</p><p>In this chapter all outputs have the following output delay constraints: (See previous chapter for details)</p><pre>#create the output maximum delay for the data output from the<br>#FPGA that accounts for all delays specified (odelay_M = 8.0)<br>set_output_delay -clock clkB_virt -max $odelay_M [get_ports {&lt;out_ports&gt;}]<br>#create the output minimum delay for the data output from the<br>#FPGA that accounts for all delays specified (odelay_m = 3.0)<br>set_output_delay -clock clkB_virt -min $odelay_m [get_ports {&lt;out_ports&gt;}]</pre><h3>First (native) implementation</h3><p>The <a href="https://github.com/raczben/tco_study/blob/dev/singlecycle">singlecycle</a> design o_native_p (/n) ports demonstrate the simplest version. Simple means a native, fabric flip-flop output connected to the output buffer.</p><pre>-- Native<br>inst_native_obufds : OBUFDS<br>generic map(<br>  IOSTANDARD =&gt; &quot;LVDS&quot;<br>)<br>port map(<br>  O  =&gt; o_native_p,<br>  OB =&gt; o_native_n,<br>  I  =&gt; q_native_d2<br>);</pre><p>This implementation will fail the timings. The timing analyzer will report negative-slack in the setup time of the virtual clkB_virt clock:</p><pre>| Port name   | setup slack | hold slack |<br>|-------------|-------------|------------|<br>| o_native_p  | <strong>-4.421</strong>      | 5.777      |</pre><p>The negative setup-slack means our signal is too slow. Let’s try to make it faster!</p><h3>Place into IOB</h3><p>All FPGAs has a dedicated, fast output flip-flop, which is placed next to the output buffer. The <a href="https://github.com/raczben/tco_study/blob/dev/singlecycle">singlecycle</a> project o_iob_p (/n) ports demonstrate this solution.</p><p>Using Xilinx FPGAs the IOB property says the compiler to place the given flip-flop in the dedicated, fast output register. This property can be set as the following: set_property IOB TRUE [get_cells &lt;register_name&gt;]</p><p>Although, this results a bit closer slack it still fails the timing.</p><pre>| Port name | setup slack | hold slack |<br>|-----------|-------------|------------|<br>| o_iob_p   | <strong>-3.821</strong>      | 5.586      |</pre><h3>Dedicated DDR flip-flop</h3><p>Another dedicated flip-flop is located in the IO in modern FPGAs. This is the DDR flip-flop. This approach is implemented by the o_ddr_p (/n) output ports. An ODDRE1 device primitive needs to be placed in order to drive DDR data:</p><pre>ODDRE1_inst : ODDRE1<br>generic map (<br>  IS_C_INVERTED =&gt; &#39;0&#39;,  -- Optional inversion for C<br>  SRVAL =&gt; &#39;0&#39;           -- Initializes the ODDRE1 Flip-Flops to the specified value (&#39;0&#39;, &#39;1&#39;)<br>)<br>port map (<br>  Q =&gt; w_ddr,   -- 1-bit output: Data output to IOB<br>  C =&gt; w_clk,   -- 1-bit input: High-speed clock input<br>  D1 =&gt; q_ddr_d2, -- 1-bit input: Parallel data input 1<br>  D2 =&gt; q_ddr_d2, -- 1-bit input: Parallel data input 2<br>  SR =&gt; &#39;0&#39;     -- 1-bit input: Active High Async Reset<br>);</pre><p>Note, that to reach the same timing behavior we need to modify the output delay constraint. The maximum delay should be reduced by the half period of the system clock (ie. 5ns)</p><pre>set_output_delay -clock clkB_virt -max [expr $odelay_M -5] [get_ports {o_ddr*}]</pre><p>In spite of the efforts the timing fails, what’s more this method has the worst results:</p><pre>| Port name | setup slack | hold slack |<br>|-----------|-------------|------------|<br>| o_iob_p   | <strong>-4.616 </strong>     | 5.907      |</pre><h3>Sum of single-cycle</h3><p>This FPGA is not fast enough to fulfill these timing requirements. The following tables show all the setup/hold timings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xzTDwV0hFfTvoiOf.png" /><figcaption>Negative setup slacks of single-cycle implemetations</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7Uyr8iNOchD2A7hc.png" /><figcaption>Hold slacks of single-cycle implemetations</figcaption></figure><h3>Multi-cycle solutions</h3><p>To understand the root cause of the failed timings we should look under hood, and need to understand the timing details. The timing analyzer expects all data at the next clock edge from the launch clock by default (single-cycle). The following waveform shows the <em>required data valid window</em> on the FPGA pad. The data must be valid throughout this window. (It is permitted for the signal to be valid earlier or keep data even after this window, but during this slack of time the data <em>must</em> be valid.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*UpD6otof_o_C_vpI2tFV0Q.png" /></figure><p>(The destination clock uncertainty and any other delays must be added/subtracted to/from odelay_M/m to get the accurate valid window, but now these are negligible.)</p><p>Let’s see one particular case. (There is no essential difference between the previously demonstrated failing implementation, so let’s choose the <em>iob</em> type implementation.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*AoVSDoUcBW9vJE2NAM_oEA.png" /></figure><p>This default (single-cycle) mode requires faster behavior, which cannot be fulfilled by this FPGA. However, the <em>required valid window</em> is shorter that the guaranteed, real valid data window.</p><p>The length of the <em>required valid window</em> is req_len = odelay_M - odelay_m = 8 - 3 = 5</p><p>The length of the real valid data window is req_len + setup_slack + hold_slack = 5 - 3.8 + 5.6 = 6.8</p><p>So if these windows can be shifted, the timing could be closed.</p><p>In most system-synchronous cases additional fix, and known delays are acceptable. Let’s shift the <em>required data valid window</em> with a whole clock cycle. This one (or more) clock cycle delay called <em>multi-cycle path</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*LUrpeNAXTZVlWnZmSBPM5A.png" /></figure><p>In this case the FPGA doesn’t need to be as fast as in the single-cycle mode, but now it should be relatively more accurate to hit the whole <em>required valid window</em>. What’s more, the harder thing is not to violate the hold time requirements, in other words, to hold data till the end of the <em>required data valid window</em>. So we can say that the FPGA has to be “as slow as possible”.</p><p>To set the multi-cycle path only the following constraint is needed:</p><pre># Set multicycle path for all outputs<br>set_multicycle_path -to [get_ports o_*] 2</pre><p>The following chapters will show different implementations, which can solve this issue. To see more details open project from the <a href="https://github.com/raczben/tco_study/blob/dev/multicycle">multicycle</a> directory.</p><h3>Native multi-cycle implementation</h3><p>We have seen that the compiler cannot route as fast as required, but maybe it can solve this multi-cycle path problem. So let’s just implement a simple register, and connect to output port with the multi-cycle constraint. This idea is implemented by the o_native_mc_p (/n) ports.</p><p>After a longer compiling the timing fails in this case too.</p><pre>| Port name | setup slack | hold slack |<br>|-----------|-------------|------------|<br>| o_iob_p   | <strong>-3.555</strong>      | 0.579      |</pre><p>What happened? The compiler tried to use general routing resources to add delay to match the required data valid window. A huge routing time can be seen in the FPGA device view. Turn on the <em>Routing resources</em>,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/105/0*spEenXaS6RGI8qzC.png" /><figcaption>The Routing resources button.</figcaption></figure><p>and see the routing snake:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/0*UlBTHOBVXDqRHGXT.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/0*TaFXaqbiInccBr2E.png" /></figure><p>The detailed timing report of this failing path is also strange. Here is the setup report, with a more than 9ns routing time!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/0*hmhJPIQKT7JREtBR.png" /></figure><p>But the same routing time in the hold report (which uses the fast model of the FPGA) is less than 5ns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/0*zwpCuNIKDUXTZYXd.png" /></figure><p>So the problem is that the FPGA’s routing resources has greater uncertainty than what the constraints require. Note, that in simpler timing requirements you can stop here, because the router will add a proper delay. But now we have to investigate more. Let’s try to use dedicated delay elements, which called ODELAY.</p><h3>Using ODELAY</h3><p>Let’s try to replace the routing delays with dedicated output delays. This approach is implemented by the o_odelay_p (/n) ports of the <a href="https://github.com/raczben/tco_study/blob/dev/multicycle">multicycle</a> project. We need to replace the routing delay of the previous (failed) solution. This was 9.4ns, with -2.4 setup slack. So we need to delay ~7ns.</p><p>Ultrascale’s ODELAYE3 primitive can delays up to 1.25ns in fixed mode. So a cascaded delay structure is needed to delay ~7ns. But also note that using cascade, additional route delays added, so lets try with three cascaded ODELAYE3 primitive. The cascade instantiation is described in the <a href="https://www.xilinx.com/support/documentation/user_guides/ug571-ultrascale-selectio.pdf">UltraScale&#39;s SelectIO</a> user guide.</p><p>Wow! This is a working solution. The timing meets the requirements:</p><pre>| Port name | setup slack | hold slack |<br>|-----------|-------------|------------|<br>| o_odelay_p| 0.064       | 0.173      |</pre><p>However, both setup and hold slacks are tiny. What happened with our great valid window? Let’s see again the detailed timing reports (the data path delays only).</p><p>Slow model (for setup calculations):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/0*m5Wfl_h0L7RMegte.png" /></figure><p>Fast model (for hold calculations):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/0*pWKGIxaMSke2dc5r.png" /></figure><p>The same effect can be read from these numbers, as from the first multi-cycle implementation. The FPGA’s uncertainty tighten the real valid window. There is big difference between the slow (11.9) and fast (7.198) models data delay. Now this unwanted effect isn’t strong enough, so the timing could be closed, unlike the native implementation.</p><p>The next two chapters will show a more sophisticated solution.</p><h3>Using phase shifted clock</h3><p>o_iob_shifted_clk_p (/n) ports of the <a href="https://github.com/raczben/tco_study/blob/dev/multicycle">multicycle</a> project meet the timing by adjusting the clock of the last flip-flop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*OjeKJ8KSm7vpoCNlu8k3kA.png" /></figure><p>This technique quasi adds extra delay to the clock path towards the FPGA (the CLK_fpga_m (/M) in the constraint file). If the value of the clock_shift above equals the previously approximated ~7ns, the value of the tco will be a simple output delay. The ~7ns of the clock_shift has to be converted to phase for <a href="https://www.xilinx.com/support/documentation/ip_documentation/clk_wiz/v6_0/pg065-clk-wiz.pdf">Xilinx&#39;s clock wizzard</a>. 7ns/10ns*360deg = 252deg The <a href="https://github.com/raczben/tco_study/blob/dev/multicycle">multicycle</a> project uses 240deg (6.6ns) as phase which gives better results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/0*EI1Cy23FxVghGYdS.png" /></figure><p>The timing constraints are met again, with better results than the odelay one:</p><pre>| Port name            | setup slack | hold slack |<br>|----------------------|-------------|------------|<br>| o_iob_shifted_clk_p  | 0.850       | 1.290      |</pre><p>What great slacks! Both of setup and hold are above half a nanosecond.</p><p>Two notes for this technique:</p><ul><li>The data have to be transferred from the system_clk to this new shifted_clock, which requires one (or more to help internal timing) flip-flop. The timing requirements of this internal path (from system_clk to shifted_clock) is auto generated, cause a clock generator is used.</li><li>Maybe a couple of recompilation are needed with adjusted phase values, to get the better output timings. First, we can think if the setup slack is greater than the hold slack, more phase shift is needed, and vice versa. But it is misleading, because router can add extra internal delay, (as in native implementation) which can lead us the wrong way.</li></ul><h3>Using inverted clock with ODELAY</h3><p>The last presented method uses a mixed technology of the previous two. For implementation see o_odelay_nclk_p (/n) ports. A special phase shift is used: the output flip-flop driven by the inverted system clock. The clock inversion means 50% phase shift, which is 5ns in our case. added a</p><pre>| Port name            | setup slack | hold slack |<br>|----------------------|-------------|------------|<br>| o_odelay_nclk_p      | 0.687       | 1.212      |</pre><p>In general, a huge number of synchronous output can be handled using a shifted clock and one delay element primitive. The clock should be shifted according to the port with the fastest requirements (the greatest odelay_M), while the fix value of the delays can be adjusted port by port.</p><p>The clock inversion has another advantage, that it does not requires PLL/MMCM module. The clock buffer itself can invert the clock.</p><h3>Sum of multi-cycle solutions:</h3><p>The router itself couldn’t fit the timings in multi-cycle mode neither, but with some more additional tricks we have seen three successful implementations for these challenging output requirements.</p><pre>| Port name             | setup slack | hold slack |<br>|-----------------------|-------------|------------|<br>| o_iob_p  (fail)       | -3.555      | 0.579      |<br>| o_odelay_p            | 0.064       | 0.173      |<br>| o_iob_shifted_clk_p   | 0.850       | 1.290      |<br>| o_odelay_nclk_p       | 0.687       | 1.212      |</pre><h3>Summary</h3><p>I hope that you won’t encounter such challenging timings, but if its the case, now you can see that there is life after death… Clone this repository set your target device, modify the constraint files according to your requirements and try to close the timings.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be4a1c56d973" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Continous integration for open FPGA projects]]></title>
            <link>https://betontalpfa.medium.com/continous-integration-for-open-fpga-projects-29eab2c3b58b?source=rss-b6f662e6241f------2</link>
            <guid isPermaLink="false">https://medium.com/p/29eab2c3b58b</guid>
            <category><![CDATA[vhdl]]></category>
            <category><![CDATA[fpga]]></category>
            <category><![CDATA[travis-ci]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Benedek Rácz]]></dc:creator>
            <pubDate>Sun, 09 Jun 2019 12:22:04 GMT</pubDate>
            <atom:updated>2020-04-21T06:06:02.483Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/continous-integration-for-open-fpga-projects">Continuous integration for open FPGA projects</a></h3><h4>How can an open-source HDL project automatically be tested?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*Mgcq6IeLWvXYOaAAKMnLBg.png" /></figure><p>The following study is based on my <a href="https://github.com/raczben/travis-hdl">travis-hdl</a> repository.</p><h4>Introduction</h4><p>Fortunately, there are more and more open-source FPGA projects. There are some open testing frameworks, testing libraries. There are open simulators for hardware descriptor languages. There are several hosted continuous integration service. But none of them supports HDL codes natively. The following paragraphs will show how to use them for integrating and test your FPGA designs.</p><h4>Pre-requirements</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*oYoq5ZmEHDl2QFIFPD3xjA.jpeg" /></figure><p>However general my methodology is, I will show a concrete, working implementation basing on some particular tools. To understand the later paragraphs, I recommend to be familiar with the following tools:</p><ol><li>VHDL language</li><li><a href="https://bitvis.no/dev-tools/uvvm/">UVVM</a> open-source VHDL testbench infrastructure (optional)</li><li><a href="http://ghdl.free.fr/">GHDL</a> open-source simulator for the VHDL language</li><li><a href="https://www.docker.com/">Docker</a> virtualization software</li><li><a href="https://travis-ci.org/">Travis-CI</a> continuous integration service</li><li><a href="https://github.com/">Github</a> to store your open source project.</li></ol><h4>Working principles</h4><p>As I mentioned in the introduction, there isn’t any continuous integration service with native HDL support. Our goal is to “install” an HDL simulator to one of these servers. I chose Travis-CI and ghdl simulator.</p><p>Despite the lack of the official release of <a href="https://github.com/ghdl/docker">ghdl-docker</a>, I suggest using this (in contrast with native binary variant), because of the <a href="https://www.docker.com/why-docker">advantages of the Docker</a>. What’s more, it will be simpler when we want using on Travis-CI.</p><p>Using Docker requires no installation on Travis-CI, just a run of the ghdl Docker image is necessary, which is <a href="https://docs.travis-ci.com/user/docker/">supported</a> on Travis-CI.</p><h4>ghdl compiler script</h4><p>All testcases need to be written, and both the DUT and the testbench/testcases all construct must be supported by the ghdl simulator. So pure VHDL simulation is required. Note that fortunately, ghdl supports a wide range of VHDL-2008 constructs.</p><p>Now the compiler script can be created, which calls ghdl. The detailed usage of the ghdl can be found in <a href="https://ghdl.readthedocs.io/en/latest/">its documentation</a>. The following example will compile and run the ghdl’s hello world VHDL file.</p><pre># The directori of HDL source files<br>srcdir=/mnt/data/hello_world</pre><pre># Test GHDL itself<br>ghdl --version</pre><pre># List the files (validating the fileshare/mount, it will be handy later)<br>ls $srcdir</pre><pre># Analyse the source<br>ghdl -a $srcdir/hello_world.vhd</pre><pre># Elaborate the top-level<br>ghdl -e hello_world</pre><pre># Run the simulation<br>ghdl -r hello_world</pre><h4>Calling from ghdl-docker</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*BwUpgq0LO2ueREuxRGViCQ.png" /></figure><p>The <a href="https://runnable.com/docker/getting-started/">installation of the Docker</a> and the <a href="https://hub.docker.com/u/ghdl/">ghdl container</a> can be tested using the following command, which should print out the version of the ghdl simulator.</p><pre>docker run -t ghdl/ghdl:stretch-mcode ghdl — version</pre><p>Now, the compiler script above can be run. Note that hdl sources and script files have to be shared/mounted with the Docker using the <a href="https://docs.docker.com/storage/bind-mounts/">-v/mount</a> switch. The compiler call will be the following command¹.</p><pre>docker run -t -v `pwd`:/mnt/data ghdl/ghdl:stretch-mcode  /bin/bash -c  &quot;chmod u+x /mnt/data/hello_world/hello_world.sh; /mnt/data/hello_world/hello_world.sh&quot;</pre><h4>Using Travis for continuous integration</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*M33aFsJCty-HeqS87yWP0g.png" /></figure><p>At this point, everything can be integrated with Travis-ci, which requires a GitHub (or any other <a href="https://docs.travis-ci.com/user/deployment#supported-providers">supported provider</a>) repository of the project.</p><p><a href="https://docs.travis-ci.com/user/tutorial/">Setting up Travis-ci</a> builds up to two steps (after sign up).</p><ol><li><em>Activate</em> and select the repositories you want to use with Travis CI.</li><li>Add a .travis.yml <a href="https://docs.travis-ci.com/user/tutorial/">configuration</a> file to your repository to tell Travis CI what to do.</li></ol><p>My <a href="https://github.com/raczben/travis-hdl">travis-hdl</a> sample repository uses the following directory structure.</p><pre>├── .travis.yml           &lt;- Setting up travis-ci<br>├── adder                 &lt;- source folder<br>│   ├── adder.sh          &lt;- compile script<br>│   ├── adder.vhd         &lt;- vhdl sources<br>│   └── adder_tb.vhd<br>└── hello_world           &lt;- source folder<br>    ├── hello_word.vhd<br>    └── hello_world.sh</pre><p>The following bare-minimal .travis.yml file uses the docker-caller commands, which were demonstrated above.</p><pre># Specify, that we want to use docker in the docker :)<br>services:<br>  - docker</pre><pre># Here are the list of run scripts of different DUTs/testcases<br>script:<br>    # Testing the installation of the ghdl<br>  - docker run -t ghdl/ghdl:stretch-mcode ghdl --version<br>  <br>    # Mount the repo to docker, and run the hello world example<br>  - &gt; <br>    docker run -t -v `pwd`:/mnt/data ghdl/ghdl:stretch-mcode<br>    /bin/bash -c  &quot;chmod u+x /mnt/data/hello_world/hello_world.sh;<br>    /mnt/data/hello_world/hello_world.sh&quot;<br>    <br>    # Mount the repo to docker, and run the adder example<br>  - &gt;<br>    docker run -t -v `pwd`:/mnt/data ghdl/ghdl:stretch-mcode<br>    /bin/bash -c  &quot;chmod u+x /mnt/data/adder/adder.sh;<br>    /mnt/data/adder/adder.sh&quot;</pre><h4>Using UVVM (extra)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LJcBxCn8j0LGE8mFuP5Opg.png" /></figure><p>I recommend to use some simulation framework, <a href="https://semiengineering.com/knowledge_centers/eda-design/models/bus-functional-model/">BFM</a>, <a href="https://www.techdesignforums.com/practice/guides/verification-ip/">VIP</a>, or any other higher-level abstraction while writing an HDL simulation. I used <a href="https://bitvis.no/dev-tools/uvvm/">UVVM</a>, which is a maintained, open-source, pure VHDL-2008 verification framework.</p><p>I used git <a href="https://git-scm.com/book/en/v2/Git-Tools-Submodules">submodule capability</a> to add UVVM to my example project:</p><p>$ git submodule add <a href="https://github/UVVM/UVVM">https://github/UVVM/UVVM</a></p><p>The ghdl supports UVVM, but --std=08 and -frelaxed-rules switches must be added:</p><pre>ghdl -a --work=&lt;library&gt; --std=08 -frelaxed-rules &lt;source_file&gt;</pre><p>The same switches are needed to start elaboration and running. For more details see <a href="https://github.com/raczben/travis-hdl/tree/master/UVVM_scripts">scripts directory</a>.</p><h4>Summary</h4><p>This study has shown an example of a continuous-integration of a VHDL project. Next, I plan to show a similar example using Verilog language. And I will try to add code coverage stats to the current implementation.</p><p>The continuous-integration improves the quality of all projects. The FPGA/ASIC project requires a high-quality code because of the complicated debugging. This study shows that a VHDL project can be integrated continuously, online, simply. So, I encourage anybody to use some similar methodology for his/her HDL project.</p><p>[1] Using Dockerfiles is a more elegant way, but this inline call is enough for this simple example.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29eab2c3b58b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>