<?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 Ravi Kiran Eticala on Medium]]></title>
        <description><![CDATA[Stories by Ravi Kiran Eticala on Medium]]></description>
        <link>https://medium.com/@ravi.eticala?source=rss-19bb84469948------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*aqia81MMeTRjiwMf.jpg</url>
            <title>Stories by Ravi Kiran Eticala on Medium</title>
            <link>https://medium.com/@ravi.eticala?source=rss-19bb84469948------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:58:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ravi.eticala/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[Understanding how Linux ethernet bridge is setup and works]]></title>
            <link>https://medium.com/@ravi.eticala/understanding-how-linux-ethernet-bridge-is-setup-and-works-771ee75bdf67?source=rss-19bb84469948------2</link>
            <guid isPermaLink="false">https://medium.com/p/771ee75bdf67</guid>
            <category><![CDATA[linux-bridge]]></category>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[brctl]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Ravi Kiran Eticala]]></dc:creator>
            <pubDate>Fri, 05 Jun 2020 17:43:45 GMT</pubDate>
            <atom:updated>2020-06-05T17:43:45.815Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is divided into three parts discussing Linux internals of ethernet bridge</p><ul><li>Bridge kernel module</li><li>Adding interface into the bridge</li><li>Life of packet inside the bridge</li></ul><blockquote><strong>Bridge Kernel Module</strong></blockquote><p>In the Linux kernel, the bridge is implemented as a kernel module “bridge”.</p><pre>$ lsmod | grep bridge</pre><p>The bridge module is not yet inserted, solsmod doesn’t show anything about the bridge module.</p><p>brctl, bridge, ipare the utilities to manage the bridge on Linux system.</p><pre>$ brctl<br>Usage: brctl [commands]<br>commands:<br> addbr      &lt;bridge&gt;  add bridge<br> delbr      &lt;bridge&gt;  delete bridge<br> addif      &lt;bridge&gt; &lt;device&gt; add interface to bridge<br> delif      &lt;bridge&gt; &lt;device&gt; delete interface from bridge<br> hairpin    &lt;bridge&gt; &lt;port&gt; {on|off} turn hairpin on/off<br>...</pre><p>Creating a new bridge interface</p><pre># brctl addbr br0</pre><p>This creates a new network interface br0. ip link or brctl show will list the new bridge interface created.</p><pre># <strong>ip link show dev br0</strong><br>3: <strong>br0</strong>: &lt;BROADCAST,MULTICAST&gt; mtu 1500 qdisc noop state DOWN mode DEFAULT group default qlen 1000<br>    link/ether 5e:cd:d7:1c:52:6e brd ff:ff:ff:ff:ff:ff<br># <strong>brctl show br0</strong><br>bridge name bridge id  STP enabled interfaces<br><strong>br0</strong>  8000.000000000000 no</pre><p>Now let’s look at lsmod output again</p><pre># lsmod | grep bridge<br>bridge                135168  0<br>stp                    16384  1 bridge<br>llc                    16384  2 bridge,stp</pre><p>Now we see that a bridge and other related modules are inserted. But what inserted these modules automatically? Let us look into it.</p><pre>$ lsmod | grep bridge<br>bridge                135168  0<br>stp                    16384  1 bridge<br>llc                    16384  2 bridge,stp</pre><pre>$ rmmod bridge<br>$ lsmod | grep bridge<br>$ strace -e trace=socket,ioctl <strong>brctl addbr br0</strong><br><strong>socket(AF_UNIX, SOCK_STREAM, 0)         = 3</strong><br>bridge name bridge id  STP enabled interfaces<br><strong>ioctl(3, SIOCBRADDBR, &quot;br0&quot;)     = 0</strong><br>+++ exited with 0 +++</pre><pre>$ lsmod | grep bridge<br>bridge                135168  0<br>stp                    16384  1 bridge<br>llc                    16384  2 bridge,stp</pre><p>Here I have removed the kernel module “bridge” with rmmod and ran strace to see what system calls are triggering the insertion of bridge module. Looks like a socket <strong>ioctl</strong> with <strong>SIOCBRADDBR</strong> is inserting the modules into the kernel.</p><pre>static long sock_ioctl(struct file *file, unsigned cmd, unsigned long arg)<br>{</pre><pre>...</pre><pre>switch (cmd) {<br>		case FIOSETOWN:<br>...<br>		case <strong>SIOCGIFBR</strong>:<br>		case <strong>SIOCSIFBR</strong>:<br>		case <strong>SIOCBRADDBR</strong>:<br>		case <strong>SIOCBRDELBR</strong>:<br>			err = -ENOPKG;<br>			if (!br_ioctl_hook)<br>				<strong>request_module(&quot;bridge&quot;);</strong></pre><pre>			mutex_lock(&amp;br_ioctl_mutex);<br>			if (br_ioctl_hook)<br>				<strong>err = br_ioctl_hook(net, cmd, argp);</strong><br>			mutex_unlock(&amp;br_ioctl_mutex);<br>			break;<br>		case SIOCGIFVLAN:<br>...<br>	return err;<br>}</pre><p>socket ioctlwith any cmd SIOCGIFBR, SIOCSIFBR, SIOBRADDBR, SIOCBRDELBR would have inserted the “bridge” module into the kernel if br_ioctl_hook is null. request_module is a macro for <a href="https://github.com/torvalds/linux/blob/6f0d349d922ba44e4348a17a78ea51b7135965b1/kernel/kmod.c#L125">__request_module</a> which takes care of inserting the module.</p><p>After the __request_module completed the br_ioctl_hook(net,cmd,argp)<strong> </strong>is called to create a new bridge interface. So request_module is setting up br_ioctl_hook. Now let us look into bridge kernel module init function to see what all are initialized and how is br_ioctl_hook set up.</p><pre>static int __init br_init(void)<br>{<br>...<br>	err = stp_proto_register(&amp;br_stp_proto);<br>...<br>	err = br_fdb_init();<br>...<br>	err = register_pernet_subsys(&amp;br_net_ops);<br>...<br>	err = br_nf_core_init();<br>...<br>	err = br_netlink_init();<br>...<br>	brioctl_set(br_ioctl_deviceless_stub);<br>...<br>}</pre><pre>module_init(br_init)<br>...<br>MODULE_ALIAS_RTNL_LINK(&quot;bridge&quot;);</pre><pre>static const struct stp_proto br_stp_proto = {<br>	.rcv	= br_stp_rcv,<br>};</pre><p>br_init is the bridge kernel module init function. It registers stp_proto_register variable which will handle BPDU (Bridge protocol data unit) frames which contains STP (Spanning tree protocol) information.</p><pre>int __init br_fdb_init(void)<br>{<br>	br_fdb_cache = <strong>kmem_cache_create(&quot;bridge_fdb_cache&quot;,<br>					 sizeof(struct net_bridge_fdb_entry), 0, SLAB_HWCACHE_ALIGN, NULL);</strong><br>...<br>	return 0;<br>}</pre><p>br_fdb_init allocates a cache for bridge forwarding database. struct net_bridge_fdb_entry is the important data structure which maintains a mapping between struct net_bridge_fdb_key (mac_address and VLAN id) to bridge port. We will see more about this structure later in the article.</p><pre>static struct pernet_operations br_net_ops = {<br>	.exit	= br_net_exit,<br>};</pre><pre>static void __net_exit br_net_exit(struct net *net)<br>{<br>...<br>	for_each_netdev(net, dev)<br>		if (dev-&gt;priv_flags &amp; IFF_EBRIDGE)<br>			<strong>br_dev_delete(dev, &amp;list);</strong><br>...<br>}</pre><p>register_pernet_subsys<strong> </strong>registers a network namespace subsystem. Here the br_net_ops as only exit function defined. It removes all devices from this network on exit.</p><p>br_nf_core_init<strong> </strong>initializes the firewall core for the ethernet bridge. br_netlink_init<strong> </strong>initializes routing Netlink address family and link operations.</p><pre>void <strong>brioctl_set</strong>(int (*hook) (struct net *, unsigned int, void __user *))<br>{<br> mutex_lock(&amp;br_ioctl_mutex);<br> <strong>br_ioctl_hook = hook;</strong><br> mutex_unlock(&amp;br_ioctl_mutex);<br>}<br>EXPORT_SYMBOL(brioctl_set);</pre><p>brioctl_set<strong> </strong>assigns the br_ioctl_deviceless_stub function to br_ioctl_hook which we saw earlier.</p><pre>int br_ioctl_deviceless_stub(struct net *net, unsigned int cmd, void __user *uarg)<br>{<br>	switch (cmd) {<br>...<br>	case SIOCBRADDBR:<br>	case SIOCBRDELBR:<br>	{<br>...<br>		if (cmd == SIOCBRADDBR)<br>			return <strong>br_add_bridge(net, buf)</strong>;</pre><pre>		return br_del_bridge(net, buf);<br>	}<br>	}<br>	return EOPNOTSUPP;<br>}</pre><p>So socket ioctlwith cmd SIOCBRADDRD would call <a href="https://github.com/torvalds/linux/blob/6f0d349d922ba44e4348a17a78ea51b7135965b1/net/bridge/br_ioctl.c#L358">br_ioctl_deviceless_stub</a> that would intern call br_add_bridge with struct net* and buffer which contains interface name to be created.</p><p>br_add_bridge creates struct net_device (a core network driver layer structure). struct net_device is created for both physical and virtual interfaces. For the NIC (network interface card), the device driver which is responsible to manage the NIC creates the struct net_device and that gets added to the kernel global struct net_device list. In the bridge case, <a href="https://github.com/torvalds/linux/blob/b71acb0e372160167bf6d5500b88b30b52ccef6e/net/bridge/br_device.c#L417">br_dev_setup</a> initializes the struct net_device of the bridge which is called from<strong> </strong>br_add_bridge.</p><pre>void br_dev_setup(struct net_device *dev)<br>{<br>	struct net_bridge *br = netdev_priv(dev);</pre><pre>	<strong>eth_hw_addr_random</strong>(dev);<br>	ether_setup(dev);</pre><pre>	dev-&gt;netdev_ops = &amp;<strong>br_netdev_ops</strong>;<br>	dev-&gt;needs_free_netdev = true;<br>	dev-&gt;ethtool_ops = &amp;<strong>br_ethtool_ops</strong>;<br>...<br>}</pre><p>eth_hw_addr_random<strong> </strong>generates random ethernet address(MAC) and assigns to dev-&gt;dev_addr.</p><p><a href="https://github.com/torvalds/linux/blob/b71acb0e372160167bf6d5500b88b30b52ccef6e/net/bridge/br_device.c#L383">br_netdev_ops</a><strong> </strong>is of type <a href="https://github.com/torvalds/linux/blob/6f0d349d922ba44e4348a17a78ea51b7135965b1/include/linux/netdevice.h#L1205">struct net_device_ops</a> which contains all the operations that can be performed on net_device.</p><p>br_ethtool_ops<strong> </strong>is of the type <a href="https://github.com/torvalds/linux/blob/6f0d349d922ba44e4348a17a78ea51b7135965b1/include/linux/ethtool.h#L331">struct ethtool_ops</a> which contains optional device operations. ethtool utility calls these operations to set/get the network device configuration.</p><pre>$ ethtool -i br0<br><strong>driver: bridge<br>version: 2.3</strong><br>firmware-version: N/A<br>expansion-rom-version:<br>bus-info: N/A<br>supports-statistics: no<br>supports-test: no<br>supports-eeprom-access: no<br>supports-register-dump: no<br>supports-priv-flags: no<br></pre><blockquote><strong>Adding interface to the bridge</strong></blockquote><p>Next, let us see how the Linux handles adding interfaces to bridge. To do this we will first create two pairs of veth (virtual ethernet device)<strong> </strong>interfaces.</p><pre>$ip link add <strong>veth10</strong> type veth peer name <strong>veth20</strong><br>$ip link add <strong>veth30</strong> type veth peer name <strong>veth40</strong></pre><p>The interface can be added to a bridge by iproute2 or brctl utility. iproute2 uses netlink socket and brctl uses ioctl to add an interface to a bridge. Either way, both utilities end up calling <a href="https://github.com/torvalds/linux/blob/b71acb0e372160167bf6d5500b88b30b52ccef6e/net/bridge/br_if.c#L560">br_add_if</a><strong> </strong>in bridge module.</p><pre>$<strong>brctl show br0</strong><br>bridge name bridge id  STP enabled interfaces<br>br0  8000.000000000000 no</pre><pre>$ip link set <strong>veth10</strong> master <strong>br0</strong><br>$ip link set <strong>veth30</strong> master <strong>br0</strong></pre><pre>$<strong>brctl show br0</strong><br>bridge name bridge id  STP enabled interfaces<br>br0  8000.2669427cd774 no  <strong>veth10</strong><br>                           <strong>veth30</strong></pre><p>Let us look into the internals of what happens when the interface is added to the bridge br0.</p><pre>int br_add_if(struct net_bridge *br, struct net_device *dev,<br>	      struct netlink_ext_ack *extack)<br>{</pre><pre>...<br>	<strong>p = new_nbp(br, dev);</strong></pre><pre>...</pre><pre>	<strong>err = kobject_init_and_add(&amp;p-&gt;kobj, &amp;brport_ktype, &amp;(dev-&gt;dev.kobj),<br>				   SYSFS_BRIDGE_PORT_ATTR);</strong></pre><pre>...<br><strong>	err = netdev_rx_handler_register(dev, br_handle_frame, p);</strong></pre><pre>...<br>}</pre><p>Some of the important initialization done in br_add_if are</p><ul><li>Create a bridge port<strong> </strong>from bridge and net_device</li><li>Setting up a sysfs<strong> </strong>entry</li><li>Registering a bridge handler for receiving packets on net_device</li></ul><p>There are three main structures struct net_bridge, struct net_device, struct net_bridge_port<strong> </strong>in br_add_if<strong>. </strong>net_bridge is the bridge to which the net_device interface is going to be added. net_bridge_port is the new bridge port created by calling <a href="https://github.com/torvalds/linux/blob/b71acb0e372160167bf6d5500b88b30b52ccef6e/net/bridge/br_if.c#L412">new_nbp</a><strong>. </strong>The <a href="https://github.com/torvalds/linux/blob/63bdf4284c38a48af21745ceb148a087b190cd21/net/bridge/br_private.h#L229">net_bridge_port</a> contains kobject which is initialized and added under net_device kboject by calling kobject_init_and_add<strong>. </strong>The<strong> </strong>macro SYSFS_BRIDGE_PORT_ATTR<strong> </strong>is brport<strong>. </strong>We can check this addition under sysfs.</p><pre># ls -la /sys/class/net/<strong>veth10/brport/</strong><br>total 0<br>drwxr-xr-x 2 root root    0 Mar 22 02:05 .<br>drwxr-xr-x 6 root root    0 Mar 22 02:04 ..<br>-rw-r--r-- 1 root root 4096 Mar 23 23:31 bpdu_guard<br>lrwxrwxrwx 1 root root    0 Mar 22 02:10 bridge -&gt; ../../br0<br>-r--r--r-- 1 root root 4096 Mar 23 23:31 change_ack<br>-r--r--r-- 1 root root 4096 Mar 23 23:31 config_pending<br>-r--r--r-- 1 root root 4096 Mar 23 23:31 designated_bridge<br>-r--r--r-- 1 root root 4096 Mar 23 23:31 designated_cost<br>...</pre><p><a href="https://github.com/torvalds/linux/blob/b71acb0e372160167bf6d5500b88b30b52ccef6e/net/bridge/br_input.c#L213">br_handle_frame</a> is a callback registered in the net_device interface. So that every packet received on this interface is handled by bridge code.</p><blockquote><strong>Life of packet inside the birdge</strong></blockquote><pre># brctl show br0<br>bridge name bridge id  STP enabled interfaces<br>br0  8000.865ee85c4139 no  veth10<br>                           veth30</pre><p>Let us create a network namespace and move one end of veth pair to into namespace.</p><pre>#ip netns add ns1<br>#ip netns add ns2<br>#ip link set veth20 netns ns1<br>#ip link set veth40 netns ns2</pre><p>Now set up interface IP inside the namespaces</p><pre>#ip link set br0 up<br>#ip link set veth10 up<br>#ip link set veth30 up<br>#ip netns exec ns1 ip link set veth20 up<br>#ip netns exec ns2 ip link set veth40 up</pre><p>Assign IP’s to interfaces in the namespace ns1 and ns2</p><pre>#ip netns exec ns1 ip addr add dev veth20 192.168.56.1/24<br>#ip netns exec ns2 ip addr add dev veth40 192.168.56.2/24</pre><p>With the interfaces and IP address setup, we can try to see if there is connectivity.</p><pre>$ip netns exec ns1 ping -c 1 192.168.56.2<br>PING 192.168.56.2 (192.168.56.2) 56(84) bytes of data.</pre><pre>--- 192.168.56.2 ping statistics ---<br>1 packets transmitted, 0 received, 100% packet loss, time 0ms</pre><p>Here I have run the Ping from the network namespace ns1 to reach the interface on network namespace ns2 . But I don’t see ICMP response. Running a tcpdump on br0 shows that ICMP request reached bridge but there is no ICMP response.</p><pre>$tcpdump -qnni br0<br>tcpdump: verbose output suppressed, use -v or -vv for full protocol decode<br>listening on br0, link-type EN10MB (Ethernet), capture size 262144 bytes<br>15:04:47.431771 IP 192.168.56.1 &gt; 192.168.56.2: ICMP echo request, id 1573, seq 1, length 64<br>15:04:52.561271 ARP, Request who-has 192.168.56.2 tell 192.168.56.1, length 28<br>15:04:52.561315 ARP, Reply 192.168.56.2 is-at 76:35:3c:05:68:ea, length 28</pre><p>So it seems like the bridge is not forwarding the packet to other port. Will run ftrace on bridge code to see what is happening.</p><pre>$cd /sys/kernel/debug/tracing<br>$echo br* &gt; set_ftrace_filter<br>$echo function_graph &gt; current_tracer<br>$echo 1 &gt; tracing_on ; ip netns exec ns1 ping -c 1 192.168.56.2 ; echo 0 &gt; tracing_on</pre><p>Here I have set ftrace filter to show only bridge functions by setting br* . This tracing output shows the last bridge function the packet was handled is inbr_nf_forward_ip .</p><pre> 1)               |  br_handle_frame [bridge]() {<br> 1)               |    br_nf_pre_routing [br_netfilter]() {</pre><pre>...</pre><pre> 1)               |            br_forward [bridge]() {<br> 1)   0.149 us    |              br_allowed_egress [bridge]();<br> 1)   0.141 us    |              br_handle_vlan [bridge]();<br><strong> 1)               |              br_nf_forward_ip [br_netfilter]() {<br> 1)   0.198 us    |                br_validate_ipv4.isra.30 [br_netfilter]();<br> 1)   0.147 us    |                brnf_get_logical_dev.isra.27 [br_netfilter]();</strong><br> 1)   7.276 us    |              }</pre><pre>...</pre><pre> 1) + 44.181 us   |  }</pre><p>Looking at the <a href="https://github.com/torvalds/linux/blob/1a9df9e29c2afecf6e3089442d429b377279ca3c/net/bridge/br_netfilter_hooks.c#L608">br_nf_forward_ip</a> code the packet is handled by NF_INET_FORWARD. If the packet was forwarded we would have seen br_nf_forward_finish in ftrace output. So it means that the packet was dropped in the FORWARD chain.</p><pre>static unsigned int br_nf_forward_ip(void *priv,<br>				     struct sk_buff *skb,<br>				     const struct nf_hook_state *state)<br>{<br>	...<br><br>	<strong>NF_HOOK(pf, NF_INET_FORWARD, state-&gt;net, NULL, skb,<br>		brnf_get_logical_dev(skb, state-&gt;in),<br>		parent,	br_nf_forward_finish);</strong><br><br>	return NF_STOLEN;<br>}</pre><p>So there are two options either we add Iptables rule to allow these packets or completely disable Netfilter calling Iptables. For the sake of simplicity, we will disable Iptables. There is a sysctl to disable this.</p><pre>$sysctl net.bridge.bridge-nf-call-iptables<br>net.bridge.bridge-nf-call-iptables = 1<br>$sysctl -w net.bridge.bridge-nf-call-iptables=0<br>net.bridge.bridge-nf-call-iptables = 0</pre><p>We will run the same ping command from network namespace again and check if there is an ICMP response.</p><pre>$ echo 1 &gt; tracing_on ; ip netns exec ns1 ping -c 1 192.168.56.2 ; echo 0 &gt; tracing_on<br>PING 192.168.56.2 (192.168.56.2) 56(84) bytes of data.<br>64 bytes from 192.168.56.2: icmp_seq=1 ttl=64 time=0.065 ms</pre><pre>--- 192.168.56.2 ping statistics ---<br>1 packets transmitted, 1 received, 0% packet loss, time 0ms<br>rtt min/avg/max/mdev = 0.065/0.065/0.065/0.000 ms</pre><p>Now we see the response for ICMP request. The ftrace output for this ICMP request shows the function graph of bridge code. Let us look more into these functions.</p><pre> 0)               |  br_handle_frame [bridge]() {<br> 0)   0.203 us    |    br_nf_pre_routing [br_netfilter]();<br> 0)               |    br_handle_frame_finish [bridge]() {<br> 0)   0.192 us    |      br_allowed_ingress [bridge]();<br> 0)   0.962 us    |      br_fdb_update [bridge]();<br> 0)   0.291 us    |      br_fdb_find_rcu [bridge]();<br> 0)               |      br_forward [bridge]() {<br> 0)   0.187 us    |        br_allowed_egress [bridge]();<br> 0)   0.186 us    |        br_handle_vlan [bridge]();<br> 0)   0.186 us    |        br_nf_forward_ip [br_netfilter]();<br> 0)   0.184 us    |        br_nf_forward_arp [br_netfilter]();<br> 0)               |        br_forward_finish [bridge]() {<br> 0)   0.713 us    |          br_nf_post_routing [br_netfilter]();<br> 0)   1.049 us    |          br_dev_queue_push_xmit [bridge]();<br> 0)   2.391 us    |        }<br> 0)   4.364 us    |      }<br> 0)   6.833 us    |    }<br> 0)   7.761 us    |  }</pre><p>br_dev_queue_push_xmit is the last call which forwards the packet to destination interface.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=771ee75bdf67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding how Linux pipe works]]></title>
            <link>https://medium.com/@ravi.eticala/understanding-how-linux-pipe-works-9a5565ed26e9?source=rss-19bb84469948------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a5565ed26e9</guid>
            <category><![CDATA[pipes]]></category>
            <category><![CDATA[system-call]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[kernel]]></category>
            <dc:creator><![CDATA[Ravi Kiran Eticala]]></dc:creator>
            <pubDate>Sat, 16 Mar 2019 01:46:14 GMT</pubDate>
            <atom:updated>2019-03-16T01:46:14.561Z</atom:updated>
            <content:encoded><![CDATA[<p>Pipe allows sending the data unidirectionally from one process to the other process.</p><p>Let&#39;s consider an example which shows what happens to file descriptors <strong>0(stdin),1(stdout),2(stderr) </strong>of processes when we run using a pipe “|” on bash shell.</p><pre>$ sleep 30 | sleep 60 &amp;</pre><pre>[1] 5695</pre><pre>$ps -ef | grep sleep</pre><pre>vagrant   <strong>5694</strong>  5365  0 03:57 pts/1    00:00:00 <strong>sleep 30</strong></pre><pre>vagrant  <strong> 5695</strong>  5365  0 03:57 pts/1    00:00:00 <strong>sleep 60</strong></pre><p>Two new processes are created. The first process with PID 5694 is running “sleep 30” and the second process “sleep 60” is running with PID 5695</p><p>Let&#39;s look at what the file descriptors of these processes are pointing to</p><pre>$ ls -la /proc/5694/fd/</pre><pre>total 0</pre><pre>dr-x------. 2 vagrant vagrant  0 Mar  8 03:57 .</pre><pre>dr-xr-xr-x. 9 vagrant vagrant  0 Mar  8 03:57 ..</pre><pre>lrwx------. 1 vagrant vagrant 64 Mar  8 03:57 0 -&gt; /dev/pts/1</pre><pre><strong>l-wx------. 1 vagrant vagrant 64 Mar  8 03:57 1 -&gt; pipe:[33199]</strong></pre><pre>lrwx------. 1 vagrant vagrant 64 Mar  8 03:57 2 -&gt; /dev/pts/1</pre><p>PID 5694 (sleep 30) file descriptor 0(stdin) is a link to pseudoterminal /dev/pts/1 . But the FD 1(stdout) is pointing to pipe:[33199] which has write permission.</p><pre>[vagrant@localhost ~]$ ls -la /proc/5695/fd/</pre><pre>total 0</pre><pre>dr-x------. 2 vagrant vagrant  0 Mar  8 03:57 .</pre><pre>dr-xr-xr-x. 9 vagrant vagrant  0 Mar  8 03:57 ..</pre><pre><strong>lr-x------. 1 vagrant vagrant 64 Mar  8 03:57 0 -&gt; pipe:[33199]</strong></pre><pre>lrwx------. 1 vagrant vagrant 64 Mar  8 03:57 1 -&gt; /dev/pts/1</pre><pre>lrwx------. 1 vagrant vagrant 64 Mar  8 03:57 2 -&gt; /dev/pts/1</pre><p>Similarly PID 5695 (sleep 60) file descriptor 0(stdin) is an link to pipe:[33199] with read permission. The read and write permissions are set by the pipe system call. We will look more about permissions later in the article.</p><p>This means bash is interpreting the commands/pipe and changing the stdin of PID 5695 and stdout of PID 5694 to point to unnamed PIPE.</p><blockquote>STRACE</blockquote><pre>$ strace -f bash -c &quot;sleep 30 | sleep 60&quot; </pre><p>Here we are running the same command but using “strace” and “bash -c”. This allows us to trace how “bash” is creating a pipe, changing the stdin and stdout of the child processes.</p><p>The important system calls to look for in strace output are execve, clone, pipe, dup2, close.</p><pre>execve(&quot;/usr/bin/bash&quot;, [&quot;bash&quot;, &quot;-c&quot;, &quot;sleep 30 | sleep 60&quot;], [/* 25 vars */]) = 0</pre><p>The strace output starts with the <strong>execve</strong> system call running the <strong>“bash -c “sleep 30 | sleep 60” ”</strong></p><pre>...</pre><pre>rt_sigprocmask(SIG_BLOCK, NULL, [], 8)  = 0<br>rt_sigprocmask(SIG_BLOCK, [CHLD], [], 8) = 0<br><strong>pipe([3, 4])                            = 0</strong><br>rt_sigprocmask(SIG_BLOCK, [INT CHLD], [CHLD], 8) = 0<br><strong>clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f8cf6effa10) = 5694</strong><br>rt_sigprocmask(SIG_SETMASK, [CHLD], NULL, 8) = 0<br>close(4)                                = 0<br>close(4)                                = -1 EBADF (Bad file descriptor)<br>rt_sigprocmask(SIG_BLOCK, [INT CHLD], [CHLD], 8) = 0<br><strong>clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f8cf6effa10) = 5695</strong><br>rt_sigprocmask(SIG_SETMASK, [CHLD], NULL, 8) = 0<br>close(3)                                = 0<br>rt_sigprocmask(SIG_BLOCK, [CHLD], [CHLD], 8) = 0<br>rt_sigprocmask(SIG_SETMASK, [CHLD], NULL, 8) = 0<br>rt_sigprocmask(SIG_BLOCK, [CHLD], [CHLD], 8) = 0<br>rt_sigaction(SIGINT, {0x43e750, [], SA_RESTORER, 0x7f8cf6523280}, {SIG_DFL, [], SA_RESTORER, 0x7f8cf6523280}, 8) = 0<br><strong>wait4(-1,</strong> strace: Process 5694 attached</pre><pre>...</pre><p>Here the parent bash process is calling the <a href="http://man7.org/linux/man-pages/man2/pipe.2.html"><em>pipe</em></a> system call. This creates two new file descriptors [3,4]. FD 3 refers to read end of the pipe and FD 4 refers to write end of the pipe.</p><p>The bash program calls clone twice. The two clone system call creates a first child process with PID 5694 and second child process with PID 5695 and runs <a href="http://man7.org/linux/man-pages/man2/wait4.2.html">wait4</a>.</p><pre>[pid  5694] rt_sigaction(SIGTTOU, {SIG_DFL, [], SA_RESTORER, 0x7f8cf6523280}, {SIG_DFL, [], 0}, 8) = 0<br><strong>[pid  5694] close(3)                    = 0<br>[pid  5694] dup2(4, 1)                  = 1<br>[pid  5694] close(4)                    = 0<br></strong>[pid  5694] stat(&quot;.&quot;, {st_mode=S_IFDIR|0700, st_size=113, ...}) = 0</pre><pre>...</pre><pre>[pid  5694] rt_sigaction(SIGCHLD, {SIG_DFL, [], SA_RESTORER|SA_RESTART, 0x7f8cf6523280}, {0x4412e0, [], SA_RESTORER|SA_RESTART, 0x7f8cf6523280}, 8) = 0<br><strong>[pid  5694] execve(&quot;/usr/bin/sleep&quot;, [&quot;sleep&quot;, &quot;30&quot;], [/* 24 vars */]) = 0</strong><br>[pid  5694] brk(NULL)                   = 0x6bd000</pre><pre>...</pre><p>The process with PID 5694 which is about to exec “sleep 30” has closed the FD “3” with close(3) system call i.e the read end of the pipe. <a href="http://man7.org/linux/man-pages/man2/dup.2.html"><strong>dup2</strong></a><strong>(4, 1)</strong> would copy of FD 4 to FD 1(stdout) and closed FD 4. At this point, the PID 5694 process would have file descriptors</p><pre>0 -&gt; /dev/pts/1<br>1 -&gt; pipe:[33199]<br>2 -&gt; /dev/pts/1</pre><p>Continuing with strace</p><pre>...</pre><pre>[pid  5695] rt_sigaction(SIGTTOU, {SIG_DFL, [], SA_RESTORER, 0x7f8cf6523280}, {SIG_DFL, [], 0}, 8) = 0<br><strong>[pid  5695] dup2(3, 0)                  = 0<br>[pid  5695] close(3)                    = 0</strong><br>[pid  5695] stat(&quot;.&quot;, {st_mode=S_IFDIR|0700, st_size=113, ...}) = 0</pre><pre>...</pre><pre>[pid  5695] rt_sigaction(SIGCHLD, {SIG_DFL, [], SA_RESTORER|SA_RESTART, 0x7f8cf6523280}, {0x4412e0, [], SA_RESTORER|SA_RESTART, 0x7f8cf6523280}, 8) = 0<br><strong>[pid  5695] execve(&quot;/usr/bin/sleep&quot;, [&quot;sleep&quot;, &quot;60&quot;], [/* 24 vars */]) = 0</strong><br>[pid  5695] brk(NULL)                   = 0x2081000</pre><pre>...</pre><p>The child process 5695 runs <a href="http://man7.org/linux/man-pages/man2/dup.2.html"><strong>dup2</strong></a><strong>(3, 0) </strong>so that read end of the pipe is copied to 0 (stdin) and closes FD 3. At this point the file descriptors of second child process are</p><pre>0 -&gt; pipe:[33199]<strong><br></strong>1 -&gt; /dev/pts/1<br>2 -&gt; /dev/pts/1</pre><p>So bash shell is using pipe and dup2 to change the stdin, stdout of the child process it creates. But how is pipe system call implemented to move data from write end to read end?</p><blockquote>System Call</blockquote><p><strong>pipe</strong></p><p>Pipe file descriptors [3,4] are used in Write and Read system calls which are controlled by VFS (Virtual file system). So the pipe should be implemented as a file system.</p><p>We can verify it by</p><pre># grep pipe /proc/filesystems<br><strong>nodev pipefs<br></strong>nodev rpc_pipefs</pre><p>Let us look at how the pipefs filesystem is created and the pipe system call works</p><p><strong>Ftrace of Pipe System call</strong></p><p>This is <a href="https://www.kernel.org/doc/html/v4.18/trace/ftrace.html">ftrace</a> output for pipe system call. We will look into some of these kernel functions __do_pipe_flags, create_pipe_files, alloc_pipe_info, fd_install</p><pre>bash-3667  [001] .... 102481.956599: SyS_pipe &lt;-system_call_fastpath<br>bash-3667  [001] .... 102481.956599: SyS_pipe2 &lt;-SyS_pipe<br>bash-3667  [001] .... 102481.956600: <strong>__do_pipe_flags</strong> &lt;-SyS_pipe2<br>bash-3667  [001] .... 102481.956600: <strong>create_pipe_files</strong> &lt;-__do_pipe_flags<br>bash-3667  [001] .... 102481.956600: new_inode_pseudo &lt;-create_pipe_files<br>bash-3667  [001] .... 102481.956600: alloc_inode &lt;-new_inode_pseudo</pre><pre>...</pre><pre>bash-3667  [001] .... 102481.956605: <strong>alloc_pipe_info</strong> &lt;-create_pipe_files</pre><pre>...</pre><p><a href="https://github.com/torvalds/linux/blob/ebc551f2b8f905eca0e25c476c1e5c098cd92103/fs/pipe.c#L1192">Pipe file system initialization</a></p><pre>static <strong>struct file_system_type</strong> pipe_fs_type = {<br>	<strong>.name		= &quot;pipefs&quot;,</strong><br>	.mount		= pipefs_mount,<br>	.kill_sb	= kill_anon_super,<br>};</pre><pre>static int __init init_pipe_fs(void)<br>{<br>	int err = register_filesystem(&amp;pipe_fs_type);</pre><pre>...</pre><pre>return err;<br>}</pre><pre><strong>fs_initcall(init_pipe_fs);</strong></pre><p>The file_system_type.name is “pipefs”, it is the same as what we saw in /proc/filesystem. fs_initcall() calls the pipefs initialization function from <a href="https://github.com/torvalds/linux/blob/a667cb7a94d48a483fb5d6006fe04a440f1a42ce/init/main.c">kernel_start</a> <a href="https://github.com/torvalds/linux/blob/a667cb7a94d48a483fb5d6006fe04a440f1a42ce/init/main.c#L951">do_initcalls</a>. <a href="https://github.com/torvalds/linux/blob/ebc551f2b8f905eca0e25c476c1e5c098cd92103/fs/filesystems.c#L72">register_filesystem</a> registers the pipefs to VFS (Virtual Filesystem switch).</p><pre>static int do_pipe2(int __user *fildes, int flags)<br>{<br>	struct file *files[2];<br>	int fd[2];<br>	int error;<br><br>	error = <strong>__do_pipe_flags</strong>(fd, files, flags);<br>...<br>	return error;<br>}<br><br>SYSCALL_DEFINE2(pipe2, int __user *, fildes, int, flags)<br>{<br>	return <strong>do_pipe2(fildes, flags)</strong>;<br>}<br><br>SYSCALL_DEFINE1(pipe, int __user *, fildes)<br>{<br>	return <strong>do_pipe2(fildes, 0)</strong>;<br>}</pre><p>Both pipe and pipe2 syscalls call do_pipe2. The only difference is pipe2 forwards the flags option. In the strace output, we see pipe syscall.</p><pre>int <strong>create_pipe_files</strong>(struct file **res, int flags)<br>{<br>	struct inode *inode = get_pipe_inode();<br>	struct file *f;<br><br>	if (!inode)<br>		return -ENFILE;<br><br>	<strong>f = alloc_file_pseudo(inode, pipe_mnt, &quot;&quot;,<br>	      O_WRONLY | (flags &amp; (O_NONBLOCK | O_DIRECT)),... &amp;pipefifo_fops);</strong></pre><pre>...<br><br>	f-&gt;private_data = inode-&gt;i_pipe;<br><br><strong>	res[0] = alloc_file_clone(f, O_RDONLY | (flags &amp; O_NONBLOCK), &amp;pipefifo_fops);</strong></pre><pre>...</pre><pre>	<strong>res[0]-&gt;private_data = inode-&gt;i_pipe;<br>	res[1] = f;</strong><br>	return 0;<br>}<br><br>static int __do_pipe_flags(int *fd, struct file **files, int flags)<br>{<br>	int error;<br>	int fdw, fdr;<br><br>	if (flags &amp; ~(O_CLOEXEC | O_NONBLOCK | O_DIRECT))<br>		return -EINVAL;<br><br>	error = <strong>create_pipe_files(files, flags)</strong>;<br>	if (error)<br>		return error;<br><br>...</pre><pre>	return error;<br>}</pre><pre>const struct file_operations pipefifo_fops = {<br>	.open		= fifo_open,<br>	.llseek		= no_llseek,<br>	.read_iter	= pipe_read,<br>	.write_iter	= pipe_write,<br>	.poll		= pipe_poll,<br>	.unlocked_ioctl	= pipe_ioctl,<br>	.release	= pipe_release,<br>	.fasync		= pipe_fasync,<br>};</pre><p>The __do_pipe_flags creates the struct files and new pipe file descriptors for the calling user process and returns 0 if there are no errors. <a href="https://github.com/torvalds/linux/blob/ebc551f2b8f905eca0e25c476c1e5c098cd92103/fs/pipe.c#L798">__do_pipe_flags</a> calls create_pipe_files which creates a struct inode* and two struct file* for the same inode. Here the interesting thing to observe is one struct file* is created by calling alloc_file_pseudo with O_WRONLY flag and another struct file* by calling alloc_file_clone of the same file with O_RDONLY flag. This means that the pipe fd’s returned to userspace refers to the two ends of the pipe. fd[0] refers to the read end of the pipe and fd[1] refers to write end of the pipe as discussed earlier.</p><p><strong>pipefifo_fops</strong> is a type of struct file_operations passed to both alloc_file_pseudo and alloc_file_clone which provides functions to be called for read, write, close system calls.</p><p><strong>Pipe buffer</strong></p><pre>struct pipe_inode_info *alloc_pipe_info(void)<br>{<br>	struct pipe_inode_info *pipe;<br>	unsigned long pipe_bufs = PIPE_DEF_BUFFERS;<br>	struct user_struct *user = get_current_user();<br>	unsigned long user_bufs;<br>	unsigned int max_size = READ_ONCE(<strong>pipe_max_size</strong>);<br><br>...</pre><pre>        if (<strong>pipe_bufs * PAGE_SIZE &gt; max_size</strong> &amp;&amp; !capable(CAP_SYS_RESOURCE))<br>		pipe_bufs = max_size &gt;&gt; <strong>PAGE_SHIFT</strong>;</pre><pre>...</pre><pre>	<strong>pipe-&gt;bufs = kcalloc(pipe_bufs, sizeof(struct pipe_buffer),<br>			     GFP_KERNEL_ACCOUNT);</strong><br><br>	if (pipe-&gt;bufs) {<br>		init_waitqueue_head(&amp;pipe-&gt;wait);<br>		pipe-&gt;r_counter = pipe-&gt;w_counter = 1;<br>		pipe-&gt;buffers = pipe_bufs;<br>		pipe-&gt;user = user;<br>		mutex_init(&amp;pipe-&gt;mutex);<br>		return pipe;<br>	}<br>...</pre><pre>}</pre><p>alloc_pipe_info creates struct pipe_info_node and allocates the memory for pipe buffers based on thresholds. <a href="https://github.com/torvalds/linux/blob/ebc551f2b8f905eca0e25c476c1e5c098cd92103/include/linux/pipe_fs_i.h#L5">PIPE_DEF_BUFFERS</a> is a macro defined as 16 and PAGE_SIZE varies based on the system config. We can run getconf to get the PAGE_SIZE</p><pre># getconf  PAGE_SIZE<br>4096</pre><p>pipe_max_size can be changed with sysctl. By default, it is 1MBytes.</p><pre># sysctl fs.pipe-max-size<br>fs.pipe-max-size = 1048576</pre><p>In this case, PIPE_DEF_BUFFERS * PAGE_SIZE is less than pipe-max-size, so kcalloc() creates a 16 * sizeof(struct pipe_buffer) of memory as pipe buffer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a5565ed26e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>