<?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 M Castelino on Medium]]></title>
        <description><![CDATA[Stories by M Castelino on Medium]]></description>
        <link>https://medium.com/@mcastelino?source=rss-36333dae6058------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QwhTFhfOf9PVj5jcDi14nA@2x.jpeg</url>
            <title>Stories by M Castelino on Medium</title>
            <link>https://medium.com/@mcastelino?source=rss-36333dae6058------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 20:40:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mcastelino/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[Kubernetes Pod Monitors & Re-Labeling — Managing Cardinality]]></title>
            <link>https://medium.com/kubehells/kubernetes-pod-monitors-re-labeling-managing-cardinality-6d38eea748d6?source=rss-36333dae6058------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d38eea748d6</guid>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[metrics-and-analytics]]></category>
            <category><![CDATA[timeseries]]></category>
            <dc:creator><![CDATA[M Castelino]]></dc:creator>
            <pubDate>Sun, 31 Jan 2021 17:37:45 GMT</pubDate>
            <atom:updated>2021-01-31T17:37:45.565Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kubernetes Pod Monitors &amp; Re-Labeling — Managing Cardinality</h3><p>The Prometheus operator offers a simple method to scrape metrics from any Pod. However in many cases the Pod itself is not what you are monitoring; but the Pod is used to expose metrics that relate to the Node. In such cases what the user cares about is the Node on which the Pod runs, and not the Pod itself. This is specially true in the case of daemonsets where Pods do not have a stable identify.</p><p>By default when using <a href="https://github.com/prometheus-operator/prometheus-operator/blob/master/Documentation/user-guides/getting-started.md#include-podmonitors">PodMonitor </a>all the time series data will have the instance label set to the Pod&#39;s name. Also there is no instance label associated with the timeseries. <strong>This means that the user will need to perform the mapping between the Pod and the Node on which it ran, which is not easy</strong>.</p><p>If a metrics collectors are updated, deleted, redeployed the number of time series associated with a given metric increases significantly. This <strong>increases</strong> <a href="https://blog.timescale.com/blog/what-is-high-cardinality-how-do-time-series-databases-influxdb-timescaledb-compare/"><strong>cardinality</strong></a><strong> </strong>putting excessive pressure on the timeseries database. This can be avoided easily.</p><h4>Prometheus Relabeling</h4><p>Prometheus allows the instance name (among other labels) to be relabeled in a very simple manner as shown below using relabelings.</p><pre>apiVersion: monitoring.coreos.com/v1<br>kind: PodMonitor<br>metadata:<br>  name: mycollector<br>  labels:<br>    k8s-app: mycollector<br>    type: mytype<br>spec:<br>  selector:<br>    matchLabels:<br>      k8s-app: mycollector<br>  namespaceSelector:<br>    matchNames:<br>    - mynamespace<br>  podMetricsEndpoints:<br>  - port: exporter<br>    interval: 10s<br><strong>    relabelings:<br>    - action: replace<br>      sourceLabels:<br>      - __meta_kubernetes_pod_node_name<br>      targetLabel: instance</strong></pre><p>Here we specify that original label instance be replaced by __meta_kubernetes_pod_node_name. __meta_kubernetes_pod_node_name is the name of the node the pod is scheduled onto. Many such built in meta data objects are available in Prometheus, which can help you modify appropriate labels to make them more <strong>meaningful or invariant</strong>. The full list of such meta data is available in <a href="https://prometheus.io/docs/prometheus/latest/configuration/configuration/#pod">Prometheus documentation</a>.</p><h4>Dropping Labels</h4><p>Furthermore you should always try and drop any and all metrics that you will not care about to further reduce cardinality. <a href="https://github.com/prometheus-operator/kube-prometheus/tree/808c2f8c3d760c7c02ab4ef1b41987da83d54f90/manifests">Kube-prometheus</a> has some very good examples of dropping both metrics and labels.</p><pre>metricRelabelings:<br>    - action: drop<br>      regex: container_(network_tcp_usage_total|network_udp_usage_total|tasks_state|cpu_load_average_10s)<br>      sourceLabels:<br>      - __name__</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d38eea748d6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kubehells/kubernetes-pod-monitors-re-labeling-managing-cardinality-6d38eea748d6">Kubernetes Pod Monitors &amp; Re-Labeling — Managing Cardinality</a> was originally published in <a href="https://medium.com/kubehells">Kubehells</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pandas, Elasticsearch and Aggregations]]></title>
            <link>https://medium.com/kubehells/pandas-elasticsearch-and-aggregations-28f9074a4dd2?source=rss-36333dae6058------2</link>
            <guid isPermaLink="false">https://medium.com/p/28f9074a4dd2</guid>
            <category><![CDATA[aggregation]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python-matplotlib]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[pandas-dataframe]]></category>
            <dc:creator><![CDATA[M Castelino]]></dc:creator>
            <pubDate>Sun, 31 Jan 2021 17:16:26 GMT</pubDate>
            <atom:updated>2021-01-31T17:16:26.824Z</atom:updated>
            <content:encoded><![CDATA[<p>Pandas is good at handling large volumes of data. However there is always an upper limit. What if you are looking for summary statistics for an extremely large data set and your narrowest window of analysis is known.</p><p>Do you want to look at all the data? Probably not.</p><blockquote>Narrowest window here means that you do not need to break down the data below a specific granularity. You may not care the exact time something happened, but you care if it happened on a particular month, day, hour or minute.</blockquote><p>In that case you can use Pandas to build aggregations and visualizations for the higher level analysis, while leveraging the aggregation capabilities of an existing data store. Using <a href="https://elasticsearch-dsl.readthedocs.io/en/latest/search_dsl.html">Elasticsearch</a> as an example to show how this can be done.</p><p>Elasticsearch is very good at performing aggregations over extremely large index patterns (billions of documents). Aggregations in elasticsearch complete in seconds. If all of the raw data was extracted into Pandas, not only would the dataframe get too large; the time to ingest the data would be significant. Also aggregations can serve as a form of data cleanup, given the right search parameters.</p><h4>Elasticsearch Aggregation</h4><p>Using the example below, we are aggregating a <a href="https://elasticsearch-dsl.readthedocs.io/en/latest/search_dsl.html">search</a> looking for the occurrence of a specific pattern and then aggregating it over several categories.</p><p><strong>Note the use of the <em>date_histogram </em>and its granularity. </strong>Here we are reducing the narrowest window of observability to a day. This can be adjusted based on the need to be higher or lower.</p><pre>from elasticsearch_dsl import Search, Q</pre><pre>def Q1(type, key, val):<br> return Q(type, **{key: val})</pre><pre>def query_aggregation(start_time, end_time, buckets):<br> <strong>q = Q1(&#39;match_phrase&#39;, &#39;log&#39;, &#39;foo saw bar&#39;)<br> </strong>t = Q1(&#39;range&#39;, &#39;<a href="http://twitter.com/timestamp">@timestamp</a>&#39;, {&quot;gte&quot;: start_time, &quot;lte&quot;: end_time})<br> s = Search(using=ES, index=index).query(q).filter(t)<br> s = s[:0]<br> s.aggs.bucket(&#39;<strong>domains</strong>&#39;, &#39;terms&#39;, field=&#39;domain.keyword&#39;, size=buckets)\<br>  .bucket(&#39;<strong>zones</strong>&#39;, &#39;terms&#39;, field=&#39;zone.keyword&#39;, size=buckets)\<br>  .bucket(&#39;<strong>regions</strong>&#39;, &#39;terms&#39;, field=&#39;region.keyword&#39;, size=buckets)\<br>  <strong>.bucket(&#39;days&#39;, &#39;date_histogram&#39;, field=&#39;</strong><a href="http://twitter.com/timestamp"><strong>@timestamp</strong></a><strong>&#39;, calendar_interval=&#39;1d&#39;)<br>  </strong>s = s.execute()<br>  return s.aggregations.domains.buckets</pre><h4>Pandas Dataframe</h4><p>You can then easily run the query over a large time window and create a dataframe. The data frame can then be used to perform second level aggregations or to create derivative dataframes or columns.</p><pre>import numpy as np<br>import pandas as pd</pre><pre>data = []</pre><pre>for domain in <strong>query_aggregation(now-30d, now, 1000)</strong>:<br> for zone in domain.zones.buckets:<br>  for region in zone.regions.buckets:<br>   for day in region.days.buckets:<br>    data.append([domain.key, zone.key, region.key, day.key, day.doc_count]) <br>                    <br>df = pd.DataFrame(data, columns = [&#39;Domain&#39;, &#39;Zone&#39;, &#39;Region&#39;, &#39;Day&#39;, &#39;Count&#39;])</pre><p>This also allows you to perform rich visualizations not possible in Kibana or Grafana with minimal effort. Given that aggregations are relatively cheap in Elasticsearch, this allows you to build real-time responsive dashboards and analyze trends.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28f9074a4dd2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kubehells/pandas-elasticsearch-and-aggregations-28f9074a4dd2">Pandas, Elasticsearch and Aggregations</a> was originally published in <a href="https://medium.com/kubehells">Kubehells</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes from first principles]]></title>
            <link>https://medium.com/kubehells/kubernetes-from-first-principles-b8ebb33bbee9?source=rss-36333dae6058------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8ebb33bbee9</guid>
            <category><![CDATA[coredns]]></category>
            <category><![CDATA[kubernetes-controller]]></category>
            <category><![CDATA[kubelet]]></category>
            <category><![CDATA[kube-proxy]]></category>
            <category><![CDATA[kubernetes-networking]]></category>
            <dc:creator><![CDATA[M Castelino]]></dc:creator>
            <pubDate>Sat, 30 Jan 2021 22:10:27 GMT</pubDate>
            <atom:updated>2021-01-30T23:38:24.086Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kubernetes and Networking from first principles</h3><p>Its been some time since I wrote the <a href="https://medium.com/@mcastelino/kubernetes-resource-management-deep-dive-b337ba15359c">Kubernetes Resource Management</a> Deep dive. In this post I wanted to reduce Kubernetes to it very bare bones ignoring all the scaffolding introduced by various controllers and higher level abstractions and focus on the building blocks with specific focus on how networking works without networking being totally within the purview of core Kubernetes.</p><p>What is the core of Kubernetes once you strip everything way. It is just the few basic constructs in <strong>etcd</strong></p><ul><li>Pod</li><li>Endpoint</li><li>Service</li><li>Node</li></ul><p>Managed and accessed by</p><ul><li>Kubelet</li><li>Kube-proxy</li><li>Scheduler</li><li>Controller</li><li>Apiserver</li><li>Coredns</li></ul><p><strong>Quick overview</strong></p><p>etcd is used to create and update Pods, Endpoints, Services and Nodes. Everything else else is built on top of these core objects. etcd is always accessed via the apiserver making etcd pluggable/replaceable. Networking is not part of core Kubernetes which shows how flexible and modular it is.</p><ul><li>When Kubelet starts, it registers the node in etcd with its available resources (At which point the controller <strong>may </strong>assign its Node.Spec.PodCIDR. This is optional and global IPAM can handle this independent of Kubernetes)</li><li>Once the controller and scheduler decide how and where to manifest a Pod it is written to etcd</li><li>Each Kubelet watches for Pods that have been assigned to its node and creates them (via a configured container runtime)</li><li>When the container runtime creates the Pod it will call into a CNI plugin to create the Pod. The CNI plugin returns back the IP address of the Pod (using either a host-local or global IPAM). Notice here the decoupling of the actual IP address management from core Kubernetes.</li><li>The allocated IP address is passed back to Kubelet and registered in etcd against the <a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.19/#podip-v1-core">podIP</a> field. Notice here that a Pod can have one IPv4 and one IPv6 address. But this does not limit how many interfaces and IPs can be within a Pod, and we will explore that a bit later.</li></ul><blockquote>Also note that the Cluster DNS IP setup within each Pod and is fixed to <strong>10.96.0.10</strong>. (This is important as this allows both the DNS as well and CNI to be decoupled from core kubernetes). This also allows for inception where Coredns which needs networking created by CNI can be decoupled from CNI.</blockquote><ul><li>At this point we have a Pod with certain <strong>labels </strong>associated with it based on whom or which controller created it.</li></ul><pre>kubectl apply -f <a href="https://k8s.io/examples/application/deployment.yaml">https://k8s.io/examples/application/deployment.yaml</a></pre><p>Examining the Pods created with specific fields of interest</p><pre><strong>kubectl get pods -o json | jq -r &#39;.items[] | [.metadata.name, .metadata.labels.app, .status.phase, .status.podIP, .status.qosClass, .spec.restartPolicy, .spec.preemptionPolicy, .spec.priority]&#39;</strong><br>[<br>  &quot;nginx-deployment-66b6c48dd5-2xwm2&quot;,<br>  &quot;nginx&quot;,<br>  &quot;Running&quot;,<br>  &quot;10.244.2.66&quot;,<br>  &quot;BestEffort&quot;,<br>  &quot;Always&quot;,<br>  &quot;PreemptLowerPriority&quot;,<br>  0<br>]<br>[<br>  &quot;nginx-deployment-66b6c48dd5-5lrcw&quot;,<br>  &quot;nginx&quot;,<br>  &quot;Running&quot;,<br>  &quot;10.244.1.61&quot;,<br>  &quot;BestEffort&quot;,<br>  &quot;Always&quot;,<br>  &quot;PreemptLowerPriority&quot;,<br>  0<br>]</pre><p><em>Now that a Pod has an IP assigned to it independent of Kubernetes; how do all the Pods in the cluster and external entities access this Pod.</em></p><p><strong>Kube-proxy </strong>is optional and pluggable and ensures traffic to and from the Pod is sent to the right Pod. Note, I mentioned Pod hence PodIP. All other network addresses are constructs out the scope of CNI.</p><p>It<em> is also decoupled from Coredns as well as CNI</em>. As seen above the Pod’s <strong>IP</strong> and <strong>labels</strong> are registered in etcd. This forms the foundation of everything networking.</p><pre><strong>kubectl expose deployment nginx-deployment</strong><br>service/nginx-deployment exposed</pre><pre><strong>kubectl get svc</strong><br>NAME               TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE<br>kubernetes         ClusterIP   10.96.0.1      &lt;none&gt;        443/TCP   4d19h<br>nginx-deployment   ClusterIP   10.96.23.127   &lt;none&gt;        80/TCP    6s<br><strong>kubectl get endpoints</strong><br>NAME               ENDPOINTS                       AGE<br>kubernetes         172.18.0.5:6443                 4d19h<br>nginx-deployment   10.244.1.61:80,10.244.2.66:80   19s</pre><pre><strong>kubectl get svc nginx-deployment -o json | jq -r &#39;.spec&#39;<br></strong>{<br>  &quot;clusterIP&quot;: &quot;10.96.23.127&quot;,<br>  &quot;ports&quot;: [<br>    {<br>      &quot;port&quot;: 80,<br>      &quot;protocol&quot;: &quot;TCP&quot;,<br>      &quot;targetPort&quot;: 80<br>    }<br>  ],<br>  &quot;selector&quot;: {<br><strong>    &quot;app&quot;: &quot;nginx&quot;<br></strong>  },<br>  &quot;sessionAffinity&quot;: &quot;None&quot;,<br><strong>  &quot;type&quot;: &quot;ClusterIP&quot;</strong><br>}</pre><pre><strong>kubectl get endpoints nginx-deployment -o json | jq -r &#39;.metadata.managedFields[].manager, .subsets[].addresses[].ip, .subsets[].addresses[].targetRef.name&#39;<br></strong>kube-controller-manager<br>10.244.1.61<br>10.244.2.66<br>nginx-deployment-66b6c48dd5-5lrcw<br>nginx-deployment-66b6c48dd5-2xwm2</pre><h4>Services and Endpoints</h4><p>The user/controllers normally create services which are just abstractions. The controller or user creates endpoints in etcd based on the service selector. The controller matches pods based on the service selector and creates and endpoints, and populates it using the IP’s found in the Pod’s in etcd.</p><p>In order to ensure that a Service does not expose Pods that are not ready it will wait till the <strong>Readiness and Liveness probe</strong> for the Pod to report that the Pod is ready.</p><blockquote>Readiness and liveness probes can be used in parallel for the same container. Using both can ensure that traffic does not reach a container that is not ready for it, and that containers are restarted when they fail.</blockquote><p>Now that we know how endpoints are populated its time to see how traffic is sent to the pod, without Kubernetes really handling networking.</p><p><strong>Coredns and Services and Endpoints</strong></p><p>Coredns has a <a href="https://coredns.io/plugins/kubernetes/">plugin </a>that registers to watch for services and endpoints. It then uses the service and endpoints to perform service to Cluster IP resolution. (Note: It may resolve a service to a list of Pod IP’s in the case of headless service). Pods use Coredns to get the IP to be used for a service.</p><p><strong>Kube-proxy and endpoints</strong></p><p>Kube-proxy watches etcd to look for endpoints and services. Whenever a service or endpoint is created or modified it updates the iptables/ipvs rules or any other method such that any traffic send to the Service IP is sent in a specified load balanced manner to the set of Pod IPs in the endpoint.</p><p>This also shows how Kube-proxy can be decoupled from CNI. In some cases for highly optimized traffic flows the two can be tightly coupled and share state.</p><p>The dump below show how a Cluster IP maps to PodIP using iptables setup by kube-proxy. (Quick primer on iptables <a href="https://gist.github.com/mcastelino/c38e71eb0809d1427a6650d843c42ac2">iptables-cheatsheet (github.com)</a>)</p><pre>-A KUBE-SERVICES ! -s 10.244.0.0/16 -d <strong>10.96.23.127/32</strong> -p tcp -m comment --comment &quot;<strong>default/nginx-deployment cluster IP</strong>&quot; -m tcp --dport 80 -j KUBE-MARK-MASQ</pre><pre>-A KUBE-SERVICES -d 10.96.23.127/32 -p tcp -m comment --comment &quot;default/nginx-deployment cluster IP&quot; -m tcp --dport 80 -j KUBE-SVC-WRNOD73BKRQH4VVX</pre><pre>-A KUBE-<strong>SVC</strong>-WRNOD73BKRQH4VVX -m comment --comment &quot;default/nginx-deployment&quot; -m statistic --mode random --probability 0.50000000000 -j KUBE-SEP-AJVPBNAAHRKWHBTA</pre><pre>-A KUBE-<strong>SVC</strong>-WRNOD73BKRQH4VVX -m comment --comment &quot;default/nginx-deployment&quot; -j KUBE-SEP-SFHBWI2PEUUOP232</pre><pre>-A KUBE-<strong>SEP</strong>-AJVPBNAAHRKWHBTA -s 10.244.1.61/32 -m comment --comment &quot;default/nginx-deployment&quot; -j KUBE-MARK-MASQ<br>-A KUBE-<strong>SEP</strong>-AJVPBNAAHRKWHBTA -p tcp -m comment --comment &quot;default/nginx-deployment&quot; -m tcp -j DNAT --to-destination 10.244.1.61:80<br><br>-A KUBE-<strong>SEP</strong>-SFHBWI2PEUUOP232 -s 10.244.2.66/32 -m comment --comment &quot;default/nginx-deployment&quot; -j KUBE-MARK-MASQ<br>-A KUBE-<strong>SEP</strong>-SFHBWI2PEUUOP232 -p tcp -m comment --comment &quot;default/nginx-deployment&quot; -m tcp -j DNAT --to-destination 10.244.2.66:80</pre><p><strong>Loadbalancers/NodePort</strong></p><p>By default a service is created as Type ClusterIP. The other types allows routing of traffic to Pod using Loadbalancers or NodePorts.</p><blockquote>Loadbalancers typically end up using NodePorts and in some cases limit the size of the Cluster based on the Loadbalancer limitations.</blockquote><p>This shows how just Nodes, Pods, Services and Endpoints are used to completely achieve everything every higher level concept in Kubernetes. We also saw how the simple Pod probes are used to actively manage traffic.</p><h3>Can a Kubernetes Pod have multiple interfaces and expose multiple IPs</h3><p>Because of how loosely coupled networking is in Kubernetes it is possible to create a Pod with a CNI or CNI plugin chain to create multiple interfaces with their own IP addresses even though the Pod spec only support a single IP address.</p><p>Only the Primary IP associated with <strong>eth0 </strong>is registered as the PodIP. The secondary IPs associated with the Pod can be stored in additional annotations in the Pod. These annotations can then be used by a plugin controller to create endpoints that map Service IP’s to these secondary IP addresses.</p><p>As we have seen that kube-proxy is decoupled completely from CNI and Pods. Kube-proxy will setup rules for secondary IP addresses just like it does for the Primary IP addresses. As long as the networking implementation has setup host routing such that the secondary IP’s are routable either at Pod level or network fabric level traffic to and from these secondary IP’s and interfaces will flow transparently across the cluster.</p><blockquote>This shows how the decoupling allows us to extend Kubernetes while keep the core constant.</blockquote><blockquote>This also allows implementations such as <a href="https://github.com/virtual-kubelet/virtual-kubelet">virtual kubelet</a> to add nodes to the cluster as long as they are conformant to the basic kubelet interface. All the rest of the typical components we expect to see like kube-proxy, containerd can be replaced by highly node specific implementations.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8ebb33bbee9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kubehells/kubernetes-from-first-principles-b8ebb33bbee9">Kubernetes from first principles</a> was originally published in <a href="https://medium.com/kubehells">Kubehells</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breakdown of kvmtool SLIRP Implementation]]></title>
            <link>https://mcastelino.medium.com/breakdown-of-kvmtool-slirp-implementation-df9bd35a65e6?source=rss-36333dae6058------2</link>
            <guid isPermaLink="false">https://medium.com/p/df9bd35a65e6</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[tcp-ip]]></category>
            <category><![CDATA[kvm]]></category>
            <dc:creator><![CDATA[M Castelino]]></dc:creator>
            <pubDate>Thu, 11 Apr 2019 04:30:33 GMT</pubDate>
            <atom:updated>2019-04-11T04:30:33.806Z</atom:updated>
            <content:encoded><![CDATA[<h3>invocation</h3><pre>./lkvm run --kernel bzImage --disk rootfs.ext4 --debug --network mode=user</pre><h3>Inside the VM</h3><pre>ip addr add 192.168.33.2/24 dev enp0s0<br>ip link set up enp0s0<br>ip route add default via 192.168.33.1</pre><p>Now you can reach the host</p><h3>Implementation</h3><h3>Setup</h3><pre>837         ndev = calloc(1, sizeof(struct net_dev));<br>841         ops = malloc(sizeof(*ops));<br>847         list_add_tail(&amp;ndev-&gt;list, &amp;ndevs);<br>849         ndev-&gt;kvm = params-&gt;kvm;<br>850         ndev-&gt;params = params;<br>852         mutex_init(&amp;ndev-&gt;mutex);<br>853         ndev-&gt;queue_pairs = max(1, min(VIRTIO_NET_NUM_QUEUES, params-&gt;mq));<br>854         ndev-&gt;config.status = VIRTIO_NET_S_LINK_UP;<br>855         if (ndev-&gt;queue_pairs &gt; 1)<br>856                 ndev-&gt;config.max_virtqueue_pairs = ndev-&gt;queue_pairs;<br>857<br>858         for (i = 0 ; i &lt; 6 ; i++) {<br>859                 ndev-&gt;config.mac[i]             = params-&gt;guest_mac[i];<br>860                 ndev-&gt;info.guest_mac.addr[i]    = params-&gt;guest_mac[i];<br>861                 ndev-&gt;info.host_mac.addr[i]     = params-&gt;host_mac[i];<br>862         }<br>863</pre><pre>864         ndev-&gt;mode = params-&gt;mode;<br>865         if (ndev-&gt;mode == NET_MODE_TAP) {<br>866                 ndev-&gt;ops = &amp;tap_ops;<br>867                 if (!virtio_net__tap_create(ndev))<br>868                         die_perror(&quot;You have requested a TAP device, but creation of one has failed because&quot;);<br>869         } else {<br>870                 ndev-&gt;info.host_ip              = ntohl(inet_addr(params-&gt;host_ip));<br>871                 ndev-&gt;info.guest_ip             = ntohl(inet_addr(params-&gt;guest_ip));<br>872                 ndev-&gt;info.guest_netmask        = ntohl(inet_addr(&quot;255.255.255.0&quot;));<br>873                 ndev-&gt;info.buf_nr               = 20,<br>874                 ndev-&gt;ops = &amp;uip_ops;<br>875                 uip_static_init(&amp;ndev-&gt;info);<br>876         }</pre><h3>virtio/net.c</h3><pre>static struct net_dev_operations uip_ops = {<br>        .rx     = uip_ops_rx,<br>        .tx     = uip_ops_tx,<br>};</pre><pre>static inline int uip_ops_tx(struct iovec *iov, u16 out, struct net_dev *ndev)<br>{<br>        return uip_tx(iov, out, &amp;ndev-&gt;info);<br>}</pre><pre>static inline int uip_ops_rx(struct iovec *iov, u16 in, struct net_dev *ndev)<br>{<br>        return uip_rx(iov, in, &amp;ndev-&gt;info);                                      &lt;&lt;&lt; note the ndev-&gt;info<br>}</pre><pre>168 static void *virtio_net_tx_thread(void *p)<br>169 {<br>188         while (1) {<br>194                 while (virt_queue__available(vq)) {<br>195                         struct virtio_net_hdr *hdr;<br>196                         head = virt_queue__get_iov(vq, iov, &amp;out, &amp;in, kvm);   &lt;&lt; we get the iov here<br>197                         hdr = iov[0].iov_base;<br>198                         virtio_net_fix_tx_hdr(hdr, ndev);<br>199                         len = ndev-&gt;ops-&gt;tx(iov, out, ndev);                   &lt;&lt; we invoke the tx function</pre><h3>uip_tx</h3><p>uip_tx -&gt; case UIP_ETH_P_ARP: uip_tx_do_arp(&amp;arg); case UIP_ETH_P_IP: uip_tx_do_ipv4(&amp;arg);</p><h3>ARP handling</h3><p>(the gw is always the host, And that should be the only ARP we should see)</p><pre>uip_tx_do_arp -&gt; uip_tx_do_arp<br>  9         info = arg-&gt;info;<br> 10         buf = uip_buf_clone(arg);                       &lt;&lt;&lt;&lt; grab a device to guest buffer. buffer state goes from FREE -&gt; INUSE<br> 11<br> 12         arp      = (struct uip_arp *)(arg-&gt;eth);<br> 13         arp2     = (struct uip_arp *)(buf-&gt;eth);<br> 14<br> 15         /*<br> 16          * ARP replay code: 2  &lt;&lt;&lt; typo, reply<br> 17          */<br> 18         arp2-&gt;op   = htons(0x2);<br> 19         arp2-&gt;dmac = arp-&gt;smac;<br> 20         arp2-&gt;dip  = arp-&gt;sip;<br> 21<br> 22         if (arp-&gt;dip == htonl(info-&gt;host_ip)) {  &lt;&lt;&lt;&lt;&lt; This is the gateway ARP. Pretty much the only one we should see<br> 23                 arp2-&gt;smac = info-&gt;host_mac;<br> 24                 arp2-&gt;sip = htonl(info-&gt;host_ip);<br> 25<br> 26                 uip_buf_set_used(info, buf);   &lt;&lt;&lt; buffer is not set to USED, which I assume means ready to transmit<br> 27         }</pre><h3>uip_rx</h3><pre>92 static void *virtio_net_rx_thread(void *p)<br>112         while (1) {<br>118                 while (virt_queue__available(vq)) {<br>127                         len = ndev-&gt;ops-&gt;rx(&amp;dummy_iov, 1, ndev);<br>154                         virt_queue__used_idx_advance(vq, num_buffers);<br>156                         /* We should interrupt guest right now, otherwise latency is huge. */<br>157                         if (virtio_queue__should_signal(vq))<br>158                                 ndev-&gt;vdev.ops-&gt;signal_vq(kvm, &amp;ndev-&gt;vdev, id);</pre><pre>int uip_rx(struct iovec *iov, u16 in, struct uip_info *info)<br>{<br>        /*<br>         * Sleep until there is a buffer for guest<br>         */<br>        buf = uip_buf_get_used(info);    &lt;&lt;&lt; if info-&gt;buf_used_nr &lt; 0, walks the info-&gt;buf_head till it finds the first UIP_BUF_STATUS_USED. This is how the packet we set out to transmit makes it back from tx to rx<br>        memcpy_toiovecend(iov, buf-&gt;vnet, 0, buf-&gt;vnet_len);<br>        memcpy_toiovecend(iov, buf-&gt;eth, buf-&gt;vnet_len, buf-&gt;eth_len);    <br>        uip_buf_set_free(info, buf);<br>        return len;<br>}</pre><h3>Handling of IPv4 Traffic</h3><pre>3 int uip_tx_do_ipv4(struct uip_tx_arg *arg)<br>  4 {<br> 14         switch (ip-&gt;proto) {<br> 15         case UIP_IP_P_ICMP:<br> 16                 uip_tx_do_ipv4_icmp(arg);<br> 17                 break;<br> 18         case UIP_IP_P_TCP:<br> 19                 uip_tx_do_ipv4_tcp(arg);<br> 20                 break;<br> 21         case UIP_IP_P_UDP:<br> 22                 uip_tx_do_ipv4_udp(arg);<br> 23                 break;<br> 24         default:<br> 25                 break;<br> 26         }</pre><h3>ICMP</h3><p>Provide a ICMP reply</p><pre>3 int uip_tx_do_ipv4_icmp(struct uip_tx_arg *arg)<br>  4 {<br>  9         buf             = uip_buf_clone(arg);   &lt;&lt;&lt;&lt; grab a device to guest buffer<br> 15         ip2-&gt;sip        = ip-&gt;dip;              &lt;&lt;&lt;&lt; flip it<br> 16         ip2-&gt;dip        = ip-&gt;sip;<br> 18         /*<br> 19          * ICMP reply: 0   &lt;&lt;&lt;&lt; Type 0 — Echo Reply,,, so a ICMP reply<br> 20          */<br> 21         icmp2-&gt;type     = 0;<br> 23         ip2-&gt;csum       = uip_csum_ip(ip2);<br> 24         icmp2-&gt;csum     = uip_csum_icmp(icmp2);<br> 26         uip_buf_set_used(arg-&gt;info, buf);        &lt;&lt;&lt; queue the reply<br> 29 }</pre><h3>UDP</h3><pre>204 int uip_tx_do_ipv4_udp(struct uip_tx_arg *arg)<br>205 {<br>212         udp     = (struct uip_udp *)(arg-&gt;eth); <br>213         ip      = (struct uip_ip *)(arg-&gt;eth);</pre><pre>216         if (uip_udp_is_dhcp(udp)) {<br>217                 uip_tx_do_ipv4_udp_dhcp(arg);</pre><pre>221         /*<br>222          * Find socket we have allocated before, otherwise allocate one<br>223          */<br>224         sk = uip_udp_socket_find(arg, ip-&gt;sip, ip-&gt;dip, udp-&gt;sport, udp-&gt;dport);</pre><pre>231         ret = uip_udp_socket_send(sk, udp);  <br>                      &gt;&gt;&gt;&gt; ret = sendto(sk-&gt;fd, udp-&gt;payload, len, 0, (struct sockaddr *)&amp;sk-&gt;addr, sizeof(sk-&gt;addr)); <br>                      &gt;&gt;&gt;&gt; just send the UDP *data* out over the process socket<br>                      &gt;&gt;&gt;&gt; Also add the fd to the list of fd&#39;s that we should wait on for replies sk-&gt;fd to epoll_wait<br>234<br>235         if (!info-&gt;udp_thread)<br>236                 pthread_create(&amp;info-&gt;udp_thread, NULL, uip_udp_socket_thread, (void *)info);<br>                     &gt;&gt;&gt;&gt;&gt; This thread waits for replies from all the opened UDP sockets</pre><pre>153 static void *uip_udp_socket_thread(void *p)<br>154 {<br>155         struct epoll_event events[UIP_UDP_MAX_EVENTS]; /// 1000 today<br>172         while (1) {<br>173                 nfds = epoll_wait(info-&gt;udp_epollfd, events, UIP_UDP_MAX_EVENTS, -1);<br>178                 for (i = 0; i &lt; nfds; i++) {<br>181                         payload_len = recvfrom(sk-&gt;fd, payload, UIP_MAX_UDP_PAYLOAD, 0, NULL, NULL);<br>188                         buf = uip_buf_get_free(info);<br>190                         uip_udp_make_pkg(info, sk, buf, payload, payload_len);<br>                            &gt;&gt;&gt; Adds ethernet header<br>                            &gt;&gt;&gt; Adds IP header<br>                            &gt;&gt;&gt; Adds UDP header<br>195                         uip_buf_set_used(info, buf);<br>                            &gt;&gt;&gt;&gt; queue it to the guest<br>196                 }<br>197         }<br>198</pre><h3>TCP Handling</h3><pre>260 int uip_tx_do_ipv4_tcp(struct uip_tx_arg *arg)<br>261 {<br>270         /*<br>271          * Guest is trying to start a TCP session, let&#39;s fake SYN-ACK to guest<br>272          */<br>273         if (uip_tcp_is_syn(tcp)) {<br>274                 sk = uip_tcp_socket_alloc(arg, ip-&gt;sip, ip-&gt;dip, tcp-&gt;sport, tcp-&gt;dport);<br>&gt;&gt;&gt; Set&#39;s up a proxy connection<br>&gt;&gt;&gt; Adds the host side socket to the list<br>278                 sk-&gt;window_size = ntohs(tcp-&gt;win);</pre><pre>288                 uip_tcp_payload_send(sk, UIP_TCP_FLAG_SYN | UIP_TCP_FLAG_ACK, 0);<br>&gt;&gt;&gt; Send a sync ack to the guest<br>289                 sk-&gt;seq_server += 1;</pre><pre>294                 uip_tcp_socket_receive(sk);<br>&gt;&gt;&gt; There is a single TCP handler thread that handles all the sockets<br>297         }<br>298<br>299         /*<br>302         sk = uip_tcp_socket_find(arg, ip-&gt;sip, ip-&gt;dip, tcp-&gt;sport, tcp-&gt;dport);<br>307         sk-&gt;window_size = ntohs(tcp-&gt;win);<br>308         sk-&gt;guest_acked = ntohl(tcp-&gt;ack);</pre><pre>312         if (uip_tcp_is_fin(tcp)) {<br>316                 sk-&gt;write_done = 1;<br>317                 sk-&gt;ack_server += 1;<br>318                 uip_tcp_payload_send(sk, UIP_TCP_FLAG_ACK, 0);<br>323                 uip_tcp_socket_close(sk, SHUT_WR);<br>326         }<br>327<br>331         if (uip_tcp_payloadlen(tcp) == 0)<br>332                 goto out;</pre><pre>337         ret = uip_tcp_socket_send(sk, tcp);</pre><pre>344         uip_tcp_payload_send(sk, UIP_TCP_FLAG_ACK, 0);<br>&gt;&gt;&gt; Send ACK back to the guest<br>348 }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df9bd35a65e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up a overlay network using point to multi-point GRE tunnels]]></title>
            <link>https://mcastelino.medium.com/setting-up-a-overlay-network-using-point-to-multi-point-gre-tunnels-c8c2422c2fa2?source=rss-36333dae6058------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8c2422c2fa2</guid>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[overlay]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[M Castelino]]></dc:creator>
            <pubDate>Thu, 11 Apr 2019 04:12:47 GMT</pubDate>
            <atom:updated>2019-04-11T04:12:47.298Z</atom:updated>
            <content:encoded><![CDATA[<h3>Multi-Point GRE Tunnels</h3><p>Typically VxLAN is used to setup a point to multi-point overlay networks. However GRE also offers a similar capability which is often not heavily used. This document calls out how to setup an effient overlay mesh network to link up multiples sits together using multi point GRE tunnels.</p><h3>Setup</h3><p>The setup used in this case assumes there is a need to link three sites hosting three different subnets together using a simple overlay mesh network.</p><ul><li>Node A: 192.168.33.1 hosting subnet 10.0.1.0/24</li><li>Node B: 192.168.33.2 hosting subnet 10.0.2.0/24</li><li>Node C: 192.168.33.3 hosting subnet 10.0.3.0/24</li></ul><p>We desire seamless connectivity between all the three subnets 10.0.1.0/24, 10.0.2.0/24 and 10.0.3.0/24.</p><h3>Setting up the overlay network</h3><h3>Setup the multi-point GRE tunnel</h3><p>On Node A:</p><pre>ip tunnel add overNet mode gre local 192.168.33.1 key 1234</pre><h3>Assign an IP Address to the tunnel end point</h3><pre>ip addr add 10.0.0.1/24 dev overNet</pre><h3>Add neighbour entries for remote end points</h3><pre>ip neighbor add 10.0.0.2 lladdr 192.168.33.2 dev overNet<br>ip neighbor add 10.0.0.3 lladdr 192.168.33.3 dev overNet<br>ip link set dev overNet up</pre><blockquote>Note: The link layer address here is the IP address of the remote node and not a IP addresses</blockquote><h3>Add routes to reach the remote subnets via the tunnel end points</h3><pre>ip route add 10.2.0.0/24 via 10.0.0.2<br>ip route add 10.3.0.0/24 via 10.0.0.3</pre><blockquote>Note: We route the traffic through the overlay tunnels</blockquote><p>Repeat these steps on Node B and Node C, with appropriate changes.</p><h3>Node B Setup</h3><pre>ip tunnel add overNet mode gre local 192.168.33.2 key 1234<br>ip addr add 10.0.0.2/24 dev overNet<br>ip neighbor add 10.0.0.1 lladdr 192.168.33.1 dev overNet<br>ip neighbor add 10.0.0.3 lladdr 192.168.33.3 dev overNet<br>ip link set dev overNet up<br>ip route add 10.1.0.0/24 via 10.0.0.1<br>ip route add 10.3.0.0/24 via 10.0.0.3</pre><h3>Node C Setup</h3><pre>ip tunnel add overNet mode gre local 192.168.33.3 key 1234<br>ip addr add 10.0.0.3/24 dev overNet<br>ip neighbor add 10.0.0.2 lladdr 192.168.33.2 dev overNet<br>ip neighbor add 10.0.0.3 lladdr 192.168.33.3 dev overNet<br>ip link set dev overNet up<br>ip route add 10.2.0.0/24 via 10.0.0.2<br>ip route add 10.3.0.0/24 via 10.0.0.3</pre><p>Now you will be able to reach all the subnets seamlessly with Node A, Node B and Node C acting as a routers and for traffic traversing across subnets</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8c2422c2fa2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tracing QEMU-KVM Interactions]]></title>
            <link>https://mcastelino.medium.com/tracing-qemu-kvm-interactions-da92a8d78f79?source=rss-36333dae6058------2</link>
            <guid isPermaLink="false">https://medium.com/p/da92a8d78f79</guid>
            <category><![CDATA[virtualization-technology]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[kvm]]></category>
            <category><![CDATA[tracing]]></category>
            <category><![CDATA[qemu]]></category>
            <dc:creator><![CDATA[M Castelino]]></dc:creator>
            <pubDate>Thu, 11 Apr 2019 04:10:58 GMT</pubDate>
            <atom:updated>2019-04-11T04:10:58.196Z</atom:updated>
            <content:encoded><![CDATA[<p>But default in linux you can figure out how many times and for what reasons there is a VM Exit from a VM into the kvm kernel module. However given the ubiquity of vhost and the ability of kvm to emulate most device models directly in the kernel, most of those VM exits do not result in a transition from host kernel into the QEMU. The transitions from VM -&gt; kvm -&gt; QEMU are typically the most expensive.</p><p>Here we try to figure out how many of the VM Exits result in the invocation of QEMU.</p><h3>Tracking VM-KVM Interactions</h3><p>This can be done very simply with perf</p><pre>sudo ./perf stat -e &#39;kvm:*&#39; -a sleep 1s</pre><p>This will give you statistics collected over 1s for all VM exits (across VMs)</p><p>You can also do this directly and get the full trace logs via</p><pre>echo 1 &gt; /sys/kernel/debug/tracing/events/kvm/enable<br>cat /sys/kernel/debug/tracing/trace_pipe</pre><h3>Background</h3><p>All <em>primary</em> exits from kvm to QEMU are via the return path of KVM_RUN ioctl. Fortunately for us QEMU already has built in instrumentation for tracing. We will leverage that to selectively trace the return path of KVM_RUN and record the exit reasons</p><p>There is a second class of KVM-QEMU interaction that go through the ioeventfs,irqfd mechanism which we will instrument later.</p><h3>Code that triggers tracing of the (explicit) kvm to qemu exit</h3><p><a href="https://github.com/qemu/qemu/blob/7e56accdaf35234b69c33c85e4a44a5d56325e53/accel/kvm/kvm-all.c#L2041">https://github.com/qemu/qemu/blob/7e56accdaf35234b69c33c85e4a44a5d56325e53/accel/kvm/kvm-all.c#L2041</a></p><h3>QEMU Tracing Documentation</h3><p><a href="http://git.qemu.org/?p=qemu.git;a=blob_plain;f=docs/devel/tracing.txt;hb=HEAD">http://git.qemu.org/?p=qemu.git;a=blob_plain;f=docs/devel/tracing.txt;hb=HEAD</a> <a href="https://fossies.org/linux/qemu/docs/tracing.txt">https://fossies.org/linux/qemu/docs/tracing.txt</a></p><h3>ftrace backend</h3><p>Enabling this backend allows you to trace both the VM-KVM events as well the KVM-QEMU events.</p><h3>Build QEMU with tracking with ftrace backend</h3><pre>./configure --disable-bluez --disable-brlapi --disable-bzip2 --disable-curl --disable-curses --disable-debug-tcg --disable-fdt --disable-glusterfs --disable-gtk --disable-libiscsi --disable-libnfs --disable-libssh2 --disable-libusb --disable-linux-aio --disable-lzo --disable-opengl --disable-qom-cast-debug --disable-rbd --disable-rdma --disable-sdl --disable-seccomp --disable-slirp --disable-snappy --disable-spice --disable-strip --disable-tcg-interpreter --disable-tcmalloc --disable-tools --disable-tpm --disable-usb-redir --disable-uuid --disable-vnc --disable-vnc-jpeg --disable-vnc-png --disable-vnc-sasl --disable-vte --disable-xen --enable-attr --enable-cap-ng --enable-kvm --enable-virtfs --target-list=x86_64-softmmu --extra-cflags=&quot;-fno-semantic-interposition -O3 -falign-functions=32&quot; --datadir=/usr/share/qemu-lite --libdir=/usr/lib64/qemu-lite --libexecdir=/usr/libexec/qemu-lite --enable-vhost-net --disable-docs --enable-trace-backends=ftrace</pre><h3>Launch QEMU with tracing enabled</h3><p>Enable the tracking of just the kvm_run exit.</p><pre>rm -f /tmp/event<br>echo kvm_run_exit &gt; /tmp/events</pre><pre>sudo ../x86_64-softmmu/qemu-system-x86_64 -trace events=/tmp/events -machine pc-lite,accel=kvm,kernel_irqchip,nvdimm -cpu host -m 256,maxmem=1G,slots=2 -smp 2 -no-user-config -nodefaults -rtc base=utc,driftfix=slew -global kvm-pit.lost_tick_policy=discard -kernel ./vmlinux-4.9.34-63.1.container -append &quot;reboot=k panic=1 rw tsc=reliable no_timer_check noreplace-smp root=/dev/pmem0p1  init=/usr/lib/systemd/systemd initcall_debug rootfstype=ext4 rootflags=dax,data=ordered dhcp rcupdate.rcu_expedited=1 clocksource=kvm-clock console=hvc0 single iommu=false &quot; -device virtio-serial-pci,id=virtio-serial0 -chardev pty,id=charconsole0 -device virtconsole,chardev=charconsole0,id=console0 -nographic -object memory-backend-file,id=mem0,share,mem-path=./clear-16160-containers.img,size=235929600 -device nvdimm,memdev=mem0,id=nv0 -no-reboot -device virtio-net-pci,netdev=net0,mac=DE:AD:BE:EF:07:83 -netdev tap,id=net0,ifname=net0,script=no,downscript=no,queues=2,vhost=off -qmp tcp:localhost:4444,server,nowait</pre><h3>Tracing I/O interactions</h3><p>The kvm_run exit only records the explicit control exits. However for handing I/O QEMU-KVM irqfd and ioeventfd interaction mechanism. Unfortunately there does not exit a direct way to tap into the ioeventfd. However we can trace the actuall callback functions ultimately invoked.</p><p><a href="https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=d34e6b175e61821026893ec5298cc8e7558df43a">https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=d34e6b175e61821026893ec5298cc8e7558df43a</a> <a href="http://blog.allenx.org/2015/07/05/kvm-irqfd-and-ioeventfd">http://blog.allenx.org/2015/07/05/kvm-irqfd-and-ioeventfd</a></p><h3>Obtained the combined trace logs</h3><p>If you had enabled kvm tracing before, you will see a mix of KVM exits as well as KVM to QEMU transistion traces.</p><pre>cat /sys/kernel/debug/tracing/trace_pipe</pre><h3>Simple Backend</h3><p>The following example shows how to trace using the simple backend. This is another method that is simpler and directly creates trace files on disk.</p><h3>Build QEMU with tracing</h3><pre>./configure --disable-bluez --disable-brlapi --disable-bzip2 --disable-curl --disable-curses --disable-debug-tcg --disable-fdt --disable-glusterfs --disable-gtk --disable-libiscsi --disable-libnfs --disable-libssh2 --disable-libusb --disable-linux-aio --disable-lzo --disable-opengl --disable-qom-cast-debug --disable-rbd --disable-rdma --disable-sdl --disable-seccomp --disable-slirp --disable-snappy --disable-spice --disable-strip --disable-tcg-interpreter --disable-tcmalloc --disable-tools --disable-tpm --disable-usb-redir --disable-uuid --disable-vnc --disable-vnc-jpeg --disable-vnc-png --disable-vnc-sasl --disable-vte --disable-xen --enable-attr --enable-cap-ng --enable-kvm --enable-virtfs --target-list=x86_64-softmmu --extra-cflags=&quot;-fno-semantic-interposition -O3 -falign-functions=32&quot; --datadir=/usr/share/qemu-lite --libdir=/usr/lib64/qemu-lite --libexecdir=/usr/libexec/qemu-lite --enable-vhost-net --disable-docs --enable-trace-backends=simple</pre><h3>Launch QEMU with tracing enabled</h3><pre>rm -f /tmp/event<br>echo kvm_run_exit &gt; /tmp/events</pre><pre>sudo ../x86_64-softmmu/qemu-system-x86_64 -trace events=/tmp/events -machine pc-lite,accel=kvm,kernel_irqchip,nvdimm -cpu host -m 256,maxmem=1G,slots=2 -smp 2 -no-user-config -nodefaults -rtc base=utc,driftfix=slew -global kvm-pit.lost_tick_policy=discard -kernel ./vmlinux-4.9.34-63.1.container -append &quot;reboot=k panic=1 rw tsc=reliable no_timer_check noreplace-smp root=/dev/pmem0p1  init=/usr/lib/systemd/systemd initcall_debug rootfstype=ext4 rootflags=dax,data=ordered dhcp rcupdate.rcu_expedited=1 clocksource=kvm-clock console=hvc0 single iommu=false &quot; -device virtio-serial-pci,id=virtio-serial0 -chardev pty,id=charconsole0 -device virtconsole,chardev=charconsole0,id=console0 -nographic -object memory-backend-file,id=mem0,share,mem-path=./clear-16160-containers.img,size=235929600 -device nvdimm,memdev=mem0,id=nv0 -no-reboot -device virtio-net-pci,netdev=net0,mac=DE:AD:BE:EF:07:83 -netdev tap,id=net0,ifname=net0,script=no,downscript=no,queues=2,vhost=off -qmp tcp:localhost:4444,server,nowait</pre><h3>Analyze the Trace Events</h3><pre>simpletrace.py trace-events-all trace-6440 &amp;&gt; /tmp/xxx</pre><p>Note:</p><ul><li>The trace-events-all file will be generated at the time of qemu compilation</li><li>The trace-xyz file will be generated at qemu execution</li></ul><h3>KVM-QEMU Exit Reasons</h3><p>This will help you co-relate exit reasons to the trace logs. Teh most common ones will be for IO (2), as these are used for device modeling.</p><p><a href="https://github.com/qemu/qemu/blob/0748b3526e8cb78b9cd64208426bfc3d54a72b04/linux-headers/linux/kvm.h#L182">https://github.com/qemu/qemu/blob/0748b3526e8cb78b9cd64208426bfc3d54a72b04/linux-headers/linux/kvm.h#L182</a></p><pre>#define KVM_EXIT_UNKNOWN          0<br>#define KVM_EXIT_EXCEPTION        1<br>#define KVM_EXIT_IO               2<br>#define KVM_EXIT_HYPERCALL        3<br>#define KVM_EXIT_DEBUG            4<br>#define KVM_EXIT_HLT              5<br>#define KVM_EXIT_MMIO             6<br>#define KVM_EXIT_IRQ_WINDOW_OPEN  7<br>#define KVM_EXIT_SHUTDOWN         8<br>#define KVM_EXIT_FAIL_ENTRY       9<br>#define KVM_EXIT_INTR             10<br>#define KVM_EXIT_SET_TPR          11<br>#define KVM_EXIT_TPR_ACCESS       12<br>#define KVM_EXIT_S390_SIEIC       13<br>#define KVM_EXIT_S390_RESET       14<br>#define KVM_EXIT_DCR              15 /* deprecated */<br>#define KVM_EXIT_NMI              16<br>#define KVM_EXIT_INTERNAL_ERROR   17<br>#define KVM_EXIT_OSI              18<br>#define KVM_EXIT_PAPR_HCALL      19<br>#define KVM_EXIT_S390_UCONTROL      20<br>#define KVM_EXIT_WATCHDOG         21<br>#define KVM_EXIT_S390_TSCH        22<br>#define KVM_EXIT_EPR              23<br>#define KVM_EXIT_SYSTEM_EVENT     24<br>#define KVM_EXIT_S390_STSI        25<br>#define KVM_EXIT_IOAPIC_EOI       26<br>#define KVM_EXIT_HYPERV           27</pre><h3>Tracing all events</h3><p>All events supported by QEMU can be found in the trace-events-all file. You can extract them all (or a subset) and feed them via a script such as the one below</p><pre>cat trace-events-all | grep &quot;(&quot; | grep -v &quot;#&quot; | cut -f 1 -d &quot;(&quot; &gt; /tmp/events</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da92a8d78f79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Virtual Machine that can be instantly resumed or duplicausing migration]]></title>
            <link>https://mcastelino.medium.com/creating-a-virtual-machine-that-can-be-instantly-resumed-or-duplicausing-migration-f8af587fc415?source=rss-36333dae6058------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8af587fc415</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[virtualization-technology]]></category>
            <category><![CDATA[qemu]]></category>
            <category><![CDATA[virtual-machine-monitor]]></category>
            <dc:creator><![CDATA[M Castelino]]></dc:creator>
            <pubDate>Thu, 11 Apr 2019 04:00:38 GMT</pubDate>
            <atom:updated>2019-04-11T04:00:38.223Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating a Virtual Machine that can be instantly resumed or duplicated using migration</h3><h3>Overview</h3><p>QEMU supports migration of a virtual machine across machine over the network. It also has the capability to <em>save</em> the state of a virtual machine and resume from that state.</p><p>It is described in detail in <a href="https://www.linux-kvm.org/page/Migration">https://www.linux-kvm.org/page/Migration</a></p><p>This capability can be leveraged to create an instant resume virtual machine image if the virtual machine is crafted with care.</p><h3>Requirements</h3><ul><li>The virtual machine should run purely from memory</li><li>The virtual machine should save any persistent state to ram based storage</li><li>The virtual machine should not rely on any host network devices (like tap, blk, 9p)</li><li>The state (including networking state) should be completely contained in the QEMU process itself (i.e. SLIRP)</li></ul><h3>How to create the Virtual machine</h3><ul><li>Use kernel + initramfs + qemu + slirp networking to create the base image</li></ul><h4>Building the Kernel</h4><ul><li>The default kernel configuration has to support initrd CONFIG_BLK_DEV_INITRD=y</li><li>This will provide you with the bzImage needed</li></ul><h4>Building the initramfs</h4><ul><li>Copied from <a href="https://gist.github.com/pacalet/660fa6472e0bcd53f71fc31f167c628f">https://gist.github.com/pacalet/660fa6472e0bcd53f71fc31f167c628f</a>)</li><li>Use a busybox based rootfs for ease of us</li></ul><pre>git clone https://github.com/mirror/busybox<br>  cd busybox<br>  make defconfig<br>  make menuconfig (enable Busybox Settings ---&gt; Build Options ---&gt; Build BusyBox as a static binary (no shared libs) ---&gt; yes)<br>  make<br>  make install</pre><h4>Create the initramfs</h4><pre>  mkdir $HOME/rootfs<br>  cd $HOME/rootfs<br>  mkdir -p bin sbin etc proc sys usr/bin usr/sbin<br>  cp -a $BUSYBOX_BUILD/_install/* .<br>  rm linuxrc</pre><ul><li>Create an init binary with appropriate contents with executeable perms</li></ul><pre>#!/bin/sh<br>  mount -t proc none /proc<br>  mount -t sysfs none /sys<br>  echo -e &quot;Hello World\n&quot;<br>  exec /bin/sh</pre><pre>cd $HOME/rootfs<br>  find . -print0 | cpio --null -ov --format=newc | gzip -9 &gt; $HOME/initramfs.cpio.gz</pre><h3>Booting the base image</h3><p>Launch the VM with monitor enabled</p><pre>sudo ~/qemu/x86_64-softmmu/qemu-system-x86_64 \<br>         -machine pc,accel=kvm,kernel_irqchip \<br>         -cpu host \<br>         -kernel ./bzImage \<br>         -initrd ./initramfs.cpio.gz \<br>         -nographic \<br>         -nodefaults \<br>         -no-user-config \<br>         -m 256,maxmem=1G,slots=2 \<br>         -smp 2 -rtc base=utc,driftfix=slew \<br>         -global kvm-pit.lost_tick_policy=discard \<br>         -append &#39;console=hvc0 single iommu=false root=/dev/ram0 dhcp&#39; \<br>         -netdev user,id=mynet0 \<br>         -device virtio-net-pci,netdev=mynet0 \<br>         -device virtio-serial-pci,id=virtio-serial0 \<br>         -chardev stdio,id=charconsole0 \<br>         -device virtconsole,chardev=charconsole0,id=console0     \<br>         -monitor telnet:127.0.0.1:1234,server,nowait</pre><h3>Capturing its state</h3><pre>telnet localhost 127.0.0.1 1234<br>stop<br>migrate_set_speed 4095m                                            <br>migrate &quot;exec:gzip -c &gt; STATEFILE.gz&quot;   <br>cont</pre><h3>Launching a new VM based on this VM’s saved state</h3><pre>sudo ~/qemu/x86_64-softmmu/qemu-system-x86_64 \<br>         -machine pc,accel=kvm,kernel_irqchip \<br>         -cpu host \<br>         -kernel ./bzImage \<br>         -initrd ./initramfs.cpio.gz \<br>         -nographic \<br>         -nodefaults \<br>         -no-user-config \<br>         -m 256,maxmem=1G,slots=2 \<br>         -smp 2 -rtc base=utc,driftfix=slew \<br>         -global kvm-pit.lost_tick_policy=discard \<br>         -append &#39;console=hvc0 single iommu=false root=/dev/ram0 dhcp&#39; \<br>         -netdev user,id=mynet0 \<br>         -device virtio-net-pci,netdev=mynet0 \<br>         -device virtio-serial-pci,id=virtio-serial0 \<br>         -chardev stdio,id=charconsole0 \<br>         -device virtconsole,chardev=charconsole0,id=console0     \<br>         -incoming &quot;exec: gzip -c -d STATEFILE.gz&quot; \<br>         -monitor telnet:127.0.0.1:1235,server,nowait \</pre><h3>Resume it</h3><p>As the VM was in a stopped state you need to resume it. This VM will resume instantly in exactly the same state as the previous one. As this is a pure RAM based VM there is no additional setup needed on host or guest side. The external network connectivity is also instantly restored.</p><p>Also you can launch as many VM’s as you need from this single image</p><pre>telnet localhost 127.0.0.1 1235<br>cont</pre><h3>Note</h3><p>Using cpu=host means that image needs to be created on the same type of machine as the target</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8af587fc415" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to track raw sockets in Linux]]></title>
            <link>https://mcastelino.medium.com/how-to-track-raw-sockets-in-linux-cd0b62fb5266?source=rss-36333dae6058------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd0b62fb5266</guid>
            <category><![CDATA[socket-programming]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[sockets]]></category>
            <category><![CDATA[kernel]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[M Castelino]]></dc:creator>
            <pubDate>Thu, 11 Apr 2019 03:52:00 GMT</pubDate>
            <atom:updated>2019-04-11T03:52:00.405Z</atom:updated>
            <content:encoded><![CDATA[<h3>Example program</h3><p>Say a program has opened a raw socket. How do you know it has it open</p><pre>+       int sock_r;<br>+       struct ifreq ifrr;<br>+       size_t if_name_len=strlen(&quot;dummy0&quot;);<br>+       struct sockaddr_ll sll;<br>+<br>+       sock_r=socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));<br>+       if(sock_r &lt; 0)<br>+       {<br>+               return 0;<br>+       }<br>+<br>+       if (if_name_len&lt;sizeof(ifrr.ifr_name)) {<br>+               memcpy(ifrr.ifr_name,&quot;dummy0&quot;,if_name_len);<br>+               ifrr.ifr_name[if_name_len]=0;<br>+       } else {<br>+               close(sock_r);<br>+               return 0;<br>+       }<br>+<br>+       if (ioctl(sock_r,SIOCGIFINDEX,&amp;ifrr)==-1) {<br>+               close(sock_r);<br>+               return 0;<br>+       }<br>+<br>+       sll.sll_family = AF_PACKET;<br>+        sll.sll_protocol = htons(ETH_P_ALL);<br>+        sll.sll_ifindex = ifrr.ifr_ifindex;<br>+<br>+       if (bind(sock_r, (struct sockaddr *)&amp;sll, sizeof(sll))==-1) {<br>+               close(sock_r);<br>+               return 0;<br>+       }</pre><h3>Using ss</h3><pre>ss -f link -lnp<br>Netid State      Recv-Q Send-Q              Local Address:Port                             Peer Address:Port<br><strong>p_raw UNCONN     0      0                               *:dummy0                                       *                    users:((&quot;lkvm&quot;,pid=12479,fd=17))<br>p_raw UNCONN     0      0                               *:ens2                                         *                    users:((&quot;dhclient&quot;,pid=897,fd=5))</strong></pre><pre>root@amused-dagonet:/proc/12397/fd# ls -l /proc/12479/fd<br>total 0<br>lrwx------ 1 root root 64 Apr  5 18:33 0 -&gt; /dev/pts/5<br>lrwx------ 1 root root 64 Apr  5 18:33 1 -&gt; /dev/pts/5<br>lrwx------ 1 root root 64 Apr  5 18:33 10 -&gt; anon_inode:kvm-vcpu<br>lrwx------ 1 root root 64 Apr  5 18:33 11 -&gt; anon_inode:kvm-vcpu<br>lrwx------ 1 root root 64 Apr  5 18:33 12 -&gt; /home/mrcastel/rootfs.ext4<br>lrwx------ 1 root root 64 Apr  5 18:33 13 -&gt; anon_inode:[eventfd]<br>lrwx------ 1 root root 64 Apr  5 18:33 14 -&gt; anon_inode:[eventfd]<br>lrwx------ 1 root root 64 Apr  5 18:33 15 -&gt; anon_inode:[eventfd]<br>lrwx------ 1 root root 64 Apr  5 18:33 16 -&gt; socket:[130535]<br>lrwx------ 1 root root 64 Apr  5 18:33 17 -&gt; socket:[130536]<br>lrwx------ 1 root root 64 Apr  5 18:33 18 -&gt; anon_inode:[eventfd]<br>lrwx------ 1 root root 64 Apr  5 18:33 19 -&gt; anon_inode:[eventfd]<br>lrwx------ 1 root root 64 Apr  5 18:33 2 -&gt; /dev/pts/5<br>lrwx------ 1 root root 64 Apr  5 18:33 20 -&gt; anon_inode:[eventfd]<br>lrwx------ 1 root root 64 Apr  5 18:33 21 -&gt; anon_inode:[eventfd]<br>lrwx------ 1 root root 64 Apr  5 18:33 22 -&gt; anon_inode:[eventfd]<br>lrwx------ 1 root root 64 Apr  5 18:33 23 -&gt; anon_inode:[eventfd]<br>lrwx------ 1 root root 64 Apr  5 18:33 3 -&gt; /dev/kvm<br>lrwx------ 1 root root 64 Apr  5 18:33 4 -&gt; anon_inode:kvm-vm<br>lrwx------ 1 root root 64 Apr  5 18:33 5 -&gt; socket:[129805]<br>lrwx------ 1 root root 64 Apr  5 18:33 6 -&gt; anon_inode:[eventpoll]<br>lrwx------ 1 root root 64 Apr  5 18:33 7 -&gt; anon_inode:[eventfd]<br>lrwx------ 1 root root 64 Apr  5 18:33 8 -&gt; anon_inode:[eventpoll]<br>lrwx------ 1 root root 64 Apr  5 18:33 9 -&gt; anon_inode:[eventfd]</pre><h3>/proc</h3><pre>cat /proc/net/packet<br>sk       RefCnt Type Proto  Iface R Rmem   User   Inode<br>ffff8801b64e4000 3      3    0003   17    1 0      0      130536<br>ffff8800b9ed6000 3      3    0003   2     1 0      0      12971</pre><h3>Reference</h3><p><a href="http://sgros.blogspot.com/2012/02/whos-listening-on-interface.html">http://sgros.blogspot.com/2012/02/whos-listening-on-interface.html</a></p><h3>Can you write to the fd</h3><p>Unfortunately you cannot</p><p><a href="http://lxr.linux.no/#linux+v3.2.11/net/socket.c#L135">http://lxr.linux.no/#linux+v3.2.11/net/socket.c#L135</a></p><pre>130/*<br> 131 *      Socket files have a set of &#39;special&#39; operations as well as the generic file ones. These don&#39;t appear<br> 132 *      in the operation structures but are done directly via the socketcall() multiplexor.<br> 133 */<br> 134<br> 135static const struct file_operations socket_file_ops = {<br> 136        .owner =        THIS_MODULE,<br> 137        .llseek =       no_llseek,<br> 138        .aio_read =     sock_aio_read,<br> 139        .aio_write =    sock_aio_write,<br> 140        .poll =         sock_poll,<br> 141        .unlocked_ioctl = sock_ioctl,<br> 142#ifdef CONFIG_COMPAT<br> 143        .compat_ioctl = compat_sock_ioctl,<br> 144#endif<br> 145        .mmap =         sock_mmap,<br> 146        .open =         sock_no_open,   /* special open code to disallow open via /proc */<br> 147        .release =      sock_close,<br> 148        .fasync =       sock_fasync,<br> 149        .sendpage =     sock_sendpage,<br> 150        .splice_write = generic_splice_sendpage,<br> 151        .splice_read =  sock_splice_read,<br> 152};</pre><p><a href="https://unix.stackexchange.com/questions/33924/write-inside-a-socket-open-by-another-process-in-linux?rq=1">https://unix.stackexchange.com/questions/33924/write-inside-a-socket-open-by-another-process-in-linux?rq=1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd0b62fb5266" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging ACPI Events in the kernel using QEMU]]></title>
            <link>https://mcastelino.medium.com/debugging-acpi-events-in-the-kernel-using-qemu-add45cb524dc?source=rss-36333dae6058------2</link>
            <guid isPermaLink="false">https://medium.com/p/add45cb524dc</guid>
            <category><![CDATA[acpi]]></category>
            <category><![CDATA[kernel]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[qemu]]></category>
            <category><![CDATA[debugg]]></category>
            <dc:creator><![CDATA[M Castelino]]></dc:creator>
            <pubDate>Thu, 11 Apr 2019 03:47:33 GMT</pubDate>
            <atom:updated>2019-04-11T03:47:33.049Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kernel Build</h3><p>Build the kernel with ACPI debug enabled as described in <a href="https://www.kernel.org/doc/Documentation/acpi/debug.txt">https://www.kernel.org/doc/Documentation/acpi/debug.txt</a></p><p>tl;dr</p><pre>ACPI debug output is globally enabled by CONFIG_ACPI_DEBUG.  If this config option is turned off, the debug messages are not even built into the<br>kernel.</pre><pre>When CONFIG_ACPI_DEBUG=y, you can select the component and level of messages you&#39;re interested in.  At boot-time, use the acpi.debug_layer and acpi.debug_level kernel command line options.  After boot, you can use the debug_layer and debug_level files in /sys/module/acpi/parameters/ to control the debug messages.</pre><pre>The &quot;debug_layer&quot; is a mask that selects components of interest, e.g., a specific driver or part of the ACPI interpreter.  To build the debug_layer bitmask, look for the &quot;#define _COMPONENT&quot; in an ACPI source file.</pre><pre>The &quot;debug_level&quot; is a mask that selects different types of messages, e.g., those related to initialization, method execution, informational messages, etc. To build debug_level, look at the level specified in an ACPI_DEBUG_PRINT() statement.</pre><pre>The ACPI interpreter uses several different levels, but the Linux<br>ACPI core and ACPI drivers generally only use ACPI_LV_INFO.</pre><h3>Launching QEMU</h3><pre>#!/bin/bash<br># -*- mode: shell-script; indent-tabs-mode: nil; sh-basic-offset: 4; -*-<br># ex: ts=8 sw=4 sts=4 et filetype=sh</pre><pre>VMN=${VMN:=1}</pre><pre>QEMU=qemu-system-x86_64</pre><pre>let APCI_UTILITIES=0x00000001<br>let APCI_HARDWARE=0x00000002<br>let APCI_EVENTS=0x00000004<br>let APCI_TABLES=0x00000008<br>let APCI_NAMESPACE=0x00000010<br>let APCI_PARSER=0x00000020<br>let APCI_DISPATCHER=0x00000040<br>let APCI_EXECUTER=0x00000080<br>let APCI_RESOURCES=0x00000100<br>let APCI_CA_DEBUGGER=0x00000200<br>let APCI_OS_SERVICES=0x00000400<br>let APCI_CA_DISASSEMBLER=0x00000800<br>let APCI_COMPILER=0x00001000<br>let APCI_TOOLS=0x00002000<br>let APCI_BUS_COMPONENT=0x00010000<br>let APCI_AC_COMPONENT=0x00020000<br>let APCI_BATTERY_COMPONENT=0x00040000<br>let APCI_BUTTON_COMPONENT=0x00080000<br>let APCI_SBS_COMPONENT=0x00100000<br>let APCI_FAN_COMPONENT=0x00200000<br>let APCI_PCI_COMPONENT=0x00400000<br>let APCI_POWER_COMPONENT=0x00800000<br>let APCI_CONTAINER_COMPONENT=0x01000000<br>let APCI_SYSTEM_COMPONENT=0x02000000<br>let APCI_THERMAL_COMPONENT=0x04000000<br>let APCI_MEMORY_DEVICE_COMPONENT=0x08000000<br>let APCI_VIDEO_COMPONENT=0x10000000<br>let APCI_PROCESSOR_COMPONENT=0x20000000</pre><pre>let acpi_debug_layer=$((APCI_HARDWARE|APCI_EVENTS|APCI_PCI_COMPONENT|APCI_TABLES|APCI_RESOURCES|APCI_BUS_COMPONENT|APCI_BUTTON_COMPONENT|APCI_OS_SERVICES|APCI_PROCESSOR_COMPONENT|APCI_MEMORY_DEVICE_COMPONENT|APCI_RESOURCES))</pre><pre>let APCI_LV_INIT=0x00000001<br>let APCI_LV_DEBUG_OBJECT=0x00000002<br>let APCI_LV_INFO=0x00000004<br>let APCI_LV_INIT_NAMES=0x00000020<br>let APCI_LV_PARSE=0x00000040<br>let APCI_LV_LOAD=0x00000080<br>let APCI_LV_DISPATCH=0x00000100<br>let APCI_LV_EXEC=0x00000200<br>let APCI_LV_NAMES=0x00000400<br>let APCI_LV_OPREGION=0x00000800<br>let APCI_LV_BFIELD=0x00001000<br>let APCI_LV_TABLES=0x00002000<br>let APCI_LV_VALUES=0x00004000<br>let APCI_LV_OBJECTS=0x00008000<br>let APCI_LV_RESOURCES=0x00010000<br>let APCI_LV_USER_REQUESTS=0x00020000<br>let APCI_LV_PACKAGE=0x00040000<br>let APCI_LV_ALLOCATIONS=0x00100000<br>let APCI_LV_FUNCTIONS=0x00200000<br>let APCI_LV_OPTIMIZATIONS=0x00400000<br>let APCI_LV_MUTEX=0x01000000<br>let APCI_LV_THREADS=0x02000000<br>let APCI_LV_IO=0x04000000<br>let APCI_LV_INTERRUPTS=0x08000000<br>let APCI_LV_AML_DISASSEMBLE=0x10000000<br>let APCI_LV_VERBOSE_INFO=0x20000000<br>let APCI_LV_FULL_TABLES=0x40000000<br>let APCI_LV_EVENTS=0x80000000</pre><pre>let apci_debug_level=$((APCI_LV_INFO|APCI_LV_DEBUG_OBJECT|APCI_LV_INTERRUPTS|APCI_LV_EVENTS|APCI_LV_IO|APCI_LV_FUNCTIONS|APCI_LV_DISPATCH|APCI_LV_OPREGION|APCI_LV_FULL_TABLES|APCI_LV_VERBOSE_INFO))</pre><pre>sudo $QEMU \<br>     -bios OVMF.fd \<br>     -enable-kvm \<br>     -nodefaults \<br>     -vga none -nographic \<br>     -smp sockets=1,cpus=4,cores=2,maxcpus=8 -cpu host \<br>     -m 512 \<br>     -kernel bzImage -append &#39;console=hvc0 iommu=false root=/dev/vda3 rw rootfstype=ext4 data=ordered rcupdate.rcu_expedited=1 tsc=reliable no_timer_check reboot=t noapictimer acpi.debug_layer=&#39;&quot;${acpi_debug_layer}&quot;&#39; acpi.debug_level=&#39;&quot;${apci_debug_level}&quot;&#39; log_buf_len=1M loglevel=2&#39; \<br>     -device virtio-blk-pci,drive=image -drive if=none,id=image,file=clear.img,format=raw \<br>     -device virtio-serial-pci,id=virtio-serial0 -device virtconsole,chardev=charconsole0,id=console0 -chardev stdio,id=charconsole0 \<br>     -monitor telnet:127.0.0.1:55555,server,nowait \<br></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=add45cb524dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use VFIO to assign a device to nested VM]]></title>
            <link>https://mcastelino.medium.com/how-to-use-vfio-to-assign-a-device-to-nested-vm-adb943dada4e?source=rss-36333dae6058------2</link>
            <guid isPermaLink="false">https://medium.com/p/adb943dada4e</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[virtio]]></category>
            <category><![CDATA[qemu]]></category>
            <category><![CDATA[vfio]]></category>
            <category><![CDATA[virtualization-technology]]></category>
            <dc:creator><![CDATA[M Castelino]]></dc:creator>
            <pubDate>Thu, 11 Apr 2019 03:43:01 GMT</pubDate>
            <atom:updated>2019-04-11T03:43:01.998Z</atom:updated>
            <content:encoded><![CDATA[<ul><li>Here the vfio-pci device is passed in into the L1 VM</li><li>The L1 VM is setup with kernel_irqchip=split</li><li>The L0 exposes a virtual IOMMU to the L1 VM</li></ul><pre>qemu-system-x86_64 \<br>    -machine q35,accel=kvm,kernel_irqchip=split \<br>    -enable-kvm \<br>    -bios OVMF.fd \<br>    -smp sockets=1,cpus=4,cores=2 -cpu host \<br>    -m 1024 \<br>    -vga none -nographic \<br>    -drive file=&quot;$IMAGE&quot;,if=virtio,aio=threads,format=raw \<br>    -netdev user,id=mynet0,hostfwd=tcp::${VMN}0022-:22,hostfwd=tcp::${VMN}2375-:2375 \<br>    -device virtio-net-pci,netdev=mynet0 \<br>    -device virtio-rng-pci \<br>    -monitor telnet:127.0.0.1:55555,server,nowait \<br>    -debugcon file:debug.log -global isa-debugcon.iobase=0x402 $@ \<br>    -device intel-iommu,intremap=on,caching-mode=on \<br>    -device vfio-pci,host=b3:00.0 \</pre><p>Within the VM you will see</p><pre>root@clr-d8a5d96d9a844656bcab094780f420b2 ~ # dmesg | grep -e DMAR -e IOMMU<br>[    0.000000] ACPI: DMAR 0x000000003E86C000 000048 (v01 BOCHS  BXPCDMAR 00000001 BXPC 00000001)<br>[    0.000000] DMAR: IOMMU enabled<br>[    0.145746] DMAR: Host address width 39<br>[    0.145747] DMAR: DRHD base: 0x000000fed90000 flags: 0x1<br>[    0.145769] DMAR: dmar0: reg_base_addr fed90000 ver 1:0 cap 12008c22260286 ecap f00f5a<br>[    0.145776] DMAR: No RMRR found<br>[    0.145776] DMAR: No ATSR found<br>[    0.145825] DMAR: dmar0: Using Queued invalidation<br>[    0.218192] DMAR: Setting RMRR:<br>[    0.218193] DMAR: Prepare 0-16MiB unity mapping for LPC<br>[    0.219038] DMAR: Setting identity map for device 0000:00:1f.0 [0x0 - 0xffffff]<br>[    0.257194] DMAR: Intel(R) Virtualization Technology for Directed I/O</pre><p>You will also see IOMMU groups setup within the VM</p><pre>root@clr-d8a5d96d9a844656bcab094780f420b2 ~ # lspci -v -s 00:03.0<br>00:03.0 Serial controller: MosChip Semiconductor Technology Ltd. 4-Port PCIe Serial Adapter (prog-if 02 [16550])<br>        Subsystem: Device a000:1000<br>        Flags: bus master, fast devsel, latency 0, IRQ 23<br>        I/O ports at 60e0 [size=8]<br>        Memory at 90003000 (32-bit, non-prefetchable) [size=4K]<br>        Memory at 90002000 (32-bit, non-prefetchable) [size=4K]<br>        Capabilities: [50] MSI: Enable- Count=1/8 Maskable- 64bit+<br>        Capabilities: [78] Power Management version 3<br>        Kernel driver in use: serial</pre><pre>root@clr-d8a5d96d9a844656bcab094780f420b2 ~ # find /sys/kernel/iommu_groups/ -type l<br>/sys/kernel/iommu_groups/5/devices/0000:00:1f.2<br>/sys/kernel/iommu_groups/5/devices/0000:00:1f.0<br>/sys/kernel/iommu_groups/5/devices/0000:00:1f.3<br>/sys/kernel/iommu_groups/3/devices/0000:00:03.0<br>/sys/kernel/iommu_groups/1/devices/0000:00:01.0<br>/sys/kernel/iommu_groups/4/devices/0000:00:04.0<br>/sys/kernel/iommu_groups/2/devices/0000:00:02.0<br>/sys/kernel/iommu_groups/0/devices/0000:00:00.0</pre><pre>root@clr-d8a5d96d9a844656bcab094780f420b2 ~ # readlink /sys/kernel/iommu_groups/3/devices/0000:00:03.0<br>../../../../devices/pci0000:00/0000:00:03.0</pre><p>This device we assigned through VFIO is now in its own IOMMU groups and can be assigned using VFIO in L1 to a L2 VM.</p><p>The L1 VM is booted with IOMMU support by passing intel_iommu=on on its kernel command line.</p><h4>Assigning virtio devices to vfio</h4><p>If a virtio device is to be assigned to vfio, then it needs to be passed as :</p><pre>-device virtio-net-pci,netdev=mynet0,disable-legacy=on,disable-modern=off,iommu_platform=on,ats=on \<br>-device intel-iommu,intremap=on,caching-mode=on,device-iotlb=on</pre><p>Documentation can be found at:<br><a href="https://wiki.qemu.org/Features/VT-d#Command_Line_Example_2">https://wiki.qemu.org/Features/VT-d#Command_Line_Example_2</a><br>Although the device is a virtio-net device, it is bound to virtio-pci driver.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adb943dada4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>