Tag Archives: ELK

Adding Networking Support to ELK: Part 3

Again I’m posting this as a post-in-progress. I was hoping to finish this before real life intrudes tomorrow. Things are going well but tomorrow looks like a real stretch goal.

In Part 1 of this post I wrote about some design goals for ELK networking. In Part 2, I described some of the implementation details that evolved as I integrated the LwIP TCP/IP stack into ELK. In this post, I’ll describe adding an Ethernet driver to ELK’s network implementation.

As in Part 2, I’m writing this as development is progressing, so be please patient if I tend to go off on tangents.

LwIP comes with a skeleton example Ethernet driver in src/netif/ethernetif.c. My ARM development environment is currently QEMU emulating the Versatile Express A9 board, which emulates the LAN 91C111 Ethernet controller. Eventually, I’d like to get ELK networking running on the Raspberry Pi, but since it uses a USB based Ethernet controller (the smsc9512), that will require a bit more work.

OK, enough with Google. Time to get to work. I’ll start or by making a copy of ethernetif.c which I have called lan91c111.c. Now I’ll start filling in the details.

I’ve made some basic changes to the driver and now I’ll add it to the list of ELK source files in sources.mk. I know the first build is going to spit out a bunch of errors, and sure enough it does. I’ll add a few “#if RICH” lines to mark places I have to add functionality. I got through the “#if RICH” part when I realized that I’m missing the whole infrastructure for socket ioctl() calls. I realized that when I started about how to initialize Ethernet devices. So I’m side tracking to add ioctl() support to the network interfaces.

As an aside, it turns out I had to make another change to the LwIP sources. One of the ioctl() calls supported on sockets is named IP_HDRINCL. It turns out that LwIP uses that name at the lower levels to represent a packet that already contains an address. I changed all instances of IP_HDRINCL to IP_HDRINCLUDED in LwIP to get around the naming conflict.

There are two interfaces that LwIP supports to configure Ethernet devices, basically because LwIP has two modes of operation as I mentioned in Part 1. The core of LwIP is meant to be used by a single (or the only) thread. That is the first mode, and is usually reserved for smaller systems where all network activity is done by a single thread. The second mode has a network thread which has a message based interface to all the other threads in the system. ELK uses the second mode, so we have to use the netifapi functions, defined in the lwip/netifapi.h file. I had to to enable this API in the ELK specific lwipopts.h file.

The ioctl() calls for sockets are documented in the netdevice(7) man page. We’ll see how well the LwIP API maps to Linux’s idea of network configuration.

There are a set of ioctl() calls defined that are used to configure network devices as described in netdevice(7). I’ve implemented a fairly large subset of socket ioctl() calls to prepare for actually adding the Ethernet driver. Here is an example of some of them:

/* ELK running as a VM enabled OS.
 */
#define _GNU_SOURCE
#include <sys/ioctl.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <arpa/inet.h>
#include <errno.h>
#include <string.h>

#include <sys/cdefs.h>
#include <stdio.h>

#include "command.h"

int main(int argc, char **argv)
{
  setprogname("elk");
  printf("%s started. Type \"help\" for a list of commands.\n", getprogname());

  int sfd = socket(AF_INET, SOCK_STREAM /*|SOCK_NONBLOCK */, 0);
  if (sfd < 0) {
    printf("socket(AF_INET) failed: %s\n", strerror(errno));
  }

  int s;
  struct ifreq ifreq;
  struct in_addr in_addr;

  // Set the device name for subsequent calls.
  strcpy(ifreq.ifr_name, "ln01");

  // Set the interface IP{ address.
  inet_aton("192.124.43.4", &in_addr);
  ifreq.ifr_addr.sa_family = AF_INET;
  memcpy(ifreq.ifr_addr.sa_data, &in_addr, sizeof(in_addr));
  s = ioctl(sfd, SIOCSIFADDR, &ifreq);
  if (s < 0) {
    printf("ioctl(SIOCSIFADDR) failed: %s\n", strerror(errno));
  }

  // Set ine interface netmask.
  inet_aton("255.255.255.0", &in_addr);
  ifreq.ifr_netmask.sa_family = AF_INET;
  memcpy(ifreq.ifr_netmask.sa_data, &in_addr, sizeof(in_addr));
  s = ioctl(sfd, SIOCSIFNETMASK, &ifreq);
  if (s < 0) {
    printf("ioctl(SIOCSIFNETMASK) failed: %s\n", strerror(errno));
  }

  // Set the interface MAC address.
  ifreq.ifr_hwaddr.sa_family = ARPHRD_ETHER;
  ifreq.ifr_hwaddr.sa_data[0] = 0x01;
  ifreq.ifr_hwaddr.sa_data[1] = 0x02;
  ifreq.ifr_hwaddr.sa_data[2] = 0x03;
  ifreq.ifr_hwaddr.sa_data[3] = 0x04;
  ifreq.ifr_hwaddr.sa_data[4] = 0x05;
  ifreq.ifr_hwaddr.sa_data[5] = 0x06;
  s = ioctl(sfd, SIOCSIFHWADDR, &ifreq);
  if (s < 0) {
    printf("ioctl(SIOCSIFHWADDR) failed: %s\n", strerror(errno));
  }
  printf("Try the command 'inetif'\n");

  // Enter the kernel command processor.
  do_commands(getprogname());
}

Where is what the compiled example produces:

[~/ellcc/examples/elk] dev% make run
Compiling main.c
Linking elk
Running elk
enter 'control-A x' to exit QEMU
audio: Could not init `oss' audio driver
elk started. Type "help" for a list of commands.
Try the command 'inetif'
elk % inetif
0 lo: active flags=137 (0x01)  mtu 0
        inet 127.0.0.1  netmask 255.0.0.0  broadcast 127.255.255.255
1 ln01: active flags=66 (0x32)  mtu 1500
        inet 192.124.43.4  netmask 255.255.255.0  broadcast 192.124.43.255
        ether 01:02:03:04:05:06
elk % 

ln01 is my stubbed driver. It looks like the ioctl() calls have worked. lwip_network.c is the source file implementing ELK's LwIP socket interface. Now it's time to get the driver to do something.

As I started to flesh out the driver I realized that the vexpress-a9 board that QEMU is emulating uses the LAN9118 Ethernet controller, not the SMC91C111 that I thought. That got me thinking. I really don't want to reinvent the wheel each time for all the different Ethernet controllers out there and it is always better to find something that exists and adapt it rather than to write it from scratch. With that in mind, I decided what it would take to use Ethernet drivers borrowed from NetBSD for ELK. As I see it, the first step is to get a NetBSD driver to compile in the ELK environment with as few source changes as possible. Step two is to make some glue code to make the NetBSD driver fit into the LwIP environment.

Yikes! I just spent a harrowing half a day trying to isolate the NetBSD driver for the LAN9118 so that it could "drop in" as a LwIP driver. I went down the path of stubbing out all the include files that were directly and indirectly included and compiling the source file, over and over, adding definitions to the include files as needed. It turns out that the driver has lots of dependencies on the NetBSD kernel, which is not surprising. I've decided to try a different route, but I did stumble on this interesting post about rump kernels, which are basically doing what ELK is doing, but with NetBSD as the basis.

I like the direction this new approach is taking. I'm using an idea from the LwIP wiki to create a driver framework. The driver skeleton has been fleshed out in ethernetif_driver.c and low level support for the LAN9118 is taking shape in lan9118.c. I hope I find some time over the next few days to fill in the reast of the details.

Adding Networking Support to ELK: Part 2

In a previous post I described how I started to add LwIP networking support to ELK, along with some of the design decisions that guide ELK development. In this post, I’ll describe how socket related system calls are added to ELK and how they interface with the LwIP network stack and the rest of the ELK modules.

A minimal source file that allows LwIP to be brought in to ELK at link time looks like this:

#include "config.h"
#include "kernel.h"
#include "lwip/tcpip.h"

// Make LwIP networking a select-able feature.
FEATURE_CLASS(lwip_network, network)

// Define socket related system calls.
ELK_CONSTRUCTOR()
{
}

// Start up LwIP.
C_CONSTRUCTOR()
{
  tcpip_init(0, 0);
}

Almost all symbols in an ELK select-able module are static. The only external linkage symbols in this module are defined by the FEATURE_CLASS() macro. In this case, the symbols __elk_lwip_network and __elk_feature_network are defined. The first symbol is used to pull this module in at link time. The second symbol is used to cause an error if another (currently non-existent) network module is linked in at the same time.

ELK used two phases of constructor functions to preform system initialization. ELK_CONSTRUCTOR() functions are called at system start up before the C library is initialized. These functions are typically used to initialize system call definitions. C_CONSTRUCTOR() functions are normal constructors called after the C library has been initialized but before main() is called. No system calls have been defined in this example, but the LwIP initialization function is called in the C_CONSTRUCTOR() phase.

There are several system calls that are specific to sockets and networking. I’ll create stub functions for all of them now. Even though I’m concentrating on getting ELK running on an ARM target right now, I always build ELK for all targets. My first attempt to create a stub handler for accept4() failed to compile for the i386:

#include <sys/socket.h>

#include "config.h"
#include "kernel.h"
#include "syscalls.h"
#include "lwip/tcpip.h"
#include "crt1.h"

// Make LwIP networking a select-able feature.
FEATURE_CLASS(lwip_network, network)

static int sys_accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
{
  return -ENOSYS;
}

// Define socket related system calls.
ELK_CONSTRUCTOR()
{
  SYSCALL(accept4);
}

// Start up LwIP.
C_CONSTRUCTOR()
{
  tcpip_init(0, 0);
}

It turns out that the i386 socket calls (and perhaps other targets) all go through one system call called SYS_socketcall. When I modified my source file like this:

#include <sys/socket.h>

#include "config.h"
#include "kernel.h"
#include "syscalls.h"
#include "lwip/tcpip.h"
#include "crt1.h"

// Make LwIP networking a select-able feature.
FEATURE_CLASS(lwip_network, network)

static int sys_accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
{
  return -ENOSYS;
}

#ifdef SYS_socketcall
static int sys_socketcall(int call, unsigned long *args)
{
  long arg[6];

  // Get the call arguments.
  copyin(arg, args, sizeof(arg));

  switch (call) {
  case __SC_accept4:
    return sys_accept4(args[0], (struct sockaddr *)arg[1], (socklen_t *)arg[2]);

  default:
    return -ENOSYS;
  }
}
#endif

// Define socket related system calls.
ELK_CONSTRUCTOR()
{
#ifndef SYS_socketcall
  SYSCALL(accept4);
#else
  SYSCALL(socketcall);
#endif
}

// Start up LwIP.
C_CONSTRUCTOR()
{
  tcpip_init(0, 0);
}

I’ll follow a similar pattern for the rest of the system calls. The result, with all the socket functions stubbed in, is here. Note that another little wrinkle is that at least some of the Linux ports, in this case the x86_64 port, don’t have the recv() and send() system calls. They use recvfrom() and sendto() instead.

Now I’ll start adding meat to the empty system call framework. I’ll start with the socket() system call, since it is the only way to get a socket and several design decisions will need to be made about how to interface with the rest of ELK. The normal LwIP socket descriptors index into a static array of structures containing the state of any open sockets. This means that all threads that use sockets share a socket namespace and that that socket namespace is different from the normal ELK file descriptor namespace. That is the first thing that has to change. To do that, I have to integrate LwIP sockets into the ELK VFS (Virtual File System) module. That is, a LwIP socket, when created, should result in the creation of a socket vnode. Subsequently, all operations on the socket should go through the vnode. The beauty of this approach is that socket descriptors and file descriptors will share the same namespace and that other operations that should be legal on sockets, like read() and write() (and select() when it gets implemented), will just work on all types of file descriptors as long as the low level support exists in the vnode implementation.

As I was delving into the implementation of the socket system call handling code, I realized that LwIP only implements the AF_INET and AF_INET6 domains. Since I’d like to support other domains, especially AF_UNIX, I decided to split the LwIP interface code out of the socket system call handling code. If I can set up the interfaces correctly, this should also allow other networking stacks to be dropped in in place of LwIP. So now I have network.c with the generic system call handling code and lwip_network.c with the LwIP interface glue.

Now’s the time to add error handling code to the system call handlers. This is really a stalling tactic while I’m thinking about how to integrate sockets into the existing virtual file system framework, but I suspect I’ll get some insights as I flesh out the generic code. After some thought and feverish coding, I came up with something that feels reasonable. I implemented the getsockopt() and setsockopt() system calls, which started giving me a better idea of what I need for socket integration. I’ve started to implement unix_network.c, which will implement the AF_UNIX (AF_LOCAL) domain. It looks like most of the code for the socket interface will be in network.c, with callbacks to the individual domain handlers where the semantics differ between domains. One of the interesting parts of the evolving design is that support for the various domain handlers can be specified at link time and eventually will be available as loadable modules.

Now I have much of the socket infrastructure done. I can create a socket file and open it, and use the socket() and socketpair() system calls. setsocketopt() and getsocketopt() are implemented and can be used to manipulate information in a generic socket structure. Although socket files exist in the normal virtual file system namespace, I had to add support for vnodes that don’t live in the normal space for non-file sockets. All socket operations go through a vnode however and socket file descriptors and regular file descriptors are indistinguishable. My first little test program looks like this:

[~/ellcc/examples/socket] dev% cat main.c
/* Simple socket tests.                                                                             
 */                                                                                                 
#include <sys/socket.h>                                                                             
#include <sys/stat.h>                                                                               
#include <fcntl.h>                                                                                  
#include <unistd.h>                                                                                 
#include <stdio.h>                                                                                  
#include <stdlib.h>                                                                                 
#include <errno.h>                                                                                  
#include <string.h>                                                                                 
                                                                                                    
int main(int argc, char **argv)                                                                     
{                                                                                                   
  int sv[2];                                                                                        
  int s = socketpair(AF_UNIX, SOCK_STREAM, 0, sv);                                                  
  if (s < 0) {                                                                                      
    printf("socketpair() failed: %s\n", strerror(errno));                                           
    exit(1);                                                                                        
  }

  s = write(sv[0], "hello world\n", sizeof( "hello world\n"));
  if (s < 0) {
    printf("write() failed: %s\n", strerror(errno));
  }
  char buffer[100];
  s = read(sv[1], buffer, 1);
  if (s < 0) {
    printf("read() failed: %s\n", strerror(errno));
  }

  s = mknod("/socket", S_IFSOCK|S_IRWXU, 0);
  if (s < 0) {
    printf("mknod() failed: %s\n", strerror(errno));
  }

  int fd = open("/socket", O_RDWR);
  if (fd < 0) {
    printf("open() failed: %s\n", strerror(errno));
  }
  s = read(fd, buffer, 1);
  if (s < 0) {
    printf("read() failed: %s\n", strerror(errno));
  }
}

Here is the result of running the program:

[~/ellcc/examples/socket] dev% make run
Preprocessing elkconfig.cfg
Compiling main.c
Linking socket
Running socket
enter 'control-A x' to exit QEMU
audio: Could not init `oss' audio driver
write() failed: Protocol not supported
read() failed: Protocol not supported
read() failed: Protocol not supported

Not bad for a day's work. The errors on the read() and write() calls are expected because I haven't yet implement the read and write buffers for AF_UNIX sockets, but the fact that the error returned is EPROTONOSUPPORT shows that the socket infrastructure is working as it's supposed to.

I've taken a little break to think about how I'd like to implement socket buffers. I think I'd like a design that

  • Allocates buffers a page (usually 4K) at a time.
  • Is coded to be shared between the different socket domains.
  • Expand and contract as needed.
  • Is as simple as possible.

I'm thinking that one approach would be to use two arrays of page pointers, each empty initially. The empty arrays would reside in the socket structure and be limited in size by a kernel compile time constant, maybe 64 entries each. This would allow a maximum 262,144 bytes for each of the buffers given 4K pages. The size would be controlled by the send and receive buffer size socket options, so sockets could be configured to use less memory in a memory constrained system.

It's been a busy day. I've implemented the socketpair() and bind() for AF_UNIX sockets. The buffering scheme seems to be working well, but I have to thing a bit more about how and when the buffer size can be reduced. I'm currently implementing listen() so I can move on to connect() and accept(). The nice thing about concentrating on AF_UNIX sockets first is that it is giving me a good feel for what I'll need to implement AF_INET using the LwIP stack.

It turns out that listen() in interesting. It is supposed to set up a backlog queue of pending connections, but what should that look like? I can see what it might look like for AF_UNIX sockets, but it is unclear what it should look like for remote connections. I guess my plan of implementing AF_UNIX first needs a slight diversion: I'm going to switch back to LwIP and see what a connection queue looks like there to try to come up with a common solution.

It turns out that interfacing LwIP with the current interface is pretty easy. I've had to make one change to the LwIP sources so far. I had to make the type of the socket member of the netconn structure definable at compile time. I needed this because sockets need to be represented by their socket structure pointer, not by a simple integer socket descriptor since socket file descriptors share the same descriptor namespace in different processes. I changed the declaration of the socket member in lwip/api.h to

#if LWIP_SOCKET
  LWIP_SOCKET_TYPE(socket);
#endif /* LWIP_SOCKET */

and added this definition in lwip/opt.h:

#ifndef LWIP_SOCKET_TYPE
#define LWIP_SOCKET_TYPE(name)          int name
#endif

In my lwipopts.h file I overrode the definition with

#define LWIP_SOCKET_TYPE(name) struct { int name; void *priv; }

This anonymous structure replaces the previous definition of "int socket;" with both an int and a pointer. I use the pointer to keep the higher level socket pointer for lwip_interface.c.

I've finished the first phase of LwIP integration. A few simple tests work, like in examples/socket/main.c. Next comes more extensive testing. I'm pretty happy with the way both AF_UNIX and AF_INET handling is implemented. It looks like it will be easy to drop in different stacks for these protocols or for other protocols as necessary.

Part 3 of this little saga will be about adding an Ethernet driver, so I can talk to something beyond 127.0.0.1.

Adding Networking Support to ELK: Part 1

The holidays are a great time. A little time away from my day job and I can concentrate a little on bigger ELLCC sub-projects. This holiday, I decided to concentrate on adding networking to ELK, ELLCC’s bare metal run time environment, previously mentioned here and here.

ELLCC is, for the most part, made up of other open source projects. ELLCC (the cross compilation tool chain) leverages the clang/LLVM compiler and for cross compiling C and C++ source code. I decided early on that the ELLCC run time support libraries would all have permissive BSD or BSD-like licensing so I use libc++ and libc++ABI for C++ library support, musl for standard C library support, and compiler-rt for low level processor support.

For those of you unfamiliar with ELK (which is probably all of you), I’ll give a brief synopsis of ELK’s design. The major design goals of ELK are

  • Use the standard run time libraries, compiled for Linux, unchanged in a bare metal environment.
  • Allow fine grained configuration of ELK at link time to support target environments with widely different memory and processor resources.
  • Have BSD or BSD-like licensing so that it can be used with no encumbrances for commercial and non-commercial projects.

The implications of the first goal are interesting. I wanted a fully configured ELK environment to support the POSIX environment that user space programs enjoy in kernel space. In addition, all interactions between the application and the bare metal environment would be through system calls, whether or not an MMU is present or used on the system. I can feel embedded programmers shuddering at the last statement: “What!?! A system call just to write a string to a serial port? What a waste!”. I completely understand, being an old embedded guy myself. But it turns out that there are a couple of good reasons to use the system call approach. The first is that system calls are the place where a context switch will often occur in a multi-threaded environment. Other than in the most bare metal of environments, ELK supports multi-threading and can take advantage of the context saved at the time of the system call to help implement threading. The second reason for using system calls is that modern Linux user space programs try to do system calls as infrequently as possible. For example, POSIX mutexes and semaphores are built on Linux futexes. A futex is a wonderful synchronization mechanism. The only time a system call is needed when taking a mutex, for example, is when the mutex is contested. Finally, using system calls allows ELK to be implemented by implemented system call functionality and you only need to include the system calls that your program needs. I gave a simple example of a system call definition in this post.

At the very lowest level, ELK consists of start-up code that initializes the processor and provides hooks for context switching and system call handling. Here is an example of the ARM start-up code. Above that, ELK consists of several modules, each of which provide system calls related to their functionality. The system call status page gives a snapshot of the system calls currently implemented by ELK, along with the name of the module that the system call has (or will be) implemented in. When I started working on adding networking to ELK, the set of modules supported were

  • thread – thread related system calls and data structures.
  • memman – memory management: brk(), mmap(), etc.
  • time – time related calls: clock_gettime(), nanosleep(), etc.
  • vfs – Virtual File System: File systems, device nodes, etc.
  • vm – Virtual Memory.

Some of the modules have multiple variations that can be selected at link time. For example, memman has a very simple for (supporting malloc() only), and a full blown mmap() supporting version, while a version of vm exists for both MMU and non-MMU systems. Much of the functionality of these modules were derived from the cool but seemingly abandoned Prex project.

Looking back at what I’ve written here so far, I’m guessing more that one of any potential readers are thinking “I thought this post was about adding networking support”. Well, I guess it is about time to get to the point.

I had several options for ELK networking. I could write a network stack myself and spent years debugging it or, like may other components of ELLCC, I could look around for a suitably licensed existing open source alternative. Unlike Prex, I wanted the networking code to show signs of being actively maintained and I wanted to be able to import it and updated with as little change to the source code as possible. I didn’t want to get into the business of doing ongoing maintenance of a one of a kind network stack. I finally settled on LwIP, which I had heard of over the years, but never actually used. LwIP has the right kind of license, and even though the last release was in 2012, it is being actively maintained as evidenced by this recent CERT advisory. In addition LwIP was originally designed for small, resource limited systems and is highly configurable.

LwIP consists of the core functionality, which is a single threaded network stack designed to provide a low level API providing callback functions for network events. In addition, LwIP provides two higher level APIs. The netconn API provides a multi-threaded interface by making the core functionality a thread and communicating with it via messages. Above that, LwIP also provides a Berkeley socket interface API. For ELK, I decided to use the core and netconn functionality and provide my own socket interface API that integrate fully into the existing ELK thread and vfs modules so that file descriptors and vnode interfaces would be consistent.

The first step was to get LwIP to compile within the ELK build framework. That was easy: I got the latest GIT clone and imported it into the ELK source tree, I added the core and netconn sources to ELK’s build rules and provided a couple of configuration headers and glue source files to tie it all together. Fortunately, LwIP has been ported to Linux, and ELK provides a Linux like environment, so even the glue files already existed.

I was very curious how much adding networking would add to the size of an ELK program, so I built an ELK example (http://ellcc.org/viewvc/svn/ellcc/trunk/examples/elk/) both with and without networking linked in. A full blown configuration, without networking, and with this main.c:

/* ELK running as a VM enabled OS.
 */
#include 
#include 

#include "command.h"


int main(int argc, char **argv)
{
#if 0
  // LwIP testing.
  void tcpip_init(void *, void *);
  tcpip_init(0, 0);
#endif
  setprogname("elk");
  printf("%s started. Type \"help\" for a list of commands.\n", getprogname());
  // Enter the kernel command processor.
  do_commands(getprogname());
}

Had a size like this:

[~/ellcc/examples/elk] dev% size elk
   text    data     bss     dec     hex filename
 162696    3364   64240  230300   3839c elk
[~/ellcc/examples/elk] dev%

When I enabled the LwIP initialization, I got

[~/ellcc/examples/elk] dev% size elk
   text    data     bss     dec     hex filename
 367390    4024   68428  439842   6b622 elk
[~/ellcc/examples/elk] dev%

Not bad, considering two things. First, I have just about all the LwIP bells and whistles turned on, and secondly I am compiling with no optimization. Total program size is about 100K smaller with -O3.

The other cool things is that at least at this stage, LwIP is starting with no complaint. I can run the example and see that the networking thread has been started:

[~/ellcc/examples/elk] dev% make run
Running elk
enter 'control-A x' to exit QEMU
audio: Could not init `oss' audio driver
elk started. Type "help" for a list of commands.
elk % ps
Total pages: 8192 (33554432 bytes), Free pages: 8131 (33304576 bytes)
   PID    TID       TADR STATE        PRI NAME       
     0      0 0x800683a0 RUNNING        1 kernel
     0      2 0x8006d150 IDLE           3 [idle0]
     0      3 0x80099000 SLEEPING       1 [kernel]
elk % 

That third thread (TID 3) is the network thread in all its glory. Now to make it do something.

In the next installment of this blog, I’ll describe how the ELK network module handles socket related system calls and interacts with the other ELK modules and the LwIP netconn API.

ELK: Closer to Embedded Linux Without the Linux

In a previous post I gave an update on the development status of ELK, the Embedded Little Kernel. ELK allows you to use the ELLCC tool chain to target bare metal environments. ELK is currently under development, but is available and becoming quite usable for the ARM.

ELK can be configured with a range of functionality, from a very simple “hello world” environment where you take control of everything, to a full MMU enabled virtual memory based system. In all cases, ELK uses the musl C standard library compiled for Linux so ELK can provide a very POSIX-like environment in the bare metal work (i.e. kernel space).

An example of elk in action can be found in the ELLCC source repository in the ELK example directory. You can configure the example to build four configurations:

  • Running from flash with no MMU.
  • Running from flash with virtual memory enabled.
  • Running from RAM with no MMU.
  • Running from RAM with MMU enabled.

The full ELK source code can be found here. Functionality currently supported by ELK:

  • Threading using pthread_create(). Many other thread synchronization functions are available, like POSIX mutexes and semaphores.
  • Virtual file system support, with a RAM, device, and fifo (pipe) file system supported currently.
  • A simple command processor for debugging and system testing.

ELK works by trapping and emulating Linux system calls. The current state of system call support is available on the system call status page.

ELK Status Update

I previously mentioned ELK, an Embedded Little (or Linux) Kernel, that can be used to do bare metal development with ELLCC. The goal of ELK is to use the musl Linux C standard run-time library to provide a POSIX environment on bare metal, i.e. in kernel space. I’ve been focused primarily on the ARM version of ELK as a proof of concept prototype, but I plan to port ELK to all the targets supported by ELLCC.

ELK is able to use the musl library compiled for Linux because it traps the Linux system calls and implements their functionality, or at least enough of their functionality to be useful in a bare metal environment.

I put together a status page that shows the progress I’ve been making on emulating the Linux systems calls in ELK. You can find it here. The source for all of this can be found in the ELLCC source repository. In particular, you can look at the glue that helps makes this work for the ARM, the ARM crt1.S file mentioned on the status page.

Building Lua with ELLCC This Time With a Twist

In a previous post, I used ELLCC to cross build Lua for the ARM running Linux. Subsequently I’ve done a bit of work to make ELLCC more configurable, and also to handle bare metal compilation more easily. I had a little time on my hands tonight so I thought I’d try out the changes with the latest Lua 5.2.3 version.
First, I modified the lua-5.2.3/src/Makefile to add the following around line 27:

# Start of ELLCC definitions.
PLAT= generic
ELLCC= /home/rich/ellcc
ELLCCBIN= $(ELLCC)/bin/
CC= $(ELLCCBIN)ecc
ELLCCPREFIX= $(ELLCCBIN)ecc-
AR= $(ELLCCPREFIX)ar rcu
RANLIB= $(ELLCCPREFIX)ranlib

TARGET= x86_64-linux-eng
MYCFLAGS= -target $(TARGET)
MYLDFLAGS= -target $(TARGET)
# End of ELLCC definitions.

Then I build for my host system, an x86_64 Linux box:

[~/lua-5.2.3/src] dev% make
/home/rich/ellcc/bin/ecc -O2 -Wall -DLUA_COMPAT_ALL  -target x86_64-linux-eng   -c -o lapi.o lapi.c
...
/home/rich/ellcc/bin/ecc -O2 -Wall -DLUA_COMPAT_ALL  -target x86_64-linux-eng   -c -o linit.o linit.c
/home/rich/ellcc/bin/ecc-ar rcu liblua.a lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o lundump.o lvm.o lzio.o lauxlib.o lbaselib.o lbitlib.o lcorolib.o ldblib.o liolib.o lmathlib.o loslib.o lstrlib.o ltablib.o loadlib.o linit.o 
/home/rich/ellcc/bin/ecc-ranlib liblua.a
/home/rich/ellcc/bin/ecc -O2 -Wall -DLUA_COMPAT_ALL  -target x86_64-linux-eng   -c -o lua.o lua.c
/home/rich/ellcc/bin/ecc -o lua  -target x86_64-linux-eng lua.o liblua.a -lm  
/home/rich/ellcc/bin/ecc -O2 -Wall -DLUA_COMPAT_ALL  -target x86_64-linux-eng   -c -o luac.o luac.c
/home/rich/ellcc/bin/ecc -o luac  -target x86_64-linux-eng luac.o liblua.a -lm  
[~/lua-5.2.3/src] dev% ./lua
Lua 5.2.3  Copyright (C) 1994-2013 Lua.org, PUC-Rio
> print ("hello")
hello
> 
[~/lua-5.2.3/src] dev% 

So far so good. How about a cross compile?

[~/lua-5.2.3/src] dev% make clean
rm -f liblua.a lua luac lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o lmem.o lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o ltm.o lundump.o lvm.o lzio.o lauxlib.o lbaselib.o lbitlib.o lcorolib.o ldblib.o liolib.o lmathlib.o loslib.o lstrlib.o ltablib.o loadlib.o linit.o  lua.o luac.o
[~/lua-5.2.3/src] dev% make TARGET=arm-linux-engeabi
/home/rich/ellcc/bin/ecc -O2 -Wall -DLUA_COMPAT_ALL  -target arm-linux-engeabi   -c -o lapi.o lapi.c
...
/home/rich/ellcc/bin/ecc -o lua  -target arm-linux-engeabi lua.o liblua.a -lm  
/home/rich/ellcc/bin/ecc -O2 -Wall -DLUA_COMPAT_ALL  -target arm-linux-engeabi   -c -o luac.o luac.c
/home/rich/ellcc/bin/ecc -o luac  -target arm-linux-engeabi luac.o liblua.a -lm  
[~/lua-5.2.3/src] dev% ~/ellcc/bin/qemu-arm lua
Lua 5.2.3  Copyright (C) 1994-2013 Lua.org, PUC-Rio
> print ("hello")
hello
> 
[~/lua-5.2.3/src] dev% 

Now for a real test. How about a bare metal test on the ARM?

[~/lua-5.2.3/src] dev% rm lua
[~/lua-5.2.3/src] dev% make TARGET=arm-elk-engeabi
/home/rich/ellcc/bin/ecc -o lua  -target arm-elk-engeabi lua.o liblua.a -lm  
[~/lua-5.2.3/src] dev%  ~/ellcc/bin/qemu-system-arm -M vexpress-a9 -m 128M -nographic -kernel lua
audio: Could not init `oss' audio driver
unhandled system call (256) args: 1, 268472376, 1610613215, 1610613023, 1207961673, 1241513744
Lua 5.2.3  Copyright (C) 1994-2013 Lua.org, PUC-Rio
> print ("hello")
unhandled system call (175) args: 1, 1241512616, 0, 8, 237792, 0
unhandled system call (174) args: 2, 1241512644, 1241512624, 8, 237792, 0
hello
unhandled system call (174) args: 2, 1241512644, 1241512624, 8, 237792, 0
> 

As described in the previous post, the unhandled system calls are those that haven’t been implemented in ELK yet. In this case, they are

...
#define __NR_rt_sigaction       174
#define __NR_rt_sigprocmask     175
...
#define __NR_set_tid_address    256
...

none of which are needed in my little test. Bare metal Lua. Luanix?

After I had this little bit of excitement, I remembered that I had configured ELK with the task scheduler and system timer. I figured it might be worth a try to see if at least the interrupt driven timer was working. Sure enough:

> print (os.date())
unhandled system call (174) args: 2, 1241512644, 1241512624, 8, 1207961832, 1241512696
unhandled system call (5) args: 276151, 657408, 0, 1, 1241510728, 1241511520
Thu Jan  1 00:07:22 1970
unhandled system call (174) args: 2, 1241512644, 1241512624, 8, 1207961832, 1241512696
> print (os.date())
unhandled system call (174) args: 2, 1241512644, 1241512624, 8, 1207961832, 1241512696
Thu Jan  1 00:07:45 1970
unhandled system call (174) args: 2, 1241512644, 1241512624, 8, 1207961832, 1241512696
> 

Time keeps on ticking. Fun stuff.

Introducing ELK: A Bare Metal Environment for ELLCC

ELLCC (pronounced “elk”) is a C/C++ programming environment based on the clang/LLVM compiler. The goal of ELLCC is to provide a complete tool chain and run-time environment for developing C/C++ programs for embedded systems. ELLCC supports several Linux targets today, specifically ARM, Mips, PowerPC, and x86 systems. ELK (which might mean “embedded little kernel” or “embedded Linux kernel”) is a work-in-progress that allows the ELLCC tool chain to target bare metal environments where an OS is not available or needed.

What will differentiate ELK from other bare metal environments is that the goal is to provide a fairly complete Linux-like environment without the need for actually running Linux. ELK is in the design and development stage right now, but the basic functionality has been implemented based on work done using ELLCC for bare metal development and making the ELLCC tool chain easily configurable.

The thing that makes ELK fairly unique is that it uses the C and C++ libraries compiled for Linux. It does this by handling Linux system calls using the normal system call mechanism for each target. ELK has extensible system call handling capability so that new system call emulators can be added as needed. ELK is being developed by setting up the infrastructure for program start up in the bare metal environment and handling system calls and context switching in a small assembly language file. A fairly functional example for ARM can be seen here. System call support can be added easily. Here is a simple exit() system call example:

/* Handle the exit system call.
 */     
#include <bits/syscall.h>       // For syscall numbers.
#include <stdio.h>
#include <kernel.h>

// Make the simple console a loadable feature.
FEATURE(exit, exit)

static int sys_exit(int status)
{
    printf("The program has exited.\n");
    for( ;; )
      continue;
}       
        
CONSTRUCTOR()   
{       
    // Set up a simple exit system call.
    __set_syscall(SYS_exit, sys_exit);
}       

Here’s an example of a simple ARM program running on QEMU in system (bare metal) mode:

[~] dev% cat hello.cpp
#include <iostream>

int main()
{
  std::cout << "hello world" << std::endl;
}
[~] dev% ~/ellcc/bin/ecc++ -target arm-elk-engeabi hello.cpp -g
[~] dev% ~/ellcc/bin/qemu-system-arm -M vexpress-a9 -m 128M -nographic -kernel a.out
audio: Could not init `oss' audio driver
unhandled system call (256) args: 1, 268472376, 1610613215, 1610613023, 1207961673, 1241513736
unhandled system call (45) args: 0, 0, 0, 1241512408, 590752, 0
unhandled system call (45) args: 4096, 4111, 1241512408, 1241512336, 592800, 1254352
unhandled system call (192) args: 0, 8192, 3, 34, -1, 0
unhandled system call (45) args: 4096, 4111, 34, 1241512336, 592800, -1
unhandled system call (192) args: 0, 8192, 3, 34, -1, 0
hello world
unhandled system call (248) args: 0, 1207962904, 1309668, 0, 1207991180, 1241513736
The program has exited.

Notice that there are several unhandled system calls (I did say that ELK is a work-in-progress) but enough has been implemented that “hello world” comes out.
The C version is a little quieter:

[~] dev% ~/ellcc/bin/qemu-system-arm -M vexpress-a9 -m 128M -nographic -kernel a.out
audio: Could not init `oss' audio driver
unhandled system call (256) args: 1, 268472376, 1610613215, 1610613023, 1207961673, 1241513736
hello world
unhandled system call (248) args: 0, 0, 1207983756, 0, 1207985256, 1241513736
The program has exited.

The current state of ELK is that only the ARM version is at all functional. It supports multiple threads, memory allocation using malloc, semaphores, and timers. ELK started out as a couple of prototypes to test the feasibility of using Linux libraries on bare metal and to enhance the ability to configure the tool chain for multiple environments. I like the way that the development is going so far and hope to have a complete ARM implementation soon and support for the other targets soon after that. You can browse the complete source code for ELK.