<?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 Emmanuel Bashorun on Medium]]></title>
        <description><![CDATA[Stories by Emmanuel Bashorun on Medium]]></description>
        <link>https://medium.com/@emmanuelbashorun?source=rss-c47a970db78d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3Wth2vxDTGUGvXf-.</url>
            <title>Stories by Emmanuel Bashorun on Medium</title>
            <link>https://medium.com/@emmanuelbashorun?source=rss-c47a970db78d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:45:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emmanuelbashorun/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[Lifecycle of a Packet Through the Linux Kernel]]></title>
            <link>https://emmanuelbashorun.medium.com/lifecycle-of-a-packet-through-the-linux-kernel-51301793df5d?source=rss-c47a970db78d------2</link>
            <guid isPermaLink="false">https://medium.com/p/51301793df5d</guid>
            <dc:creator><![CDATA[Emmanuel Bashorun]]></dc:creator>
            <pubDate>Wed, 10 Dec 2025 00:48:41 GMT</pubDate>
            <atom:updated>2025-12-18T00:07:23.208Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is a high level intro to the networking stack of the Linux kernel</em>.</p><p>In Linux, a packet can be passed to a socket through a userspace application, daemon, kernel space programs or received from the transport layer.</p><p>This article is an attempt to better understand the paper [1] supplemented by code that shows actual function calls (userspace, system calls, kernelspace) from the userspace through the network interface card (to be referenced as <strong>NIC</strong> onwards) and vice-versa.</p><p><strong>Software prerequisites<br></strong>The program to illustrate packet movement was written on an M1 Mac but the same can easily be done on a Linux machine. To wield introspective capability into the kernel, we make use of eBPF and its associated tooling in BCC that makes it easy to write eBPF programs with a Python frontend.</p><p>To set up on a Linux machine, just clone the <a href="https://github.com/brieflatency/eBPF-programs">repository</a>, navigate to packet-tracer and execute the commands in sudo mode.</p><p>On a Mac, you need to virtualize your hardware to access eBPF commands and Linux kernel headers. My choice for this is Colima which uses Lima under the hood (so it’s still QEMU running). The readme in the repository details how to setup Colima and the demo program on a Mac.</p><p><strong>sk_buff</strong></p><p>The origin of a packet either starts from the network interface card or by an application writing to a socket which involves several steps that includes the very important step to create sk_buff.<br>sk_buff is a C struct with fields as pointers (better memory management since pointers don’t require extra memory when referenced at different memory locations, efficient packet modification etc [1]) that tracks the metadata of a packet through the kernel. For egress paths, sk_buff is created right after a TCP connection is established and is written to the socket queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*zfKjZ3j1YX6iYc10i0EjNQ.png" /><figcaption>Figure 1. Structure of two sk_buff structs pointing to the same packet [1]</figcaption></figure><p><strong>Packet Traversal<br>1. Egress Path</strong>: In egress connections, the path of the packet starts right from userspace and ends up at the NIC. This path involves steps that cuts through the stack of the OSI model by starting at the application layer and ending at the datalink/physical layer as frames sent out to the network (external or internal) with sk_buff at the center of it all.</p><ul><li><strong>Socket layer</strong>: First off, in Linux everything is a file. It’s a core philosophy that governs the data management of everything in Linux (including sockets, hardware devices &amp; peripherals). This layer starts with the instantiation of the system call [2] <strong>write(</strong><em>fd</em><strong><em>, </em></strong><em>buf</em><strong><em>, </em></strong><em>len</em><strong>) </strong>or<strong> </strong><strong>sendto(</strong><em>sockfd</em><strong>, </strong><em>buf</em><strong>, </strong><em>len</em><strong>, </strong><em>flags</em><strong>, </strong><em>dest_addr</em><strong>, </strong><em>addrlen</em><strong>)</strong>.<br>For stream oriented sockets like TCP,<strong> </strong><strong>write() </strong>is usually called which invokes <strong>sock_sendmsg() </strong>(<strong>sendto</strong> works the same way as <strong>write</strong> when <em>flags</em> is set to zero [3]).<br>In Linux, sockets are files (as earlier said) referenced by a file descriptor which is basically an integer that points to a set of data structures describing the metadata of a file. <strong>sock_sendmsg() </strong>requires this file descriptor so it can figure out the location of the socket to route the data needed to build the packet. Depending on the transport mechanism determined by sk_prot field in sk_buff <strong>sock_sendmsg()</strong>calls the appropriate transport layer which could be either <strong>TCP</strong> or <strong>UDP</strong>. In this case it calls the TCP handler determined by <strong>inet_sendmsg()</strong> function.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*UpLwwGQtqOf7VGFzRb8Iow.png" /><figcaption>Figure 2. sendto is equivalent to send [3]</figcaption></figure><ul><li><strong>Transport Layer (TCP)</strong>: The flow in the layer is triggered by <strong>tcp_sendmsg()</strong> which in turn invokes several helper functions. We are going to touch on a couple of these functions as we explore this layer.<br>In the OSI model, this is where TCP/UDP comes into play. As we might all know, establishing a TCP connection is a 3-way handshake. Upon the completion of this handshake, sk_buff is created by allocating segments (basic unit of data in the transport layer) from the userspace or page cache (referenced by the data pointer of sk_buff) and stored in the kernel memory pool whilst ensuring that the Maximum Segment Size (MSS) isn’t exceeded. It also enqueues sk_buff to socket_write queue implemented as a doubly linked list. While we know the asymptotic advantages of a linked list, the practical decision to use such data structure is that the TCP output engine knows when to continue reading sk_buff struct from the queue that’s to be sent down the networking stack. If the head sk_send_head(keeps track of sent packets) is NULL then we know there’s no more data to read [4].<br>Asides MSS, there are more restrictions and validations carried out by <strong>tcp_write_xmit()</strong>. For instance, the minimum value between the congestion window (cwnd, how much data can be sent by the sender) and receiver’s advertised window [7] (how much data the receiver can receive) is used to determine the rate at which data should be sent as ACK packets arrive from the receiver and the cwnd of the sending machine increases. When a packet is sent and an ACK isn’t received it also persists the packet within the queue for retransmission.<br>Before the packet is sent, the kernel ensures that transport and network headers are appropriately set at the beginning of sk_buff. Transport headers helps with interprocess communication allowing the kernel to properly route packet to the destination port on a process (port 80, 443 etc). Network headers help with determining inter host communication by assigning IP addresses of the packet’s destination to its corresponding section of the packet.<br>The packet is eventually handed over to <strong>tcp_transmit_skb(). </strong>This function regardless of the packet source handles reading the write queue and transmitting it to the network layer.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*Q03AmSkiItEHUIVf9f4PMQ.png" /><figcaption>Figure 3. tcp_transmit_skb called right after tcp_write_xmit</figcaption></figure><p>Also don’t forget that TCP needs to store the packet in case of congestion issues for retransmission. It does this by creating a clone of sk_buff into skb_clone (inexpensive because sk_buff is a pointer to the actual packet’s memory location).</p><ul><li><strong>Transport layer (UDP)</strong>: In our demo program, we can observe the path of a UDP packet through requests to the DNS registry by simply executing a curl command. <strong>udp_sendmsg() </strong>is instantiated by <strong>inet_sendmsg() </strong>similar to how its done in TCP.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*1r57l7U5wEgo8Nf6_puDuA.png" /><figcaption>Figure 4. UDP path way of a packet before entering the</figcaption></figure><ul><li><strong>Network Layer</strong>: This layer handles IP routing and things like ICMP requests but we’d focus on IP routing. <br>In this layer, the kernel attempts to forward the request down the stack. <strong>ip_queue_xmit()</strong> is the first function call used to determine the packets destination. The mechanism to determine the route involves multiple steps depending on if the location is found in the first step. The first step involves <strong>ip_queue_xmit() </strong>checking if skb-&gt;skb_refdst is set, if it is, it generates the header. If it isn’t, a call is made to the socket address to see the destination of previously sent packets. If this prove unfruitful, the kernel makes a request to the routing cache through a process called Forward Information Base (FIB) [1]. If this still proves unsuccessful, it returns <em>host unreachable.<br></em>If successful, the next stage involves setting the IP options to sk_buff headers and also triggering Linux’s firewall mechanism [1].<br><strong>ip_output()</strong> is the last phase of the network layer before its sent to the data link layer for transmission. It does validations that ensures that the packet size is within the limits of the Maximum Transmission Unit (MTU), fragments the packet and builds the IP header of the new packets of the original exceeds the MTU size.</li><li><strong>Ethernet Layer</strong>: As we drill down the stack, <strong>__dev_queue_xmit() </strong>function is responsible for setting the MAC address in the in the Ethernet header field of sk_buff. It’s also responsible for queuing packets (sk_buff) in the queueing discipline [5]qdisc which determines the ordering of the packets and how they are sent to the TX ring using the NIC driver before scheduling into the NIC for transmission to the wire. When the TX ring buffer of the NIC is filled up, the kernel stops scheduling packets.<br>TX ring doesn’t actually contain the packets, rather it contains descriptors (physical memory location) of sk_buff in the RAM.<br>Modern computer architecture allows hardware subsystems (think NIC or other peripheral devices) to directly access the RAM by reducing the CPU’s workload through a process called Direct Memory Access (DMA). We already know that the slowest subsystem [6] (think speed bottleneck in CPU registers v. CPU cache; SRAM v. DRAM) of an entity impacts the overall speed and its inefficient to always have the CPU block when it needs to write data thereby wasting precious CPU cycles. The CPU issues the instruction to move data from RAM to the NIC but since actually writing the data to the card costs more CPU cycles, the instruction/memory location of the packet is added to the TX ring for the DMA to actually perform the task of moving data to the NIC.</li></ul><p><em>Note the distinction between issuing an instruction by the CPU and moving the data to the NIC.</em></p><p>2. <strong>Ingress Path: </strong>This section entails the path of a packet starting from the <strong>NIC</strong> to the socket layer where it’s consumed by an application process reading from a socket connection.</p><ul><li><strong>Ethernet Layer</strong>: The NIC hardware examines the Destination MAC Address in the Ethernet header and compares it to its own MAC address, broadcast addresses, and registered multicast addresses. After verification and the transfer of data from the NIC buffer to system RAM buffer the DMA raises an interrupt to the CPU to notify it that it can continue the sequence of processing the packet by allocation sk_buff and assigning metadata to it. <strong>ip_rcv()</strong>function is called at the end of this layer and hands over control to the IP/network layer.<br>NB: You can run the program in ingress.py to observe the stack trace.</li><li><strong>IP Layer</strong>: <strong>ip_rcv()</strong> is the entry point to this layer. It performs IP related verification, verifies the MAC address and discard ones that are outside the scope of concern of this layer. One of the most important functions of this layer is determining where the destination of a packet. This happens by calling dst_input() which in turn calls one of the three following functions:<br>- <strong>ip_forward()</strong>: This is called when a packet destination isn’t intended for the local machine.<br>- <strong>ip_local_deliver()</strong>: This is called when the intended destination is the current machine. The packet if forwarded up the stack [1]<br>- <strong>ip_mr_input()</strong>: This function is intended for packets with multiple destination addresses.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d-QZXVznmDN6fc28OlUayA.png" /><figcaption>Figure 5. Ingress stack trace for IP layer</figcaption></figure><p><strong>ip_local_deliver() </strong>is called at the end of the IP layer and sends the packet to the TCP/UDP layer. Just as we learnt in the egress section, the kernel is able to route the pack to either TCP/UDP depending on specification in sk_buff.</p><ul><li><strong>Transport Layer (TCP)</strong>: <strong>tcp_rcv_v4() </strong>is the entry point of the transport layer. As with other layers, the transport header is also validated to ensure data hasn’t been tampered with. <strong>inet_lookup_skb()</strong> is invoked in other to forward the packet to the intended socket. <br>When a packet is being processed during the 3-way handshake there are two important states <strong>TCP_NEW_SYN_RECV</strong> and <strong>TCP_TIME_WAIT.</strong> A packet arrives with the <strong>SYN flag</strong> set, indicating a client wants to start a new TCP connection. The kernel doesn’t yet establish the connection until it performs validations (through <strong>tcp_filter()</strong>)that ensure there is enough resources to service the connection and then sends a <strong>SYN/ACK</strong> response for an <strong>ACK</strong> from the sender. After a <strong>FIN/ACK</strong> that closes a TCP connection usually from the server, the client might send more packets thinking there’s still a valid connection. <strong>TCP_TIME_WAIT </strong>prevents incoming packets from this connection (even though it has been closed) from corrupting data on a new connection instance. When a TCP connection is established between to machines, <strong>TCP_ESTABLISHED </strong>becomes the current state which is the end state of the slow path that marks the beginning of the data transfer in the fast path between two machines. During the process leading to this state (<strong>TCP_ESTABLISHED)</strong>, the kernel performs validations and more security checks. <strong>tcp_rcv_v4()</strong>calls <strong>tcp_rcv_established()</strong>, which processes packets in both slow and fast path (in contrast to the slow path, the fast path occurs when connection has been established thereby skipping a lot of validations). The end of this layer involves enqueueing the packet to the socket queue for the socket layer to read [1].</li><li><strong>Socket Layer</strong>: This stage involves dequeuing the packet from the socket queue by first invoking <strong>read() </strong>which then calls<strong> </strong><strong>sys_recv()</strong>. The socket where the packet was written to in the TCP layer is determined by<strong>sys_recvfrom() </strong>and <strong>sock_recvmsg() </strong>is subsequently called to read the data from the socket. <strong>inet_recvmsg()</strong> calls the respective tcp/udp rcv_msg function to dequeue the packet, write to the userspace buffer for the application to read and eventually frees up sk_buff from memory.</li></ul><h3><strong>Conclusion</strong></h3><p>Since we will always want faster networks for improved user experience, the need to asymptotically push bandwidth bottleneck to 0 will remain ever present.<br>To achieve this, we’d to know where to look at. By knowing at point in the stack to perform checksum calculations; techniques to reduce memory footprint like pointers and page caching; qdisc optimization for <strong>NIC </strong>packet scheduling; TX ring buffer size fine tuning etc provides us with the technical prerequisites to think up solutions and quickly find bugs down to the kernel layer.<br>This also forms the knowledge basis for network engineers to figure out ways to improve packet routing in software defined networks which is very core to inter GPU communication in AI hyperscalers (supporting connections of up to 10TB/s).</p><p>Hopefully, this article has been able to serve as a companion in understanding some of the concepts discussed in [1]. In a future article on computer networks, we’d discuss the specification of TCP and its implementation in modern Linux kernel.</p><p><strong>NB: I know nothing. If you notice any inaccuracy or misleading information, please drop a comment and I will quickly rectify with credits.</strong></p><p><strong>References</strong></p><ol><li>Alexander Stephan, Lars Wüstrich, “The Path of a Packet Through the Linux Kernel,” <em>in Seminar IITM</em>, 2024, 89–93. Available: <a href="https://www.net.in.tum.de/fileadmin/TUM/NET/NET-2024-04-1/NET-2024-04-1_16.pdf">https://www.net.in.tum.de/fileadmin/TUM/NET/NET-2024-04-1/NET-2024-04-1_16.pdf</a></li><li>Michael Kerrisk, “Linux Programming Interface”.</li><li>sendto(2) — Linux man page. <a href="https://linux.die.net/man/2/sendto">https://linux.die.net/man/2/sendto</a></li><li>The Linux Kernel Archives, “How the TCP Output Engine Works”. <a href="http://oldvger.kernel.org/~davem/tcp_output.html">http://oldvger.kernel.org/~davem/tcp_output.html</a></li><li>Red Hat, “Linux Traffic Control”. <a href="https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/8/html/configuring_and_managing_networking/linux-traffic-control_configuring-and-managing-networking">https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/8/html/configuring_and_managing_networking/linux-traffic-control_configuring-and-managing-networking</a></li><li>Ulrich Drepper, “What Every Programmer Should Know About Memory”, <em>Red Hat Inc</em>, 2007. Available: <a href="https://people.freebsd.org/~lstewart/articles/cpumemory.pdf">https://people.freebsd.org/~lstewart/articles/cpumemory.pdf</a></li><li>Helali Bhuiyan, Mark McGinley, Tao Li, Malathi Veeraraghavan, “TCP Implementation in Linux: A Brief Tutorial”, <em>University of Virginia. </em>Available:</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51301793df5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding systemd]]></title>
            <link>https://emmanuelbashorun.medium.com/understanding-systemd-ad06aeca4fd0?source=rss-c47a970db78d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad06aeca4fd0</guid>
            <category><![CDATA[systemd]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Emmanuel Bashorun]]></dc:creator>
            <pubDate>Sat, 27 Feb 2021 13:59:39 GMT</pubDate>
            <atom:updated>2021-02-27T13:59:39.835Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Prerequisites<br>1. Familiarity with basic Linux commands.<br>2. An understanding of Linux processes, daemons and cgroups.</p><p>The official website describes systemd (spelled with a small ‘s’) as a suite of tools that forms the basic building block for a Linux system. systemd handles the boot process for Linux systems. As an init implementation, it has a PID of 1 like other init systems e.g System V, Upstart.</p><h3>What’s init?</h3><p>Before we delve further, let’s talk more about what exactly init is. An init program is usually the first to start and the last to stop.<br>It initializes and terminates programs and services crucial to the operation of Linux systems.</p><p>It’s also a <a href="https://man7.org/linux/man-pages/man7/daemon.7.html">daemon</a> process that runs during the entire lifetime of all programs in the system.</p><p>It’s an ancestor process to all processes. It also adopts orphaned or zombie processes. That is, after a child loses its parent, the init process becomes its new parent.</p><p>Now, what happens when the init process doesn’t start first (the kernel doesn’t boot the init process)? A kernel panic occurs because there isn’t an init process to startup things and make way for essential services.</p><h3>Implementations of init</h3><p>There are some init implementations that usually differ by the scope of their responsibility.<br>systemd for instance is a very functional software. Some might argue that systemd’s functionality is outside the scope of what an init system should do. <br>It does more than starting daemons and services, mounting filesystems, configuring network interfaces.</p><ol><li>System V init: This is the traditional init system (also pronounced as “sys five”). It consists of several scripts that start various services expected to run on a runlevel. In System V, the state of a Linux machine at any particular stage points to a <a href="https://developer.ibm.com/technologies/linux/tutorials/l-lpic1-101-3/">runlevel</a>. The runlevel stages span from 0 to 6. <br>They help differentiate between startup, shutdown, single-user mode, console mode states. System V init has a lot of deficiencies that make startup time slower. Since shell scripts execute line-by-line, system execution isn’t parallelized.<br>If there is an error with a script’s execution, it would have to time-out before the next script in line gets executed. System V init rigidity limits its ability to manage many dependencies. This is because one script waits for the complete execution of the previous one.</li><li>Upstart: Ubuntu’s implementation of the init system. It solves the problems associated with System V.<br>Rather than execute scripts during a runlevel, upstart manages the system state by reacting to events.<br>An event occurs when a hot-plug device is connected/removed from the machine. Upstart initializes the required dependencies and services for this event change.</li><li>systemd: Current standard for implementing init systems in modern Linux machines. It’s also the focus of this article.</li></ol><h3>Why systemd?</h3><p>systemd is capable of starting services in parallel which speeds up the boot process. It is also capable of handling hot-plug devices; such as starting up services on demand at the occurrence of an event (like upstart). The process of managing service daemons in System V is a little bit involved. This is so because scripts get detached from the daemons they spawn upon runtime. Some daemons spawn 3rd party processes that get orphaned and re-parented by PID 1. Some processes even re-fork and rename themselves which makes process management difficult.</p><p>systemd makes daemon/service management easier by placing their processes in a control group (cgroup).</p><p>Here, spawned processes are made members of their parent cgroup (named after the service). These processes are not capable of leaving their cgroup until their parent terminates them. This prevents the creation of zombie processes. It also eases the management (running kill -9 as an example) of related processes since they belong to one cgroup.</p><p>systemd also provides a tool called <em>systemctl</em>. <em>man 1 systemctl </em>says <em>systemctl</em> may be used to introspect and control the state of the <em>systemd</em> system and service manager.</p><p>This tool can be used to start and stop services including other things as we will soon see. System V init implementations manage system state by the use of shell scripts. <br>systemd on the flip-side takes a different approach towards writing configuration files. It does this by expressing commands in a declarative format. This makes the job of administering Linux systems easier by making uniform all aspects of system administration.</p><p><a href="https://www.amazon.com/UNIX-Linux-System-Administration-Handbook/dp/0134277554">ULSAH </a>gives a succinct description on systemd’s mode of operation:</p><blockquote>Much like a package management system, systemd defines a robust dependency model, not only among services but also among “targets,” systemd’s term for the operational modes that traditional init calls runlevels. systemd not only manages processes in parallel, but also manages network connections (networkd), kernel log entries (journald), and logins (logind).</blockquote><p>systemd is also compatible with existing init scripts of System V.</p><h3>systemd deep-dive</h3><p>During boot time systemd loads its configuration, determines its boot goal and dependences. It then activates them afterward.</p><p>systemd also doesn’t follow a sequential pattern for starting services. Rather, a flexible process by which extra components activate when system events occur.</p><p>The systemd Linux manual states that systemd provides a dependency system between various entities called “units”.<br>Units encapsulate various objects that are relevant for system boot-up and maintenance.</p><blockquote>A <strong>unit type</strong> is a type of <strong>task that’s relevant</strong> to the management of a Linux system. A task is a unit in systemd parlance. These units are a standardized representation of system resources managed by the suite of systemd daemons.</blockquote><p>There are default unit files supplied by the packages of the service that usually reside in <strong><em>/lib/systemd/system/</em></strong>. These files are vendor-written and can be overwritten by the package maintainer in the event of a package update. User-specific configurations for units are usually made in <strong><em>/etc/systemd/system/</em></strong> because the unit files in this location won’t be overwritten in the event of a package upgrade.</p><p>Note: It’s common practice to copy the default unit file into <strong><em>/etc/systemd/system/</em></strong> and make appropriate customization.</p><p>There are 11 types of units in systemd. We’d talk about the most common ones. <strong><em>man 1 systemd</em></strong> describes them. So give it a check.</p><ol><li>Service units: This unit defines how to manage service daemons controlled by systemd. Unit files of this service end with .service.</li><li>Socket units: This contains information about local inter-process communication or network sockets in a Linux system.</li><li>Target units: This is used to provide synchronization amongst unit files during boot-up. It can also be used as a medium to extend scope by specifying their targets to other targets.</li><li>Device units: This unit describes devices that need exposure to systemd by udev and sysfs filesystem.</li><li>Mount units: This defines a mount point for attaching filesystems controlled by systemd.</li><li>Automount units: This provides automount capabilities.</li><li>Timer units: This unit (synonymous with cron) defines a timer controlled by systemd. It schedules the activation of other units.</li><li>Swap units: This unit describes a memory swap partition.</li><li>Path units: This can define a path that activates other services when files within the path are modified.</li><li>Slice units: Now this is a special unit. It’s used in conjunction with cgroups to group processes, daemons, services into one hierarchical tree for the management of resources.</li><li>Scope units: This manages externally created processes. See <strong><em>man 5 systemd.scope</em></strong>.</li></ol><p><strong>How systemd manages dependencies</strong></p><p>Earlier on, we talked about systemd starting up services required to hit a default boot goal during boot time. Imagine this default boot goal to be a node at the top of a tree. So when a target is activated, all other targets below it (dependencies) are also activated.</p><p>A visual cue could be of help here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*K6Vd-V6PDW37ZyZ_CRK3nw.png" /><figcaption>Figure 1. Dependency tree</figcaption></figure><p>So it turns out that dependency management is difficult in modern Linux machines. These machines have many services that depend on each other. One service failure can solely freeze the boot process of a Linux machine.</p><p>Imagine defining a dependency from an X server to a logging service. That is, the logging service would have to start before the X server. In a situation where the logging service doesn’t start, we’d be unable to get our X server running because one of its dependencies isn’t running.</p><p>System V init implementations don’t have dependency management issues because things are kept simple at the expense of flexibility.<br>systemd developers devised a method for handling dependencies in such a way that the failure of one dependency doesn’t put the entire system in limbo.</p><p>There is a handful of dependency types that gives systemd the ability to flexibly manage dependencies. These “dependency types” are regarded as directives in unit files and are found with the Unit section of the unit:</p><p>- <strong>Requires</strong>: A unit file with a ‘Requires’ dependency means units within this directive must be successfully activated when an activation signal is else the current unit will fail. Dependencies with this directive are strict.</p><p>- <strong>Wants</strong>: This is a less strict version of Requires. The Wants dependencies are activated upon activation of the containing unit file. This unit will be activated regardless of if the Wants dependencies fail.</p><p>- <strong>Conflicts</strong>: Units outlined within this dependency are automatically stopped upon activation of the containing unit file.</p><p>- <strong>Requisite</strong>: Units within this dependency must already active before the unit is activated else systemd fails on the activation of the unit with the dependency.</p><p>- <strong>Before</strong>: This dependency directive explicitly declares ordering. This is important in situations when you’d want to start a unit before another. For this instance, the current unit is activated before the unit under the Before directive.</p><p>- <strong>After</strong>: This dependency is also used for ordering dependency activation. It’s the opposite of Before. The unit under this directive is/are activated before activation of the current unit.</p><p>- <strong>Conditional Dependencies</strong>: This is used to evaluate a truthy or falsy value of units with it. The current unit won’t be activated if the conditional directive evaluates to false.</p><h3>syntax of unit files</h3><p>So now, we have an idea of how systemd manages dependencies. But that isn’t all of it. We’d talk more about them as we attempt to understand the syntax and structure of unit files.</p><p>A unit file is divided into multiple parts know as Sections. A section has its name enclosed in square brackets ([]). Within a section are declarations of variables and their assignments to values.</p><p>Variables specified within sections are known as Directives.</p><p>NB: <em>howlinuxworks</em> notes that unit files are derived from the XDG Desktop Entry Specification (for .desktop files, which are very similar to .ini files on Microsoft systems)</p><h3>Service Section</h3><p>The service section contains configurations applicable only to .service unit files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*cNwsiYUGGo_HFJzHGYfyKQ.png" /><figcaption>Figure 2: An example of a unit file (.service) with Sections and Directives</figcaption></figure><p>Figure 2 contains three directives — [Unit], [Service] and [Install] with their respective directives.</p><p>Let’s talk a bit about the directives of the Service section</p><ol><li><strong>Type</strong>: This defines services by their process and daemonizing behavior.</li><li><strong>ExecStart</strong>: This directive set the path and arguments of the executable command for the unit.</li><li><strong>ExecStartPre</strong>: This specifies an additional command that executes before ExecStart.</li><li><strong>ExecStartPost</strong>: This configures the path to commands that will be executed after ExecStart.</li><li><strong>ExecReload</strong>: This defines a command to reload the service file.</li><li>Restart: systemd restarts the service when this point is reached. In the example above, the service is restarted on failure.</li><li><strong>TimeoutSec</strong>: This directive sets the value systemd waits when stopping a service before marking it as failed or killing it.</li></ol><h3>Unit section</h3><ul><li><strong>Description</strong>: This directive is used to describe the function of the unit.</li><li><strong>Documentation</strong>: This provides information on how the unit’s documentation can be accessed. The documentation can be accessed via URLs or man pages.</li></ul><p>We talked about the remaining directives of the Unit section above. You can also recall that they’re used to manage dependencies.</p><h3>Install section</h3><p>This section can be used to manage dependencies too. It is used to define the behavior of a unit when enabled or disabled without modifying any configuration file. There are two directives commonly used within this section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*6CXhHlVf3NLBQNXIoSXaSg.png" /><figcaption>Figure 3. symbolic link of ssh.service</figcaption></figure><ol><li><strong>WantedBy</strong>: Figure 2 above has a WantedBy dependency in its install section. systemd usually ignores this section during its normal operation. systemd processes this section when it is enabled. The WantedBy dependency establishes a relationship between the current unit and the dependency unit without modifying the dependency unit (just like the Wants dependency of the unit section). Using our example, when systemd parses the WantedBy dependency, a symbolic link of the current unit (ssh.service in our case) is automatically within a folder in <strong>/etc/systemd/system/</strong>. This folder is named as the WantedBy dependency with .wants appended to the end. The folder name, in this case, would be multi-user.target.wants. We can see the ssh.service symbolic link pointing to the target — <strong>/lib/systemd/system/ssh.service</strong> (vendor written unit files are kept in <strong>/lib/systemd/system/</strong>).<br>ssh.service unit would be enabled before the units grouped in multi-user.target. One doesn’t need to write a Wants dependency requiring ssh.service in all the unit files of multi-user.target. This method keeps multi-user.target clean from any form of edit because they might be overwritten in the future during an upgrade but the WantedBy dependency in ssh.service will keep the relationship.</li><li><strong>RequiredBy</strong>: This directive is similar to WantedBy but will cause the activation to fail is not met.</li><li><strong>Alias</strong>: Units can assume names defined by this directive.</li></ol><h3>Mount section</h3><p>systemd uses mount units for mount point management. This section type comes with several directives. This functionality is defined using the mount section directive.</p><ol><li><strong>What</strong>: This directive defines the UUID of the device to be mounted.</li><li><strong>Where</strong>: This defines the UUID or absolute path of where the device should be mounted.</li><li><strong>Type</strong>: Type of filesystem to mount</li><li><strong>Options</strong>: This defines another mount option as a comma-separated list.</li></ol><p>The Linux man page for systemd describe other unit types in detail: <strong><em>man 5 systemd.socket</em></strong>, <strong><em>man 5 systemd.automount</em></strong>, <strong><em>man 5 systemd.device</em></strong>.</p><h3>systemctl</h3><p><strong><em>man 5 systemctl</em></strong> describes systemctl as a tool that may be used to introspect and control the state of the “systemd” system and service manager. This is the tool used in interacting with systemd. Things like service activation, deactivation, enabling, disabling, reloading, dependencies listing etc are executed using <strong><em>systemctl</em></strong>.</p><p>In conjunction with its many flags, Linux machines can be flexibly managed. It’s also very helpful when debugging certain services that don’t function due to dependency malfunctions.</p><ul><li><strong><em>systemctl status [unit]</em></strong>: shows the status of unit.</li><li><strong><em>sudo systemctl stop [unit]</em></strong>: deactivates a unit.</li><li><strong><em>sudo systemctl start [unit]</em></strong>: activates a unit.</li><li><strong><em>sudo systemctl disable [unit]</em></strong>: removes the symbolic link if it has an install section.</li><li><strong><em>sudo systemctl enable [unit]</em></strong>: creates a symbolic link and it should be run before activating activating a unit else won’t run the systemd the install section.</li><li><strong><em>systemctl list-units</em></strong>: lists all active units.</li><li><strong><em>sudo systemctl reload [unit]</em></strong>: reloads a particular unit when there’s an edit in its configuration file.</li><li><strong><em>sudo systemctl restarts [unit]</em></strong>: restart the unit by stopping and starting the unit. This method causes more disruption of service unlike ‘<strong><em>systemctl reload [unit]</em></strong>’ that only reloads the configuration file.</li><li><strong><em>sudo systemctl daemon-reload</em></strong>: reloads all unit configuration files.</li></ul><p>Check <strong><em>man 5 systemctl</em></strong> to see more commands systemctl provides.</p><h3>Editing unit files using Drop-ins</h3><p>We previously discussed that systemd units can be edited directly from <strong><em>/lib/systemd/system/</em></strong> which is not advisable.</p><p>Unit files within <strong><em>/lib/systemd/system/</em></strong> can be copied to <strong><em>/etc/systemd/system/</em></strong>.<br>Edits are made in this location because it won’t be overwritten during a system upgrade (advisable). Also, unit files in <strong><em>/etc/systemd/system/</em></strong> have higher precedence for discovery than other locations.</p><p>Unit files in either of these locations can also be overwritten and extended through the use of drop-in files.</p><p>In this section, we’d write a configuration file to manage a sample application.</p><p>Install stress via “<strong><em>sudo apt install stress</em></strong>” and create a file service named foo.service using “<strong><em>sudo vim /etc/systemd/system/foo.service</em></strong>”.</p><p>Define the body of this file with the following section and directives like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*5ZCKPOhEmjaIrF34pfVKAg.png" /><figcaption>Figure 4. foo.serviceExecStart directives defines the program for execution</figcaption></figure><p>This creates a cgroup for foo.service using the ExecStart — CPU, — io, — vm, — vm-bytes flags to specify values for their respective cgroup subsystem.</p><p>“<strong><em>sudo systemctl start foo.service</em></strong>” starts the service and “<strong><em>sudo systemctl status foo.service</em></strong>” to view the status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*lqlf_2Rp8UnWCiLbgGEjtw.png" /><figcaption>Figure 5. foo.service current status</figcaption></figure><p>To create a drop in file for foo.service in <strong><em>/etc/systemd/system/</em></strong>, create a foo.service.d directory create <strong>00-foo.conf</strong> which is the drop-in file.</p><p>Edit <strong>00.foo.conf</strong> to look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*MZQKb4SDXGmdXt8mxw0kOA.png" /><figcaption>Figure 6. Drop-in file for foo.service</figcaption></figure><p>When modifying ExecStart of the actual unit file in a drop-in file, make sure to define ExecStart to nothing and redefine it to a new command just like we have above.<br>Now, ExecStart has been successfully modified in <strong><em>/etc/systemd/system/foo.service</em></strong> without actually writing to it. Restart the service to see the change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*KpkSKqcHQIALgmIx-DBPIA.png" /><figcaption>Figure 7. Drop-in file modifying foo.service</figcaption></figure><p><strong>NB: You should reload the systemd daemon before restarting.</strong></p><p>We can now see that the drop-in file is active and systemd was able to reflect the change on foo’s service.</p><p><strong><em>systemd-delta</em></strong> outputs the different changes made to all unit files. This is the equivalent of git diff.</p><p>Please refer to the systemd manual page for more insight on resource management using systemd and cgroups (which is outside the scope of this article).</p><p>“<strong><em>sudo systemctl edit [unit]</em></strong>” creates a drop-in file in <strong><em>/etc/systemd/system/unit.d/override.conf</em></strong> and automatically reloads the unit after editing.</p><p>“<strong><em>sudo systemctl revert [unit]</em></strong>” reverts back to the vendor-specific version.</p><h3>Conclusion</h3><p>systemd standardizes how Linux-based systems should be managed. This is different from hacks common among System V init implementations.</p><p>We’ve also discussed the Sys V-based issues and how systemd surmounts them. But it is only little of systemd’s capabilities that I can fit in this article. Archlinux intro paragraph to their wiki on systemd says:</p><blockquote>systemd provides aggressive parallelization capabilities, uses socket and D-Bus activation for starting services, offers on-demand starting of daemons, keeps track of processes using Linux control groups, maintains mount and automount points, and implements an elaborate transactional dependency-based service control logic.</blockquote><p>Like this isn’t huge enough, it still goes on to say:</p><blockquote>systemd supports SysV and LSB init scripts and works as a replacement for sysvinit. Other parts include a logging daemon, utilities to control basic system configuration like the hostname, date, locale, maintain a list of logged-in users and running containers and virtual machines, system accounts, runtime directories and settings, and daemons to manage simple network configuration, network time synchronization, log forwarding, and name resolution.</blockquote><p>So to experience and use the power of systemd to its full glory, I’d advise you to study further. Links to resources and materials referenced in this can be found below.</p><p><strong>Quick Fact</strong><br>systemd was developed by Lennart Poeterring and Kay Sievers — software engineers working for Red Hat. The migration from traditional init based systems to systemd is probably the most fiercely debated topics in Linux’s history. For arguments for and against systemd, it would be interesting if you visit the <a href="http://0pointer.de/blog/projects/the-biggest-myths.html">biggest myths</a> and <a href="https://nosystemd.org/">no-systemd</a>.</p><h3>References</h3><p><a href="https://wiki.archlinux.org/index.php/Systemd#Editing_provided_units">Archlinux systemd wiki</a></p><p><a href="https://en.wikipedia.org/wiki/Systemd">Wikipedia systemd</a></p><p><a href="https://www.digitalocean.com/community/tutorials/understanding-systemd-units-and-unit-files#anatomy-of-a-unit-file">Understanding Systemd Units and Unit Files | DigitalOcean</a></p><p><a href="https://www.amazon.com/UNIX-Linux-System-Administration-Handbook/dp/0134277554">UNIX and Linux System Administratior Handbook</a></p><p><a href="https://www.amazon.com/How-Linux-Works-2nd-Superuser/dp/1593275676">How Linux Works</a></p><p><a href="https://man7.org/linux/man-pages/man5/systemd.service.5.html">systemd.service(5) — Linux manual page</a></p><p><a href="https://man7.org/linux/man-pages/man7/cgroups.7.html">cgroups(7) — Linux manual page</a></p><p><a href="https://developer.ibm.com/technologies/linux/tutorials/l-lpic1-101-3/">Learn Linux, 101: Runlevels, boot targets, shutdown, and reboot</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad06aeca4fd0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why is money the problem for a startup in Africa?]]></title>
            <link>https://emmanuelbashorun.medium.com/why-is-money-the-problem-for-a-startup-in-africa-ebede4b6595f?source=rss-c47a970db78d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebede4b6595f</guid>
            <dc:creator><![CDATA[Emmanuel Bashorun]]></dc:creator>
            <pubDate>Thu, 30 Apr 2020 21:35:39 GMT</pubDate>
            <atom:updated>2020-04-30T23:13:30.847Z</atom:updated>
            <content:encoded><![CDATA[<p>This post first appeared as my answer to a question on Quora:</p><p><a href="https://www.quora.com/Why-is-money-the-problem-for-a-startup-in-Africa">Why is money the problem for a startup in Africa?</a></p><p>Money really isn’t the problem for African startups and by definition of African startups, I mean startups founded or not founded by Africans but operate or have Africa as their primary market base.</p><p>One issue is the unassurance of a monetarily viable market that can match the millions of dollars from Venture Capital firms. As these startup’s burn through investors money, they simultaneously have a hard time in figuring out on how to have a profitable business model.</p><p>Konga for instance — an e-commerce firm in Nigeria — got money of up to $160m with major investments coming from Kinnevik and Naspers. A whole lot went into operational costs, building entire infrastructures that was lacking within the industry (Kongapay was built because there wasn’t a viable payment infrastructure in the country as at their time) etc. They eventually ran out of money and were forced to sellout for less than $10m.</p><p>Now all this doesn’t mean Nigeria isn’t mature for tech businesses or what have you on the contrary it means tech startups entrepreneurs aren’t solving the problems that need solutions. Simple. There are lots of people going to bed without food, water and electricity, there are bad roads, poor educational system, shambolic healthcare policies and facilities and most importantly unemployment.</p><p>Entrepreneurs need to create businesses that empowers an average African. That’s the first way to get this thing done. Empower them by creating a system that gives money or alleviates poverty or takes away a significant problem from their lives (power blackouts) or gives tangible value (healthcare and education).</p><p>African countries don’t require solutions to problems that won’t have an immediate poverty-alleviating effect on the lives of people. Africa needs solutions to real problems and not abstract ones.</p><p>Most of these ideas being churned out and funded by foreign VC’s don’t have positive effects that influences the majority of Africa’s demography which are the poor ones. They are too luxurious for the bulk of Africans to pay attention to while they battle with problems bigger problems staring right at their faces.</p><p>Ride hailing companies (Uber and Taxify) are perfect examples of businesses that tackles a pressing problem faced by Africans — Transportation. They’ve been solved to a limited extent, the transport problems in cities like Lagos and at the same time provided value to car drivers and owners hence its popularity. Yet most Africans can’t afford on-hailing services because of the high cost. Asides that, their business model is threatened by unstable policies instituted by a highly uninformed government. Other factors include lack of infrastructure which is majorly the responsibility of the government</p><p>One may also argue that poor Africans might experience higher economic dividends if more investments are poured into think tank groups that focus on policy research with sharp pro-trade and liberal economy undertone cum ideology.</p><p>Adoption of these developments as replacement to outdated policy and regulatory frameworks would lead to a multiplier effect that won’t only benefit just the poor people but also make room for the development of an advanced economy.</p><p>I believe if these issues faced by Africans are well understood by angel investors and VC firms they’d develop a sixth sense for the identification of well meaning ideas and startups that solve real problems rather throwing greenbacks on some “hey bro” app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebede4b6595f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linux File System: Virtual File System (VFS) Layer | Part 3]]></title>
            <link>https://emmanuelbashorun.medium.com/linux-file-system-virtual-file-system-vfs-layer-part-3-79235c40a499?source=rss-c47a970db78d------2</link>
            <guid isPermaLink="false">https://medium.com/p/79235c40a499</guid>
            <category><![CDATA[windows-10]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[filesystem]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Emmanuel Bashorun]]></dc:creator>
            <pubDate>Thu, 30 Apr 2020 19:55:06 GMT</pubDate>
            <atom:updated>2020-04-30T20:38:30.990Z</atom:updated>
            <content:encoded><![CDATA[<p>Before getting into the business of the day, let me quickly establish some points 📌.</p><ol><li>This is not a beginner level tutorial but anyone can follow up as long as learning isn’t a problem.</li><li>I’m not a Linux file system guru so I can’t basically cover everything here but I’ll try my best.</li><li>All mistakes, inaccuracies and falsehood made are my fault and I take responsibility for them. At the same time please point them out. Loud and clear.</li></ol><p>It’s a normal instance for Linux systems to contain multiple mounted file systems. These file systems usually have different implementation details on how they manipulate data.</p><p>Lets assume a Computer has <strong>NTFS</strong> (native windows file system) and <strong>ext4</strong> file systems mounted at different namespaces on a disk drive together with a <strong>network file system</strong> (NFS) for transferring data between a network and a user-space program that needs to interface with these file systems.</p><p>One problem arising from this instance is that if a user-space client requires to interact among these file systems, the kernel would then need to define a 1:1 mapping between the file system handling mechanism and file system. i.e. One unique method for connecting various file systems with the kernel. A programmer might quickly note that defining multiple manipulation strategies automatically leads to code duplication or duplication of actions.</p><p>Another problem is that these file systems would also have a hard time communicating with one another. This means our user-space client can’t pipe data from one file system into another, do some filtering and output modified data using another file system. At every point of piping the kernel would have to initiate complex procedures to handle file system switching.</p><p>3 file systems above translates to 3 different kernel implementations. So what if there were 20 different file systems? You do the math.</p><p>How do we the go about the problem?</p><p>This problem is solved with the help of the VFS (<strong>V</strong>irtual <strong>F</strong>ile <strong>S</strong>ystem).</p><h3>So what’s the VFS?</h3><p>VFS (Virtual File System aka Virtual File Switch) is actually a wrapper around the kernel low-level file system interface. It abstracts all the file handling mechanisms into one procedure that all user-space programs and file system types must conform too.</p><p>Our very good ol’ Wikipedia the free encyclopedia gives a succinct explanation:</p><blockquote>A <strong>virtual file system</strong> (<strong>VFS</strong>) or <strong>virtual filesystem switch</strong> is an abstract layer on top of a more concrete file system. The purpose of a VFS is to allow client applications to access different types of concrete file systems in a uniform way. A VFS can, for example, be used to access local and network storage devices transparently without the client application noticing the difference.</blockquote><p>Need a mental model?</p><p>Here’s one I got for you at <a href="https://opensource.com/article/19/3/virtual-filesystems-linux">opensource</a> free-of-charge:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*dNuKgJjRomCjVGIfkevr2Q.png" /><figcaption>Figure 1: VFS’s interactions</figcaption></figure><p>A computer having multiple file systems can interact and coexist with themselves by communicating with the <strong>VFS</strong> which now poses as a common file system interface. Generic syscalls like <strong>write()</strong>, <strong>read()</strong> can then made by user-space programs which is then interpreted by the <strong>VFS</strong> and sent to the file system for the appropriate command to be executed.</p><p>Problem solved!!.</p><h3>The file system abstraction layer</h3><p>We understand that different file system come with different features, implementations, quirks and similarities too!!. And we know that the abstraction layer makes these things work together seamlessly when used with <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=15&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwiBlqjD7ZDpAhWpyoUKHdIRA7MQFjAOegQIAhAB&amp;url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FSystem_call&amp;usg=AOvVaw3s7Mu981EpL9aSnhlfCmrq"><strong>syscalls</strong></a>.</p><p>So how does this abstraction layer work?</p><p>The abstraction layer is possible because the <strong>VFS</strong> has a common file model that understands the different features, quirks of these file system and also represent the file system’s general feature set and behavior. The data structures (files and directories) and interface supported by the file systems are defined by the abstraction layer.</p><blockquote>The filesystems mold their view of concepts such as “this is how I open files” and “this is what a directory is to me” to match the expectations of the VFS. The actual filesystem code hides the implementation details. To the VFS layer and the rest of the kernel, however, each filesystem looks the same. They all support notions such as files and directories, and they all support operations such as creating and deleting files.</blockquote><blockquote>Ref: <a href="https://www.amazon.com/Linux-Kernel-Development-Developers-Library-ebook/dp/B003V4ATI0/ref=sr_1_1?dchild=1&amp;keywords=Linux+Kernel+Development+Robert+Love&amp;qid=1588273281&amp;s=books&amp;sr=1-1"><strong>Robert, Love. Linux Kernel Development.</strong></a></blockquote><p>The kernel doesn’t need to understand the intricacies of the computer’s file system. All of these have been abstracted away from the kernel by the <strong>VFS</strong>.</p><p>So a user-space program which uses the <strong>write()</strong> <strong>syscall</strong> doesn’t execute a <strong>syscall</strong> subroutine in the kernel immediately, rather a generic <strong>syscall</strong> from the <strong>VFS</strong> handles the request and determines which file system is been called via the file descriptor. The generic <strong>syscall</strong> automatically initiates the <strong>write()</strong> call that’s part of the particular file system implementation.</p><p>The above explanation can be summarized with the code snippet and diagram below:</p><p><strong>ret = write (fd, buf, len);</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*x8jiNbuEBeFoH2OAuFxJTg.png" /><figcaption>Figure 2: How the user-space write() call executes</figcaption></figure><p>The <strong>write()</strong> call attempts to transfers the data in <strong>buf </strong>into the location indicated by <strong>fd </strong>(location of receiving file system) by invoking <strong>sys_write()</strong> in the <strong>VFS</strong> which then triggers the appropriate file system with the help of <strong>fd </strong>(file descriptor)</p><p><strong>Examples of file systems supported by Linux VFS includes</strong></p><ul><li>Disk-based filesystems: ext2, ext3, ext4, MINIX, ubifs, VxFS, sysv, ufs, UDF DVD, ISO9669 CD-ROM</li><li>Network filesystems: nfs, coda, afs, cifs, ncp</li><li>Special filesystems: cgroups, tmpfs, devtmpfs, proc, Sysfs etc.</li></ul><p>NB: Check the <strong>fs </strong>folder in your Linux machine’s kernel repository to see supported file systems.</p><p><strong>Examples of system calls supported by VFS</strong></p><ul><li>Filesystem: mount(), umount(), umount2(), sysfs(), statfs(), fstatfs(), statfs64(), fstatfs64(), ustat()</li><li>Directories: chdir(), fchdir(), getcwd(), mkdir(), rmdir(), getdents(), getdents64(), readdir(), link(), unlink(), rename() etc</li><li>Files: chown(), fchown(), lchown(), fchmod(), chmod() etc</li><li>Links: readlink(), symlink()</li></ul><p><strong>A recap on what Linux file systems are</strong></p><p>File system in Linux systems means the structured representation of saved data in a disk drive that follows specific (hierarchical) format all within a single namespace.</p><p>We can also have multiple namespaces within a disk drive but they are all hooked up or mounted at a particular point within the disk drive. The top most point of the main namespace where all other namespaces are mounted on is called root.</p><p>This is unlike Windows systems that represent disk drives in form of drive letter such as C:, E: etc (this file system design is inferior to Linux’s). The situation leads to a phenomenon call “hardware leak”. You can look that up on Google.</p><p>Abstraction related to Linux file systems includes:</p><ol><li>Files</li><li>Directories</li><li>Inodes</li><li>Mount points</li></ol><p>PS: Calling directories as folders usually elicit unpleasant reactions from Linux users because its a Windows thing. So beware!</p><p>Files are represented as an ordered string of bits while directories consists of files. Directories can also nest other directories called sub-directories. A collection of nested directories can be referred to as a path. The components within this path is called a <strong>dentry</strong>. Therefore directories, sub-directories and files within a path are know as <strong>dentries</strong></p><p>And we also know that information about a particular file such as owners, permissions etc are stored as a datastructure known as <strong>inode</strong> <strong>i</strong>ndex <strong>n</strong>ode. Inodes don’t contain file names. There are other things like <strong>superblocks</strong> etc.</p><p><a href="https://medium.com/@emmanuelbashorun/a-deep-dive-into-the-linux-filesystem-part-1-d06d365d42bb">You can find more about file systems here</a></p><h3>VFS and its associated objects (The fun part 🥳)</h3><p><strong>VFS</strong> is object oriented.</p><p>Well, that’s a partial lie. Remember when we talked about the common file model that’s able to interact with these multiple file systems? The <strong>VFS</strong> implements this model as <strong>primary objects</strong>. But we know C language doesn’t support OOP so we make use of structures as a hack. This way, we are kinda able to assign object oriented capabilities to this model.</p><blockquote><strong><em>Structures == Objects in Linux VFS parlance</em></strong></blockquote><p>In this section we will talk about these objects and their datastructures.</p><p>The primary objects represented by the <strong>VFS</strong> includes:</p><ol><li>File object: This represents an open file as associated with a process</li><li>Superblock object: This represents the entire file system metadata</li><li>Inode object: Represents metadata about a particular file</li><li>Dentry object: This represents a directory object.</li></ol><p>The primary objects represent the file abstractions that were familiar with in normal file systems.</p><p><strong>NB</strong>: This primary objects are logical entities within the <strong>VFS</strong> as opposed to the actual <strong>superblocks</strong>, <strong>inodes</strong> contained with specific part of a disk drive.</p><p><strong>NB</strong>: The primary objects were built with a Unix mindset but other file systems e.g FAT32 that don’t support these objects model their datastructures to suit the common file model of the <strong>VFS</strong>.</p><p><em>In Robert Love’s Linux kernel development book, he notes that</em></p><blockquote>“people often miss this, or even deny it, but there are many examples of object-oriented programming in the kernel. Although the kernel developers may shun C++ and other explicitly object-oriented languages, thinking in terms of objects is often useful. The VFS is a good example of how to do clean and efficient OOP in C, which is a language that lacks any OOP constructs.”</blockquote><p>He further notes that</p><blockquote>“objects refer to structures — not explicit class types, such as those in<br>C++ or Java.These structures, however, represent specific instances of an object, their associated data, and methods to operate on themselves.They are very much objects.”</blockquote><p>The kernel needs to manipulate the file system primary objects and it does so by manipulating each of their individual <strong><em>operations object</em></strong>. And we have 4 of them. Namely:</p><ol><li><strong>file_operations </strong>object: We know from OOP that objects contain methods. So this objects contains methods that the kernel can invoke to open file. Some are read(), write()</li><li><strong>super_operations</strong> object: The kernel uses the methods to invoke meta data about a particular file system in hierarchy. Eg. write_node() and sync_fs(); <strong>*write_super()</strong> is a pointer that writes to the file system superblock.</li><li><strong>inode_operations</strong> object: The kernel can invoke methods associated with this object on specific file. It can determine set permissions, owner, group and other meta data belonging to a file. Eg. create() and link()</li><li><strong>dentry_operations</strong> object: This contains methods that kernel can call on a particular directory. Eg d_compare() and d_delete()</li></ol><p>We should also note that each mount point in the file system is represented by the <strong>vfsmount </strong>structure. Each mounted file system is also represented by the <strong>file_system_type </strong>structure. Even processes have their own structures which describes their associated file system and files.</p><h3>Let’s take a look at the <strong>super_block</strong> primary object.</h3><p>So we know that the <strong>superblock</strong> stores information about the file system and its object counterpart in the <strong>VFS</strong> is also used for the same purpose. Infact it maps to the <strong>superblock</strong> region that’s contained within the disk drive. <a href="https://medium.com/@emmanuelbashorun/a-deep-dive-into-the-linux-filesystem-part-1-d06d365d42bb">Check here for a refresher on what superblocks are</a>.</p><p>The <strong>superblock</strong> object is defined as a <strong>struct.</strong> Remember that we use structs as objects in C. A description for this object can be found within the <strong>&lt;linux/fs.h&gt;</strong> header file.</p><p>And we know that header files don’t necessary contain C code although they could, but most of the time, they usually contain directives utilized by the C compiler when executing C programs. The actual C code related to the directives specified in the header file resides in a library file or exists as a precompiled binary code. That’s why the code utilized by for manipulating superblocks resides within <strong>fs/super.c</strong>.</p><p>So a mounted file system automatically,</p><ol><li>triggers <strong>alloc_super()</strong> function,</li><li>reads the file system data contained within the superblock of the disk drive and</li><li>transfers it into the <strong>super_block</strong> object of the VFS.</li></ol><p>The <strong>&lt;linux/fs.h&gt; </strong>that describes the <strong>super_block</strong> structure is really big and it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*ea92nIQdcKl6cGdqK79afw.png" /><figcaption>Figure 3: super_block object or struct defined in a header file</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*n5p2FclAYD7tkjof2izy9g.png" /><figcaption>Figure 4: Continuation of the super_block struct</figcaption></figure><p>We can see that this <strong>super_block</strong> struct contains the <strong>super_operations</strong> that we discussed above.</p><h3>Let’s take a look at the <strong>s_op</strong> item of the super_block object</h3><p>The <strong>s_op </strong>object is within the <strong>super_block </strong>header and its also defined within the <strong>&lt;linux/fs.h&gt;</strong> header file which is the same as that of <strong>super_block </strong>and it points to the <strong>super_block operations </strong>table which is contained by <strong>struct</strong> <strong>super_operations</strong>. You can check for all this in the image above.</p><p>Here is the <strong>super_operations</strong> <strong>struct</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*JClfb92Y-KOrPuhCAIGAOw.png" /><figcaption>Figure 5: super_operations struct</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*ET12tSMeRkXF5jdj3PTFlw.png" /><figcaption>Figure 6: Continuation of super_operations struct</figcaption></figure><p>Before I further go into the details of this, let me point 😊 out something.</p><p>Each item within the <strong>super_operations</strong> struct is a pointer to a function that operates on a <strong>super_block</strong> object.</p><p>Therefore,<strong> super_operations</strong> object or structure is actually a structure of pointers. And recall when we said operations contain methods that the kernel uses in manipulation. The pointers residing within the <strong>super_operations</strong> <strong>struct</strong> point to functions and methods that operate on the parent object which is the <strong>super_block</strong>. Magic!</p><p>Look, I don’t know how you see this, but it feels like a type recursion to me. It actually isn’t though.</p><p>Let’s see the pointers pointing.</p><p><strong><em>sb-&gt;s_op-&gt;write_super(sb);</em></strong></p><p><strong><em>sb </em></strong>(super_block) points to a <strong>superblock</strong> within the particular mounted filesystem which then points to <strong><em>s_op </em></strong>which further points to the <strong>super_operations</strong> <strong>struct </strong>and follows up to the <strong><em>write_super(). write_super() </em></strong>accepts the super_block as parameter aka parent object. You see.</p><p><strong>super_block </strong>had to go through all this hassle just to call <strong><em>write_super() </em></strong>which still accepted <strong>super_block</strong> as a paremter. This is basically because C lacks OOP constructs. With Python, C++ or any OOP langauage we could easily have achieved this task using a simple <strong><em>sb.write_super().</em></strong></p><p>Other <strong>VFS</strong> objects like <strong>inode</strong> object, <strong>dentry</strong> object have their own associated operations and methods of which I just can’t go through in this article.</p><p>Wheew. So we’ve come along talking about file systems and a few things in it.</p><p>If you genuinely read up to this point then congrats because you already possess the traits of becoming a great computer hacker. Also, I’m of the assumption that curiosity led you to this point so I suggest you read-up further on the other objects not talked about here and also expatiate the knowledge you gained here.</p><p>I’ll leave some links to resources that I’ve found helpful. I do hope you make out time to open them. They are good for you.</p><p>Thanks to you all readers and I hope I’ve been able to spark your bulb for an affinity to Linux and also to <a href="https://twitter.com/CuriousPaul2">@Curious Paul</a> for making corrections and edits.</p><p>And also, please drop your comments below and a clap 👏 beside.</p><h3>Resources and References</h3><p><a href="https://www.control-escape.com/linux/lx-filesys.html">The Linux (Virtual) File System - Guide to Linux for Beginners</a></p><p><a href="https://www.amazon.com/Linux-Kernel-Development-Developers-Library-ebook/dp/B003V4ATI0/ref=sr_1_1?dchild=1&amp;keywords=Linux+Kernel+Development+Robert+Love&amp;qid=1588273281&amp;s=books&amp;sr=1-1">https://www.amazon.com/Linux-Kernel-Development-Developers-Library-ebook/dp/B003V4ATI0/ref=sr_1_1?dchild=1&amp;keywords=Linux+Kernel+Development+Robert+Love&amp;qid=1588273281&amp;s=books&amp;sr=1-1</a></p><p><a href="https://www.amazon.com/Primer-Plus-Plus_6-Developers-Library-ebook/dp/B00GWLPX76/ref=sr_1_1?crid=381BW5QQLT74A&amp;dchild=1&amp;keywords=c+primer+plus+6th+edition&amp;qid=1588273405&amp;sprefix=C+Primer%2Caps%2C387&amp;sr=8-1">https://www.amazon.com/Primer-Plus-Plus_6-Developers-Library-ebook/dp/B00GWLPX76/ref=sr_1_1?crid=381BW5QQLT74A&amp;dchild=1&amp;keywords=c+primer+plus+6th+edition&amp;qid=1588273405&amp;sprefix=C+Primer%2Caps%2C387&amp;sr=8-1</a></p><p><a href="https://www.amazon.com/Linux-Programming-Interface-System-Handbook-ebook/dp/B004OEJMZM/ref=sr_1_1?dchild=1&amp;keywords=Linux+programming+interface&amp;qid=1588274140&amp;sr=8-1">https://www.amazon.com/Linux-Programming-Interface-System-Handbook-ebook/dp/B004OEJMZM/ref=sr_1_1?dchild=1&amp;keywords=Linux+programming+interface&amp;qid=1588274140&amp;sr=8-1</a> [Chapter 3 to understand Syscalls]</p><p><a href="https://medium.com/@emmanuelbashorun/a-deep-dive-into-the-linux-filesystem-part-1-d06d365d42bb">https://medium.com/@emmanuelbashorun/a-deep-dive-into-the-linux-filesystem-part-1-d06d365d42bb</a> [PART I]</p><p><a href="https://medium.com/@emmanuelbashorun/a-deep-dive-into-the-linux-filesystem-part-2-87999610062f?source=your_stories_page---------------------------">https://medium.com/@emmanuelbashorun/a-deep-dive-into-the-linux-filesystem-part-2-87999610062f</a> [PART II]</p><ul><li><a href="https://learnlinuxconcepts.blogspot.com/2014/10/the-virtual-filesystem.html">The Virtual Filesystem</a></li><li><a href="https://en.wikipedia.org/wiki/Virtual_file_system">Virtual file system</a></li><li><a href="https://www.kernel.org/doc/html/latest/filesystems/vfs.html">Overview of the Linux Virtual File System - The Linux Kernel documentation</a></li><li><a href="http://www.tldp.org/LDP/khg/HyperNews/get/fs/vfstour.html">A tour of the Linux VFS</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79235c40a499" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep-dive into the Linux Filesystem | Part 2]]></title>
            <link>https://emmanuelbashorun.medium.com/a-deep-dive-into-the-linux-filesystem-part-2-87999610062f?source=rss-c47a970db78d------2</link>
            <guid isPermaLink="false">https://medium.com/p/87999610062f</guid>
            <category><![CDATA[filesystem]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Emmanuel Bashorun]]></dc:creator>
            <pubDate>Wed, 01 Apr 2020 20:52:21 GMT</pubDate>
            <atom:updated>2020-04-01T20:52:21.393Z</atom:updated>
            <content:encoded><![CDATA[<p>The part one of this article series explained what a filesystem is and how it manages files or itself (in a preliminary level) in conjunction with the operating system. Since this is a Linux-themed article series, filesystems that are commonly associated with the Linux operating system were briefly discussed.</p><p>In this article, we take a deeper look into Linux’s filesystem hierarchy; file permissions, formatting and mounting of file systems will also be discussed.</p><h3>Filesystem Hierarchy</h3><p>NB: In Linux everything is a file! Block devices, processes, peripherals, kernel data structures, what else? Think of anything. It’s a file in Linux.</p><p>The filesystem hierarchy defines how files and directories are structured within the operating system.</p><p>Every Linux filesystem starts with a <strong>root</strong> directory. This is the entry point into the filesystem for all other files and directories. The <strong>root </strong>is represented with a ‘forward slash’ (/). i.e. it is a host for all other directories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*ZpH8AQS0TlWkx2iOmA30fw.png" /><figcaption>Figure 1: Filesystem hierarchy of my Linux computer</figcaption></figure><p>This root directory is different from the /root directory above. We would get to the difference later on.</p><p><strong>/bin</strong>: This folder contains executable files of core operating system commands. Examples of such commands include: ls, rm, lsmod, lsblk, cat, kill etc</p><p><strong>/home</strong>: Home to the users files such as pictures, personal documents, music, downloads etc. Linux is a multi-user OS so all other users of the Linux system would have their own home folder (with appropriate permissions) containing data peculiar to them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*Wl9356UlKWRLulTkf3rXNg.png" /><figcaption>Figure 2: The ‘home’ directory contains a home directory called bashorun. bashorun belongs to user bashorun.</figcaption></figure><p><strong>/lost+found: </strong>Data recovered after a system crash are dumped here.</p><p><strong>/proc: </strong>Hosts information about processes. You can ‘ls’ within this directory to get the PID’s of current running processes.</p><p><strong>/snap: </strong>Contains files and folders pertaining to installed Snap applications.</p><p><strong>/usr: </strong>Secondary hierarchy for read-only user data. Contains the binaries, executable files, libraries of secondary level applications</p><p><strong>/usr/include: </strong>contains standard libraries and files. These standard libraries are usually C/C++ header files.</p><p><strong>/usr/lib: </strong>hosts libraries to binary programs in the <strong>/bin</strong> and <strong>/sbin </strong>directories.</p><p><strong>/usr/libexec: </strong>includes internal binaries that are not intended to be executed directly by users or shell scripts.</p><p><strong>/usr/local: </strong>Contains data such as header files, binaries, man pages of applications installed locally. i.e compiled by a Sysadmin rather than the Linux system distribution.</p><p><strong>/usr/sbin: </strong>Contains inessential binaries that are useful to Sysadmin’s. E.g for binaries for repairs, daemons for network-services etc</p><p><strong>/usr/src: </strong>Contains source to local and non-local compiled software. E.g kernel source code</p><p><strong>/boot: </strong>Houses boot-loader files (grub), initrd. These files are essential for starting up a Linux machine.</p><p><strong>/media: </strong>Removable media such as USB, CD-ROM are mounted on this directory.</p><p><strong>/srv: </strong>Contains data served by this system for specific services. They could be data and scripts for web servers or version-control related data.</p><p><strong>/var: </strong>Contains configuration files, system specific data and data that are subject to change (can be overwritten). Examples include system and application logs.</p><p><strong>/cdrom: </strong>CD-Roms can be mounted to this folder. But they are rarely mounted here as a result of the official Linux Filesystem Hierarchy specification stating that mounts should be made on the <strong>/media </strong>directory.</p><p><strong>/mnt: </strong>Contains temporarily mounted filesystems.</p><p><strong>/root: </strong>Linux systems have a root user account. This directory is the home directory of the superuser account. On Ubuntu, the superuser is unavailable by default. It would have to be created by the Sysadmin.</p><p><strong>/dev: </strong>Physical devices are mounted on this directory. Hard drive partitions are listed as sda’s here.</p><p><strong>/lib: </strong>Dynamic libraries, shared libraries to executable found in /bin and /sbin.</p><p><strong>/run: </strong>This temporary directory that becomes available from boot time. It stores runtime information (PID files, socket endpoints etc) required by boot-time programs ( programs that start up very early) before the <strong>/var/run </strong>becomes available to the system.</p><p><strong>/sys: </strong>Contains files that provides an interface certain kernel modules and subsystems, hardware devices to the user space.</p><p><strong>/etc: </strong>Contains system-wide configuration files that controls critical parts of the system</p><p><strong>/opt: </strong>for optional software packages</p><p><strong>/sbin: </strong>Contains essential operating system commands.</p><p><strong>/tmp: </strong>Contains temporary files generated by applications. The files are usually deleted after shutdown.</p><p><strong>vmlinuz (virtual memory linux gzip):</strong> This is not a directory. It is the Linux kernel executable in compressed form. It loads (vmlinuz is bootable) the operating system into the RAM and also mounts with initrd during boot-time.</p><p><strong>initrd (initial ramdisk):</strong></p><blockquote>The <em>initial RAM disk (initrd)</em> is an initial root file system that is mounted prior to when the real root file system is available. The initrd is bound to the kernel and loaded as part of the kernel boot procedure. The kernel then mounts this initrd as part of the two-stage boot process to load the modules to make the real file systems available and get at the real root file system.</blockquote><blockquote>Reference: <a href="https://developer.ibm.com/articles/l-initrd/">https://developer.ibm.com/articles/l-initrd/</a></blockquote><h3>Linux Filesystem Permissions</h3><p>Linux provides an intuitive and simple mechanism for Sysadmins and Linux users to impose restrictions on who-and-who can access files and directories.</p><p>Permissions to files and directories are represented as a collection of 9 bits which appears as -<strong>rwxrwxrwx</strong>.</p><p>The first three bits specifies the owner’s permission status, the second does for groups while the last specifies the permission for others.</p><ol><li>‘r’ represents a ‘read permission’. Current user can read files and directories.</li><li>‘w’ character represents a ‘write’ permission. Current user can write, delete, rename files. Can also add files to directories and rename.</li><li>‘x’ represents an ‘executable’ permission. Current user can run a file as a program and also execute programs from a directory, search through a directory too.</li></ol><p>It’s also worthy of note that the ‘-’ <em>dash </em>before the 9-bits indicates a file object. A ‘d’ represents a directory, ‘l’ stands for a symbolic link, ‘p’ stands for a named pipe, while ‘s’ stands for a socket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*q-hgIP-9tEyqon0RtIAc_Q.png" /><figcaption>Figure 3: File permissions within my /run directory</figcaption></figure><p>File permissions can also be changed. There are a few commands used for setting permissions.</p><p><strong>Chmod</strong></p><p>Each permission (rwx) is assigned a number; r = 4, w = 2, x = 1. The sum total of permissions of each of the 3-bits is represented as a number.</p><p>Hence,</p><ul><li><strong>-rwxrwxrwx </strong>has a <strong>777</strong> permission value — can read, write and execute for everbody</li><li>-<strong>rwxr — r — </strong>has a <strong>722 </strong>permission value — can read, write and execute for owners only. But can read only for groups and others.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*ea-mj40leM1uT4ASnepKZA.png" /><figcaption>Figure 4: Using chmod to change permission</figcaption></figure><p>I assigned full permissions to owner, groups and others by doing chmod 777 bfs.py</p><p><strong>Chmod with Letters</strong></p><p>We’ve been able to change permissions using numbers. Linux also gives us the ability to change permission using letters. Let us see.</p><blockquote>You can also turn file permissions on and off using plus (+) and minus (–) signs, respectively, along with letters to indicate what changes and for whom.</blockquote><blockquote>Using letters, for each file you can change permission for the user (u), group (g), other (o), and all users (a). What you would change includes the read (r), write (w), and execute (x) bits.</blockquote><blockquote>For example, start with a file that has all permissions open (-rwxrwxrwx). Run the following <strong>chmod</strong> commands using minus sign options.</blockquote><blockquote><em>Reference</em>: <em>Negus, C.</em> “Linux Bible”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*lBbDfMFQAB6WclFenfztyQ.png" /><figcaption>Figure 5: Doing chmod with letters</figcaption></figure><p>So,</p><ul><li>bfs.py<strong> has -rwxrwxrwx </strong>permission status. <strong>chmod go-wx</strong> takes away (minus) write and execute permissions for groups and other users.</li><li><strong>chmod g+x bfs.py</strong> adds (plus) execute permission to groups.</li></ul><h3>Managing Filesystems and Partitions</h3><p>Disk partitions could be viewed using the lsblk or fdisk command</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*VhCQnODEXHHLen5Y1rlK7g.png" /><figcaption>Figure 6: lsblk</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*T3nPgS77wW5YBS9ZjWm_-A.png" /><figcaption>Figure 7: fdisk.</figcaption></figure><p>I have an 8gb flash drive hooked up to my usb port for demonstrating filesystem and disk management concepts. The flash drive is labelled sdb1 within the <strong>/dev</strong> folder.</p><p>NB: Be sure to run <strong>sudo umount /dev/sdb </strong>to be sure that the flash drive is unmounted</p><p>Firstly, I’d be creating a new partition</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*crUSggyuYUIAqF-_8mI72A.png" /><figcaption>Figure 7: Partitioning flash drive with fdisk</figcaption></figure><ul><li>Partition your flash drive using fdisk -c -u /dev/sdb1 command</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*hIPhtiBS1S8qxMv7D1NMaA.png" /><figcaption>Figure 8</figcaption></figure><ul><li>Type p to show the partition table. Mine shows my flash drive is a Linux partition</li><li>Type d to delete the existing partition then type ’n’ to create a new one.</li><li>You’d be prompted to type ‘p’ for a primary partition or ‘e’ for an extended one. I chose ‘p’ and you should.</li><li>Type ‘1’ so as to create 1 partition on the flash drive</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*fUT9CiSUIi9vrV8rEJMF5w.png" /><figcaption>Figure 8</figcaption></figure><ul><li>Type ‘w’ to write the partition to disk.</li></ul><p>At this point, a partition has been created but can’t be used.</p><p>A confirmation can be made to ensure if the partition was created by typing ‘ls -la /dev/sdb*</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*_xw9bQn5x-iPiNndgl6y4w.png" /><figcaption>Figure 9</figcaption></figure><p>We’d need to format this partition with a filesystem to let the operating system access it.</p><p>This can be done using the <strong>mkfs(8)</strong> command. Remember in the last article where we discussed about different types of filesystems? We’d be formatting with the ext4 filesystem member of the ext’s family.</p><p>We do this by,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*2OY_Zz1rzxgYe2yIbe8csg.png" /><figcaption>Figure 10</figcaption></figure><p>The filesystem can now be mounted on a particular directory for access.</p><p>I created a folder called ‘mountp’ in my ‘/’ directory and mounted the filesystem there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*96rq98Fvo6BPHr0UYGAyeA.png" /><figcaption>Figure 11</figcaption></figure><p>The /etc/fstab file should be edited this way so that the OS knows where the filesystem should be mounted whenever it is plugged to the system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9dCKvMfijlkil15jjz-cPA.png" /><figcaption>Figure 11: After editing /etc/fstab</figcaption></figure><p>So far, we have read a lot concerning Linux filesystems. In the next article, we’d take a further look into more intricate things than we have done so far. Eg. VFS (<strong>Vi</strong>rtual <strong>F</strong>ile <strong>S</strong>ystem).</p><p>Hope you enjoyed the article.<br>Please leave a comment below and a clap beside.</p><p>Thanks and bye!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87999610062f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep-dive into the Linux Filesystem | Part 1]]></title>
            <link>https://emmanuelbashorun.medium.com/a-deep-dive-into-the-linux-filesystem-part-1-d06d365d42bb?source=rss-c47a970db78d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d06d365d42bb</guid>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[filesystem]]></category>
            <dc:creator><![CDATA[Emmanuel Bashorun]]></dc:creator>
            <pubDate>Thu, 19 Mar 2020 14:58:20 GMT</pubDate>
            <atom:updated>2020-03-19T17:30:26.759Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is one out of a series of articles that seeks to embark on a low to deep level dive geared towards understanding the Linux filesystem.</p><p>This article is cool for:</p><ol><li>new Linux users wanting to understand the filesystem mechanism,</li><li>mid-level Linux users that want to have a deep but not academic-type understanding of the filesystem,</li><li>programmers interested in how the kernel (some kernel dev’ish things) handles files and directories.</li><li>Or if you’re a professional knowledge hoarder like me</li></ol><p>During the course of this article, there’d be some C code snippets around but you won’t need to be a C ninja to understand as I’m not even one. But I’d make sure to have simple explanations for them.</p><p>But before throwing lots of Linux filesystem ‘gibberish’ at you, its pertinent to genuinely have an understanding on the working internals of a ‘filesystem’ regardless of the operating system so as the ‘gibberish’ can make some sense.</p><p>So, to business…</p><h3>What’s a filesystem?</h3><p>You see a filesystem basically handles how data (files, directories, block devices) is arranged, stored. It could also be described as a collection of these datastructures within the operating system. It can even be seen as the whole logic and program structure that controls the behavior of data.</p><p>Wikipedia says a filesystem</p><blockquote>‘controls how data is stored and retrieved. Without a file system, data placed in a storage medium would be one large body of data with no way to tell where one piece of data stops and the next begins.’ <a href="https://en.wikipedia.org/wiki/File_system">https://en.wikipedia.org/wiki/File_system</a></blockquote><p>In essence the filesystem arranges data in an intelligent way. And the storage medium can be a HDD, SDD, flash drive or even a RAM. There are lots of filesystem implementations (Minix, EXT’s, XFS, ZFS, NTFS etc) around (I’d try to talk a bit about them later) with an individual and one collective (VFS comes later on) method of working with data. A filesystem could even be seen as a filesystem implementation.</p><p>The filesystem gives the rules on how data should be accessed on our storage drive. The drive is usually formatted with a type of filesystem implementation to make it accessible to the operating system.</p><h3>Filesystem Structure</h3><p>NB: Data on disks are usually accessed in blocks rather than bytes.</p><p>As said earlier, data is organized on disk drives by the filesystems and the organization can be understood in layers.</p><p>Firstly, there’s the lowest layers which is the <strong>physical device</strong> or disk drive.</p><p>Secondly, the <a href="https://www.cs.uic.edu/~jbell/CourseNotes/OperatingSystems/12_FileSystemImplementation.html"><strong>Input/Output Control</strong></a><strong> </strong>are the hardware drivers or programs which communicate with the devices by reading and writing special codes directly to and from memory addresses corresponding to the controller card’s register.</p><p>Thirdly, the <strong>basic file system</strong> cooperates with the device driver to retrieve and store information of blocks of data without knowing the blocks content.</p><p>Fourthly, the <strong>file organization module </strong>has information on how logical blocks are mapped to physical blocks on the disk for data storage or retrieval.</p><p>And lastly there’s the <strong>logical file system </strong>handles information about a file i.e. it meta data except the files actual data. Things like superblocks and inodes are handled here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*UXwrwlJFa05BzBuGqzbTUA.jpeg" /><figcaption>Figure 1: Filesystem structure</figcaption></figure><p>Ref: <a href="https://www.cs.uic.edu/~jbell/CourseNotes/OperatingSystems/12_FileSystemImplementation.html">https://www.cs.uic.edu/~jbell/CourseNotes/OperatingSystems/12_FileSystemImplementation.html</a></p><p>Data on a disk resides in a partition and a disk can be divided into more partitions.</p><p>You create a partition on a disk drive by formatting it with a filesystem type (remember EXT’s, ZFS etc). Partitions are created if you want to independently have multiple drives formatted with different filesystems and operating system all on one physical hard disk.</p><p>By the way, a partition within a disk, be it an hard disk or flash drive is divided into sectors. This sector can be about 512 bytes in size. A group of sector is called a block. And a block can be made of one or more sectors. For information to be retrieved from disk, the operating system would have to point to a particular block.</p><p>When a partition is created, data is pushed into the first block of the drive which is called the boot block or MBR (Master Boot Record). The boot block contains information that helps bootstrap the machine unto its feet.</p><p>The partition also contains the super block which holds information regarding the filesystem’s layout or structure. It also gives information about the drive’s size, permissions and control, how many file resides on the filesystem, inodes location. The superblock stores metatdata of the filesystem.</p><p>Check: <a href="https://www.slashroot.in/understanding-file-system-superblock-linux">https://www.slashroot.in/understanding-file-system-superblock-linux</a></p><p>Another component of a partition are the inodes (<strong>i</strong>ndex <strong>nodes</strong>). Each file is linked to a number called the i-number.</p><p>Inodes contain specific information such as owner identifier, type of file, array of pointers to data blocks on disk, file size etc about a particular file-object. They store the attribute of a particular disk block that data resides in.</p><p>The inode stores metadata of a file. Feel free to call an inode the superblock of a file. Its similar to how superblocks store metadata of the entire filesystem.</p><blockquote>The inode number indexes a table of inodes in a known location on the device. From the inode number, the kernel’s file system driver can access the inode contents, including the location of the file, thereby allowing access to the file</blockquote><p>Ref: <a href="https://en.wikipedia.org/wiki/Inode">https://en.wikipedia.org/wiki/Inode</a></p><p>Disk space allocation is controlled by inodes. They are created using the <strong>mkfs (1) </strong>command. These <a href="http://digi-cron.com:8080/filesystems.html">inodes</a> are so special that they can’t even be modified directly but are controlled by user space commands like touch or <a href="https://www.slashroot.in/what-is-system-call-in-unix-and-linux">systemcalls</a> like <strong>open(2)</strong>, <strong>unlink(2)</strong>. Commands like <strong>chmod(1)</strong> and <strong>chmod(2)</strong> can be used to alter access permissions.</p><p>There’s also the data block which contains the actual data on the drive that makes sense to us. This could be your text documents or binary files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*M0aOjcezS9Wn_BP5BSlILA.png" /><figcaption>Figure 2: The command shows the existing partition of my hard disk and the size of 1 sector.</figcaption></figure><p>sda1 in the image above contains my Windows OS and also has the bootloader. sda5 is a logical partition that was derived from the sda2 extended partition.</p><p>There was a time in ‘filesystems history’ that hard disks were designed to only have 4 partitions. This proved to be a problem when sysadmins, programmers and computer users need more than a partition to manage their hard disk. For instance a programmer probably wanted to have a Linux, Windows, FreeBSD, Solaris, MS-DOS and Minix OS all at once on his/her drive. Or may be the programmer needed a separate swap partition rather than a swap file. This couldn’t happen because of the limit imposed by the prevalent design schema of then.</p><p>So you see the problem huh?</p><blockquote>To overcome this design problem, extended partitions were invented. This trick allows partitioning a primary partition into sub-partitions. The primary partition thus subdivided is the extended partition; the sub-partitions are logical partitions. They behave like primary partitions, but are created differently. There is no speed difference between them. By using an extended partition you can now have up to 15 partitions per disk.</blockquote><p>Ref: <a href="https://www.tldp.org/LDP/sag/html/partitions.html">https://www.tldp.org/LDP/sag/html/partitions.html</a></p><p>A flash drive on a PC is loaded by device drivers which makes it accessible to the PC but not readable or writable. It is then formatted using a file system of choice to make it usable.</p><p>Before using the flash drive or a request to access a file on the flash drive requires Linux to check the superblock to see the formatted filesystem of the drive. Drivers that supports the flash drive’s file system are loaded from the Linux kernel to read the flash drive and place it on a specific directory. The action of placing a block device formatted with a particular file system on a directory is called <strong>mounting</strong> and that place is called the <strong>mount point</strong>.</p><h3>A few supported Linux File systems</h3><p>There are lots of filesystem types supported by the Linux kernel. You can check yours by running the following command on a terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*2L2oD4vKLEDCbicrUmUxOw.png" /><figcaption>Figure 3: Command shows supported filesystem types</figcaption></figure><p><strong>Minix</strong>: This filesytem was the defacto filesystem of the Minix OS. Minix had its own problems as it only could access 64MB of storage, wasn’t free and open source</p><p><strong>ext</strong>: This was created by Remy Card a year after Torvald’s debuted the Linux kernel. This filesystem could address up to 2GB of storage and 255-character filenames. It also introduced the Virtual File System abstraction layer.</p><p><strong>ext2</strong>: This came to solve ext’s problem by adding more timestamps to the inodes for file access, inode creation and file modification. It could also access a bigger pool of storage space. This was a proper filesystem</p><p><strong>ext3</strong>: The idea of <em>Journaling </em>came with ext3. ext2 could handle problems that results when there’s a power failure during read/write operations on the hard disk. This most of the time leads to great loss of data from related or unrelated files.</p><blockquote>A journaling filesystem is a filesystem that maintains a special file called a journal that is used to repair any inconsistencies that occur as the result of an improper shutdown of a computer. Such shutdowns are usually due to an interruption of the power supply or to a software problem that cannot be resolved without a rebooting.</blockquote><p><a href="http://www.linfo.org/journaling_filesystem.html">What is a journaling filesystem? -- definition by The Linux Information Project (LINFO)</a></p><p><strong>ext4</strong>: This is an extension of ext3 and also the latest iteration of the EXT’s. It provides a higher performance, resistance to fragmentation, and improved timestamps. It was built to be backward-compatible with ext3 but not vice-versa. <a href="https://opensource.com/article/18/4/ext4-filesystem">Check here for a solid talk on ext4 features</a>.</p><p><strong>ZFS: </strong>This has been touted by people as a next-gen filesystem. It also doubles down as a volume manager. Features include: Copy-on-write, snapshots, cryptographically based check-summing ability (for detecting data corruption). <a href="https://www.freebsd.org/doc/handbook/zfs.html">https://www.freebsd.org/doc/handbook/zfs.htm, l</a><a href="https://itsfoss.com/what-is-zfs/">https://itsfoss.com/what-is-zfs/</a>.</p><p>Others include <a href="http://man7.org/linux/man-pages/man5/xfs.5.html">xfs(5)</a>; <a href="https://btrfs.wiki.kernel.org/index.php/Main_Page">btrfs</a> and <strong>man 8 btrfs </strong>for btrfs on the man page.</p><p><strong>Up next!</strong></p><p>The Linux filesystem hierarchy, permissions, access controls, mounting and formatting of partitions would be discussed in a subsequent article.</p><p>Thanks and see you later!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d06d365d42bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How can I start an e-commerce company even with no background in tech in Nigeria?]]></title>
            <link>https://emmanuelbashorun.medium.com/how-can-i-start-an-e-commerce-company-even-with-no-background-in-tech-in-nigeria-319516567e3a?source=rss-c47a970db78d------2</link>
            <guid isPermaLink="false">https://medium.com/p/319516567e3a</guid>
            <category><![CDATA[nigeria]]></category>
            <dc:creator><![CDATA[Emmanuel Bashorun]]></dc:creator>
            <pubDate>Wed, 03 Apr 2019 10:07:22 GMT</pubDate>
            <atom:updated>2019-04-03T10:07:22.121Z</atom:updated>
            <content:encoded><![CDATA[<p>Running an e-commerce business in Nigeria isn’t all about the tech.</p><p>Konga had all the tech yet they couldn’t scale through.</p><p>It’s more of understanding the market dynamics than the technical intricacies to run a successful e-commerce business in Nigeria’s brutally unforgiving market.</p><p>Other than all that, then there are:</p><p><strong>Three ways.</strong></p><ol><li>Hire a professional: This is like the prettiest or easiest way to get it up and running.</li></ol><p>From Thomas Edison</p><blockquote><em>I don’t ​know anything about Mathematics; can’t even do proportions. But I can hire all the good mathematicians I need for $15 a week.</em></blockquote><p>2. Building it yourself​: Building a product like and e-commerce site requires a great understanding of the tech involved. You’ll have to familiarize yourself with modern web technologies, frameworks, UI/UX design, database management, security etc. It’s going to take you some time, effort but it’ll be worth if you go through the path.</p><p>And thirdly,</p><p>3. Get a technical partner: You can get a competent individual as partner (co-founder) that would handle the technical aspect of the business. This saves you some money since it’s a business being run by you both. It saves you time too. You get to concentrate on the other aspects of the business such as marketing, product etc.</p><p>Navigating the business waters of Nigeria is as tough as Ferdinand Magellan discovering the sea route to India.</p><p>The end is all sweet and rosy but the journey is turbulent.</p><p>Are you ready to walk the talk?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=319516567e3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>