<?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 Ankit K Pandey on Medium]]></title>
        <description><![CDATA[Stories by Ankit K Pandey on Medium]]></description>
        <link>https://medium.com/@ankitkpandey1?source=rss-285c7ae18b08------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zez4i1ezlCbQHpSs8Tz7Lg.jpeg</url>
            <title>Stories by Ankit K Pandey on Medium</title>
            <link>https://medium.com/@ankitkpandey1?source=rss-285c7ae18b08------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 02:06:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ankitkpandey1/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[Mechanistic Prompt Engineering]]></title>
            <link>https://blog.devgenius.io/mechanistic-prompt-engineering-b0f73de7989a?source=rss-285c7ae18b08------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0f73de7989a</guid>
            <category><![CDATA[writing-prompts]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ankit K Pandey]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 16:03:54 GMT</pubDate>
            <atom:updated>2025-11-26T08:01:06.581Z</atom:updated>
            <content:encoded><![CDATA[<p>The discipline of prompt engineering has undergone a fundamental epistemological shift. By late 2025, the era of “<em>prompt whispering</em>”, the reliance on superstition and natural language persuasion has concluded. In its place, a rigorous engineering discipline known as <strong>Mechanistic Prompt Engineering</strong> has emerged.</p><p>This new paradigm treats the prompt not as a conversation with an agent, but as a set of precise control signals designed to modulate the internal activation states of the model. We no longer view the Large Language Model (LLM) as a black box; we view it as a computational graph composed of distinct, addressable circuits.</p><h3>Part 1: Attention Circuit Control</h3><p><em>Target Mechanisms: Induction Heads, Softmax Normalization, and Attention Sinks.</em></p><p>The most significant breakthrough in understanding In-Context Learning is the identification of <strong>Induction Heads, </strong>circuits that search for patterns and copy them. However, these circuits are prone to noise and “<em>attention dumping.</em>”</p><h3>1. The Sacrificial Buffer (Fixing Attention Sinks)</h3><h4><em>The Mechanism:</em></h4><p>The Softmax function used in attention layers must strictly sum to 1.0. If the model determines that no previous token is relevant to the current step, it must still assign that probability mass somewhere. It defaults to “<em>dumping</em>” this attention on the very first tokens of the sequence (usually the Beginning of Sequence token). These tokens become “<em>Attention Sinks</em>,” accumulating massive, noisy activations that can overwrite semantic information in the residual stream.</p><h4>The Pattern:</h4><blockquote>Insert a “trash bin” sequence at the start of the system prompt to absorb this noise.</blockquote><pre>&lt;|start_header_id|&gt;system&lt;|end_header_id|&gt;<br>--------------------------------------------------<br>[Actual System Prompt starts here]</pre><p><em>By sacrificing these initial delimiters, you provide a designated sink for the massive activations, preserving the fidelity of the subsequent semantic tokens.</em></p><h3>2. The Rigid Anchor (Triggering Token Induction)</h3><h4>The Mechanism:</h4><p>Token Induction Heads are the primary drivers of rote copying and strict formatting. They operate on exact string matching circuits. Research indicates that random variation in prompt structure inhibits these heads, whereas rigid repetition lowers their firing threshold by establishing a rhythmic anchor for the Query-Key (QK) circuit.</p><h4>The Pattern:</h4><blockquote>Use identical, repetitive delimiters to “warm up” the repetition neurons.</blockquote><p><strong>Inefficient (Variable):</strong></p><p>Example 1… Next case… Another one…</p><p><strong>Mechanistic (Anchored):</strong></p><pre>### CASE: [Data]<br>### CASE: [Data]<br>### CASE: [Data]</pre><p><em>The consistent </em><em>### token acts as a high-fidelity anchor, locking the induction head onto the pattern.</em></p><h3>3. System 2 Attention (Noise Filtering)</h3><h4>The Mechanism:</h4><p>Standard attention is “<em>System 1</em>”, fast, automatic, and susceptible to distractors. It often attends to irrelevant context simply because of lexical overlap. System 2 Attention (S2A) forces a manual “hard attention” step, physically removing noise from the context window before the reasoning generation begins.</p><h4>The Pattern:</h4><blockquote>Split the prompt into a Filtering Phase and a Reasoning Phase.</blockquote><pre>Phase 1: Read the Context and the Query. Rewrite the Context to include <br>ONLY sentences causally necessary to answer the Query. Delete all fluff.</pre><pre>Phase 2: Answer the Query using only the Rewritten Context.</pre><h3>Part 2: Memory &amp; State Engineering</h3><p><em>Target Mechanisms: KV Cache, Positional Encodings, and Recurrent States.</em></p><p>As context windows exceed 1 million tokens, the bottleneck shifts to managing the <strong>Key-Value (KV) Cache</strong> and preventing information loss (forgetting) in the middle of the sequence.</p><h3>4. Prefix Stability (KV Cache Optimization)</h3><h4>The Mechanism:</h4><p>The KV Cache is computed autoregressively. If token t changes, the cache for all subsequent tokens t&gt;1 is invalidated and must be recomputed. Placing dynamic user data (names, dates, session IDs) at the start of the prompt forces a cache miss for every new request.</p><h4>The Pattern:</h4><blockquote>Adhere to the Append-Only Imperative. Move all dynamic variables to the end of the static block.</blockquote><p><strong>Inefficient:</strong></p><p>System: You are helping User 492… [Static Instructions]</p><p><strong>Efficient:</strong></p><pre>System: You are a helpful assistant... [4000 tokens of Static Instructions]<br>User Context: ID=492 | Date=2025-11-22</pre><p><em>This preserves the computed cache for the heavy instruction block across all users.</em></p><h3>5. Positional Scaling (Mitigating “Lost in the Middle”)</h3><h4>The Mechanism:</h4><p>Models exhibit a U-shaped performance curve. They recall information at the Start (Primacy Bias) and End (Recency Bias) with high accuracy, but information in the middle suffers from attention dilution.</p><h4>The Pattern:</h4><blockquote>Artificially boost the attention score of middle-context data using Redundant Injection.</blockquote><pre>[Start of Document]<br>...<br>[Middle of Document]<br>*** CRITICAL REMINDER: The deadline is 5 PM. ***<br>*** REPEAT: The deadline is 5 PM. ***<br>...<br>[End of Document]</pre><p><em>High-frequency tokens and local repetition simulate a higher weight in the hidden state, compensating for the natural dip in the attention curve.</em></p><h3>6. The Mamba State Reset (SSM Control)</h3><h4>The Mechanism:</h4><p>State Space Models (SSMs) like Mamba compress context into a fixed-size recurrent hidden state. In continuous processing tasks, this state becomes saturated with noise, leading to “Anterograde Amnesia.” Unlike Transformers, SSMs cannot explicitly “look back” at past tokens once processed.</p><h4>The Pattern:</h4><blockquote>Insert high-entropy separators to force a state flush.</blockquote><pre>[Task A Output]<br>=== END OF SEGMENT === RESET STATE ===<br>[Task B Input]</pre><p><em>This acts as a signal to the gating mechanism to reset the compression trajectory, preventing the manifold of Task A from bleeding into Task B.</em></p><h3>Part 3: Routing &amp; Reasoning Strategy</h3><p><em>Target Mechanisms: MoE Routers, Latent Space Trajectories, and Entropy.</em></p><p>Modern architectures are often <strong>Mixtures of Experts (MoE)</strong> or utilize probabilistic decoding. These components can be steered adversarially.</p><h3>7. Adversarial Expert Steering (MoE Routing)</h3><h4>The Mechanism:</h4><p>MoE models utilize a Router network to select the top-k experts based on the dot product of the input embedding and the expert’s signature. Vague or casual inputs often route to “<em>Generalist</em>” experts, which are safety-tuned and less capable in niche domains.</p><h4>The Pattern:</h4><blockquote>Prepend dense, domain-specific jargon to shift the input embedding vector toward the desired expert centroid.</blockquote><p>Goal: Solve a physics problem.</p><pre>Let L be the Lagrangian density. Consider the Hamiltonian formalism...<br>[Insert actual question]</pre><p><em>This mathematical density aligns the embedding vector with the “Physics Expert” weights before the model parses the actual query.</em></p><h3>8. Critique-Driven Alignment (AlignRAG)</h3><h4>The Mechanism:</h4><p>When retrieved evidence (RAG) contradicts the model’s parametric memory, the model often hallucinates or merges the two conflicting sources. AlignRAG utilizes a feedback loop to explicitly nudge the generation trajectory in the latent space toward the retrieved evidence.</p><h4>The Pattern:</h4><blockquote>Force a “Rationale — Critique — Refinement” loop.</blockquote><pre>1. Rationale: Explain the answer based on the documents.<br>2. Critique: Identify where the rationale relies on internal bias vs. external evidence.<br>3. Gold Answer: Rewrite the rationale removing the internal bias.</pre><h3>9. Entropy Pruning (Algorithm of Thoughts)</h3><h4>The Mechanism:</h4><p>Standard Chain-of-Thought (CoT) is computationally inefficient. Algorithm of Thoughts (AoT) leverages Step Entropy as a metric for reasoning quality. Low entropy steps are predictable and trivial; high entropy steps represent information gain.</p><h4>The Pattern:</h4><blockquote>Instruct the model to evaluate the “information gain” of its own thoughts during generation.</blockquote><pre>Strategy: Depth-First Search with Entropy Pruning.<br>Step 1: [Thought] -&gt; Evaluation: Trivial. Action: Prune.<br>Step 2: [Thought] -&gt; Evaluation: Insightful. Action: Keep.<br>Path: Execute Step 2...</pre><p><em>This mimics a tree-search algorithm, conserving the context window for high-value reasoning steps only.</em></p><h3>Conclusion</h3><p>Prompt engineering has matured from an art to a science. By understanding the architectural constraints of the model: Softmax summation, KV cache physics, and Router vector dynamics, we can write prompts that act as executable code. The prompt is the program; the model is the hardware; and mechanistic interpretability provides the instruction set architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0f73de7989a" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/mechanistic-prompt-engineering-b0f73de7989a">Mechanistic Prompt Engineering</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Tightrope of Generalization]]></title>
            <link>https://blog.devgenius.io/the-tightrope-of-generalization-4d0ceba6377b?source=rss-285c7ae18b08------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d0ceba6377b</guid>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ankit K Pandey]]></dc:creator>
            <pubDate>Fri, 31 Oct 2025 15:32:52 GMT</pubDate>
            <atom:updated>2025-11-06T07:48:55.681Z</atom:updated>
            <content:encoded><![CDATA[<p>Last time, we wrapped up wrestling with the <a href="https://medium.com/dev-genius/no-free-lunches-for-the-wicked-ae8720744855">NFL theorem</a> and the whole messy business of inductive bias. I remember staring at my screen after hitting publish, thinking, “Okay, so every learning algorithm has to bake in some assumptions about the world just to get off the ground.” It’s like you’re forced to pick a worldview, linear relationships if you’re going old-school with regression, or hierarchical feature extraction if you’re leaning into neural nets. And without that bias, you’re basically just memorizing noise, no better than random guessing across all possible problems. Vapnik nailed this in his statistical learning theory: without restrictions on the hypothesis class, you can’t guarantee generalization. It’s a necessary evil, that inductive bias, the lens that lets you see patterns.</p><p>But here’s where it gets personal, and a little frustrating. You spend weeks tuning hyperparameters, curating your dataset with all the care of a sommelier picking wines, and you land on what feels like the perfect inductive prior, maybe a boosted tree ensemble that captures those non-linear interactions just right, or a transformer that’s been fine-tuned to echo the structure of your domain. Validation scores look solid, cross-validation holds up, and you’re patting yourself on the back for nailing the bias sweet spot. Then deployment hits, and <em>bam, </em>new data streams in, and your model starts choking. Predictions drift, accuracy tanks on edge cases you swore you’d covered, and suddenly you’re debugging at 2 a.m., wondering if you overcommitted to that worldview after all.</p><p>This is the practical paradox that keeps me up at night as an engineer: why do our carefully chosen models, loaded with just the right amount of inductive bias, still falter when the world throws curveballs? It’s not always about data quality or implementation bugs, sometimes it’s deeper, baked into the very mechanics of how we learn from samples.</p><p>Enter the <strong>bias-variance tradeoff</strong>, that quiet enforcer of humility in machine learning. I like to think of it as the inescapable price of having a worldview. You commit to a hypothesis class with its built-in assumptions, and in exchange, you get two bills to pay: <strong>bias</strong>, the systematic error from your model’s blind spots, and <strong>variance</strong>, the jitter from overfitting to the quirks of your training set. Pay too little on one, and the other skyrockets; balance them, and maybe, just maybe, you generalize. It’s the theorem that reminds us, that no matter how fancy your architecture, you’re always trading underfitting for overfitting in the pursuit of that elusive true signal.</p><p>In the sections ahead, we’ll unpack this. But for now, let’s just sit with the hook: if inductive bias is the ticket to the game, the bias-variance tradeoff is the fine print telling you it’ll cost you.</p><p>Alright, with that hook still tugging at the back of my mind, the way our models betray us despite all the care we pour in. Let’s roll up our sleeves and dig into where this bias-variance thing really comes from. The information-theoretic soil that makes the tradeoff inevitable. Think of it like this: learning from data is fundamentally about compressing uncertainty into predictions, and any compression scheme has to wrestle with what’s knowable and what’s just noise. You can’t squeeze the world into your model without leaving some bits on the table or picking up extras you don’t need.</p><p>I always circle back to Shannon’s information theory when I need to remind myself why this isn’t some arbitrary engineering quirk. In <em>The Mathematical Theory of Communication</em> from 1948, Shannon framed information as the reduction of uncertainty, measured in bits, the average surprise you get from an event given what you already know. Fast-forward to learning algorithms, and your training data is this finite message from the world, carrying a mix of signal (the true underlying function you’re after) and noise (random fluctuations). Your model, with its inductive bias, is essentially a decoder trying to extract that signal. But here’s the rub: the channel, the way data flows to you , is noisy, and your decoder has limited capacity because of the assumptions you baked in. If your hypothesis class is too restrictive (high bias), you’re ignoring bits of information that could refine your understanding; if it’s too flexible (high variance), you’re latching onto noise, amplifying uncertainty instead of quelling it. It’s like trying to transmit a photo over a spotty line: too much compression, and faces blur into guesses; too little, and you’re drowning in artifacts.</p><p>This ties straight into PAC learning, that framework from Valiant in the 80s that gave us a way to talk about learnability without hand-waving. <em>Probably Approximately Correct</em> learning says, roughly, that for a concept class to be learnable, there needs to be a way to sample hypotheses such that with high probability, you get one that’s close to the truth, using a polynomial number of examples. The VC dimension pops up here as a measure of your hypothesis class’s complexity, how many points it can shatter, or fit arbitrarily without regard for labels. Take a simple example: in binary classification, a linear separator in 2D has VC dimension 3, meaning it can shatter three points (fit any labelling) but not four in general position. That’s your classic high-bias setup, great for linearly separable data, like plotting species by petal length and width in the iris dataset, where a straight line slices things cleanly. But toss in some quadratic interactions, say if species boundaries curve around, and that linear bias leaves you with systematic underfitting: your error stays stubbornly high because the class can’t capture the bends.</p><p>Now crank it up: a polynomial threshold function of degree d in one dimension has VC dimension roughly d+1. So a degree-1 line fits straight trends with low variance on noisy data, change the sample, and your slope doesn’t jiggle much. But go to degree 10, and suddenly you can shatter 11 points, weaving through any wiggles in your training labels. On a sine wave corrupted by Gaussian noise, that high-degree fit hugs the samples too tightly, so a slight shift in the noise across runs sends your curve all over the place, classic high variance, where test error spikes because you’re chasing ghosts. In deep nets, it’s even wilder: their effective VC dimension can balloon to exponential in layers and width, letting them interpolate any dataset, but at the cost of sample-hungry variance unless you regularize. PAC bounds tell us the sample complexity grows with VC dim over epsilon squared, so for those overparameterized models, you need mountains of data to tame the variance, or your generalization guarantees evaporate.</p><p>And don’t get me started on how this echoes in the mutual information lens, often called the “<em>information bottleneck.</em>” The core idea is to find a compressed <em>representation</em> of your input that is still highly <em>predictive</em> of the final answer. You’re trying to achieve two conflicting goals at once: first, make this compressed version tell you as much as possible about the target output (how much “smarter” you get about the answer just by looking at the compressed data). Second, you want to squeeze the <em>original</em> input down as much as possible, forcing the model to discard “junk” details. It’s a direct tradeoff, like rate-distortion theory in compression: you balance squeezing the data hard to ditch noise (compression) against keeping just enough detail to preserve the true signal (fidelity). In a neural net, the early layers might compress by forgetting irrelevant pixels in an image, funneling down to features like edges. But push too hard on compression, and you create <strong>bias</strong>, systematically throwing away useful details (like fine-grained textures that distinguish cat breeds). Ease up too much, and <strong>variance</strong> swells as the net retains pixel-level noise, overfitting to training artifacts.</p><p>In practice, when I train a model, I see this tradeoff play out in the diagnostic plots. In the early epochs, the compressed representation doesn’t tell you much about the final answer because the net hasn’t learned <em>what</em> to keep. This is high bias; predictions stay generic. Then, as the layers fit, the representation gets more and more predictive. But if the model <em>also</em> starts holding onto too much raw, uncompressed information from the input, variance takes over, memorizing quirks like specific training batch orders. Tools that estimate this “bottleneck” help me diagnose the problem: I can literally plot how <em>predictive</em> the internal representation is against how <em>compressed</em> it is. The resulting curve shows the “efficient frontier” of this tradeoff, much like a bias-variance curve. It’s why techniques like dropout feel so intuitive, they are, in effect, hacks to <em>force</em> this bottleneck, compelling the net to generalize by forgetting the noise.</p><p>Instead of just tweaking knobs, I’m asking: what bits am I systematically dropping (bias), and which noise bits am I hoarding (variance)? What’s my effective VC dim telling me about sample needs? The goal isn’t zero error on training data but a bound on the deviation between expected and empirical risk.</p><p>As we saw, learning is a battle between compression and fidelity through lenses like VC dimension and information bottlenecks. It’s time to get our hands dirty with the actual breakdown that quantifies the pain. We’re talking squared error loss here, the go-to for regression, but the ideas ripple out to classification too via things like cross-entropy surrogates.</p><p>Let’s set the stage without getting lost in notation. Imagine you have a true underlying relationship between inputs and outputs, plus some irreducible noise that’s just part of the world, random flips you can’t predict, no matter what. Your training data is a bunch of samples drawn from this, and you fit a model to predict outputs for new inputs. The key trick in the decomposition, to consider what happens when you average over many possible training sets of the same size, all sampled from the same distribution.</p><p>Start with the expected test error at a fixed input point: that’s the average squared difference between the true output (including its noise) and your model’s prediction, where the average is over all possible training datasets and noise instances. Now, break it down step by step. First, think about the average prediction your learning algorithm would make across all those training sets, call that the central tendency of your predictor. The bias part comes from how far this average prediction sits from the true signal (ignoring noise for a moment); square that gap, and you’ve got the systematic error squared, the cost of your model’s assumptions missing the mark consistently.</p><p>Then there’s variance: for each training set, your prediction jiggles around that average one. Measure how much it deviates on average, square those deviations, and sum them up — that’s the variance term, capturing sensitivity to the particular quirks in your samples. Add in the irreducible noise variance, which is always there, no matter how perfect your model, and boom: the total expected error is just bias squared plus variance plus noise. It’s additive in this squared-error world, a clean split that shows why cranking model complexity lowers bias (your average predictor gets closer to the truth) but pumps variance (predictions scatter more across samples).</p><p>In practice, this decomposition is why we mock up multiple train-test splits when prototyping. Fit on one bootstrap sample, predict on held-out, repeat a hundred times, and average the squared errors, subtract the estimated noise (from residuals on a huge dataset or known sigma), and what’s left splits into bias (difference between overall average prediction and truth proxy) and variance (spread of predictions). It’s not perfect for finite data, but it beats guessing. And in VC theory terms, low-capacity models keep variance tight but bias high if the target complexity exceeds their shatter limits; high-capacity ones flip it, interpolating training but exploding on variance until data volume catches up.</p><p>This breakdown isn’t just fancy stuff, bias too high? Loosen the inductive bias, add capacity. Variance dominating? Regularize, gather more data, and ensemble. But as we’ll see next, modern overparameterized models laugh at the classic U-shaped curve this implies.</p><p>Now that we’ve got the classic decomposition under our belt, that tidy bias squared plus variance plus noise splitting the error pie, it’s tempting to sketch the usual U-curve: plot test error against model complexity, watch it dip to a minimum before climbing back up as overfitting kicks in. I leaned on that graph for years, using it to justify pruning layers or adding dropout when things went south. But then I stumbled into the double descent phenomenon, and suddenly the whole picture felt like a relic from a simpler era. It’s this empirically observed pattern where test error doesn’t just bottom out and rise; instead, it descends again after the point where the model starts perfectly fitting the training data, challenging the idea that more complexity always means more variance trouble. What gives? In the overparameterized world of modern deep learning, where models have way more parameters than training examples, the bias-variance tension morphs into something more forgiving, and sometimes even beneficial.</p><p>Thing kicked things off with a simple setup: kernel ridge regression using random features, like those Gaussian kernels you might use for non-linear regression on toy data such as a noisy 1D sine wave. You fix your training set size, say 100 points, and gradually increase the number of random features (your model complexity). Up to around 100 features, the model underfits a bit, test error decreases steadily as bias drops. Hit exactly 100 features, and it interpolates the training data perfectly (zero train error), but test error peaks right there, a classic overfitting hump where variance is raging because the fit is memorizing noise. But then, keep adding features, say up to 1000 or more, and instead of error climbing higher, it starts dropping again, often landing lower than the classical minimum. Why? The extra parameters don’t just add chaos; they create a space of many possible interpolating solutions, and the ridge regularization (or equivalent) nudges toward smoother ones that generalize better, effectively reducing variance through this overabundance.</p><p>Scaling to deep nets amps up the drama. Take a convolutional net on MNIST or CIFAR-10: with a small network (say, a few thousand params), you get the standard U: error falls then rises. But widen it to millions of params, train until train loss is zero (interpolation), and test error might tick up briefly, then keep falling as you add depth or width. Tying this to theory, double descent connects to how optimization behaves in overparameterized spaces, and that’s where neural tangent kernels (NTK) come in as a key explanatory tool. The NTK views a wide neural network during gradient descent as approximating a fixed kernel regression problem. Here’s the intuition without diving too deep: as your net gets infinitely wide (think thousands of neurons per layer), the weights barely change during training because gradients average out, and the network’s evolution looks like kernel ridge regression on a special kernel derived from the architecture, the NTK itself. This kernel captures the “tangent” space of functions the net can learn at initialization, evolving slowly.</p><p>In double descent terms, NTK to bound the behaviour: in the underparameterized regime, the kernel is low-rank, high bias; at interpolation, it matches the data but variance spikes if the kernel’s eigenvalues are spiky (amplifying noise); overparameterized, the kernel becomes full-rank, smoothing out predictions via its spectrum, leading to the second descent.</p><p>But here’s the paradox: if double descent means we can crank up capacity without the variance penalty biting as hard, why do we still need all those regularization tricks? Why does my transformer still hallucinate on out-of-distribution prompts unless I fine-tune with care? The answer is that the second descent isn’t free; it demands massive data to explore that manifold effectively, and without it, you’re just sampling bad interpolators. Plus, in non-convex deep landscapes, the implicit bias of SGD toward max-margin or low-norm solutions only goes so far; noise in gradients can still steer you to sharp valleys. It’s a reminder that while the tradeoff curve might double-dip, the underlying tension between bias (from architecture choices) and variance (from sampling and optimization) hasn’t vanished; it’s just reshaped for the era of giants.</p><p>This modern twist forces a rethink: maybe the old U-curve is a local minimum, and overparameterization lets us escape to global betterment, but only if we understand the inductive priors steering us there.</p><p>With the double descent curve bending our expectations and showing that overparameterization can sometimes buy us better generalization without the full variance hit, it’s easy to feel like the bias-variance tradeoff is more suggestion than rule these days. Start with regularization, that broad umbrella for constraining your hypothesis class to fight variance while chipping at bias. In classical stats, it’s as old as ridge regression, adding an L2 penalty to the loss to shrink coefficients toward zero, effectively lowering the effective degrees of freedom. L1 for sparsity (lasso-style, forcing irrelevant features to zero, which echoes VC dimension reduction by pruning the shatterable space), dropout that randomly zeros neurons during training to simulate ensemble averaging, and even early stopping when validation loss plateaus, implicitly bounding the capacity via optimization time. From a PAC lens, these are sample-efficient hacks; by controlling the complexity term in VC bounds, you tighten generalization gaps without needing exponentially more data.</p><p>Validation is the compass here, the ritual that lets you peek at the tradeoff without peeking at the test set. Cross-validation, k-fold style, averages performance across held-out folds to estimate the expected error from our decomposition, smoothing out the sample variance in your bias-variance split. But in high dimensions, where double descent lurks, plain k-fold can mislead if folds don’t capture distribution shifts. Plot train vs. val loss, and if val starts climbing while train hugs zero, variance alert, dial up L2. If both plateau high, bias is the culprit; widen the net or tweak the architecture’s inductive prior.</p><p>We’ve journeyed through the layers now: the No-Free-Lunch theorem forced our hand to pick a worldview, and the bias-variance tradeoff is the ongoing audit of that choice, the meter running on how well it holds up against the world’s mess.</p><p>Think about it in the round: inductive bias sets the stage, constraining your hypothesis class to something learnable under PAC guarantees, with VC dimension as the ticket price for sample efficiency. But that constraint inevitably injects bias, the systematic skew from assuming, say, smoothness in a Gaussian process or locality in a convolutional filter. Variance then tests the glue, how much does your fit wobble when the samples shift, amplified by the flexibility you bought with that dimension? The decomposition quantifies the bill, while double descent whispers that in high dimensions, you might overpay in parameters but get a discount on variance through implicit regularization, like SGD’s lazy paths in NTK space. It’s a full circle: your chosen bias isn’t static; it’s dynamically traded against variance in every training run, shaped by data volume, optimization, and the regularization levers we pulled in the last section.</p><p>This is the deeper implication, beyond any one technique: in an era of foundation models hoovering petabytes, the tradeoff enforces humility. Even with billions of params, you’re still paying for your worldview, bias from tokenization assumptions in LLMs, variance from finetuning on niche corpora. Connect the dots wrong, and your inductive prior becomes a liability; align it with the decomposition’s guidance, and it scales. The world’s not handing out free lunches, but understanding this price tag? That’s how you eat well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d0ceba6377b" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/the-tightrope-of-generalization-4d0ceba6377b">The Tightrope of Generalization</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[No Free Lunches for the Wicked]]></title>
            <link>https://medium.com/@ankitkpandey1/no-free-lunches-for-the-wicked-ae8720744855?source=rss-285c7ae18b08------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae8720744855</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[nfl]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ankit K Pandey]]></dc:creator>
            <pubDate>Sat, 25 Oct 2025 14:37:37 GMT</pubDate>
            <atom:updated>2025-10-25T14:37:37.914Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first read about the No Free Lunch theorem. It felt like the rug was pulled out from under me. I was excited about models and architectures, and the theorem basically said something like: averaged over every possible problem, no algorithm is better than any other. Okay? Interesting!<br>Now if that’s true, how does any learning model works well in practice? Why does a convolutional net crush it on images while a random forest might do better on tabular data? Answer to that lies in fundamental understanding of how learning works; it is assumptions that we make about problem is what makes or breaks our model.</p><p>Again, implications are much more than neural nets, any assumption in right direction can give significant head start (there you go, all multi shot learning enjoyers, giving examples were not waste of tokens after all).</p><h3>No Free Lunches for you</h3><p>The core idea is simple. Imagine every possible problem you could ever ask a learning algorithm to solve. Now average an algorithm’s performance across that entire set of problems. Do the same for another algorithm. The NFL result says the averages are the same. In other words, there is no universally best learner when you consider every conceivable task. (<a href="https://www.cs.ubc.ca/~hutter/earg/papers07/00585893.pdf">Wolpert, 1996</a>).</p><p>Treating every possible input to output mapping as equally likely is a deliberate, neutral modelling choice. It makes the setup symmetric so there is no hidden preference for any family of tasks. Under that symmetry you can take any advantage an algorithm has on some mappings and build matching mappings where that advantage vanishes or reverses, so when you average over the whole space the wins and losses balance out. I like to think of it as a bookkeeping trick: if you start with no prior favourites, every welcome surprise for one learner has a mirror that punishes it somewhere else.</p><p>But why no hidden preference? In practice those are all the design choices you make before seeing data. Picking a hypothesis class or model family, choosing a loss function or regularizer, deciding on architecture and connectivity, preferring smooth or sparse solutions, even the way you initialize and optimize the model , all of these choices encode which input-to-output mappings you consider more plausible. When you pick a convolutional architecture you are explicitly betting on locality and repeated patterns. When you prefer simpler models you are implicitly saying complicated mappings are unlikely. Those bets tilt the uniform view into a focused one, and that focused view is what lets an algorithm outperform others on the subset of problems you actually care about.</p><p>It means something important: if an algorithm does well on the set of problems you actually care about, it must be making assumptions about those problems. It cannot be a blank slate that magically learns everything equally well. To succeed we must bake in some guesses about the world.</p><blockquote>This has some very important implications. If you make wrong assumptions about problem, no matter how hard you try, your algorithm is not going to perform any better.</blockquote><h3>Enter Inductive Bias</h3><p>So, if the NFL theorem forces our hand, and we <em>must</em> make assumptions, what does that look like in practice? This is where the concept of Inductive Bias comes in. It’s a fancy phrase, but it just means the set of built-in assumptions an algorithm carries into learning. It’s the set of preferences or constraints that guides a model toward certain answers before it even sees a single data point.</p><p>For example, imagine you’re given a dataset of points and asked to draw a line that fits them. Even with a small number of points, there are an infinite number of possible lines that could pass through them all. How does the algorithm choose? Without a bias, it can’t. It would be stuck in a state of infinite indecision. The inductive bias is the rule that breaks the tie. It’s the algorithm’s innate preference for, say, the <em>simplest</em> line that fits the data reasonably well (which points should I pick first?). That preference for simplicity isn’t in the data; it’s in the algorithm’s design.</p><p>That’s how it works, fundamentally. It’s a guiding mechanism. Since learning is about going from specific examples to general rules (that’s the “induction” part), we need a way to choose one general rule over another. The bias is that chooser.</p><p>The implication of this is massive. It means that there is no neutral learning. Every model, from a simple linear regression to a 100-billion parameter transformer, is pre-loaded with a worldview. Its success isn’t just about the quality of your data (or probably it is, as current state of LLMs goes) or the sheer number of parameters, but about how well its built-in biases match the hidden structure of your specific problem.</p><p>This leads to a crucial assumption we have to make: that the world, or at least the slice of it we’re trying to model, has some kind of structure that our bias can latch onto. Our preference for simplicity assumes the world isn’t needlessly complex. A CNN’s bias for local patterns assumes that the important signals in an image are in the relationships between nearby pixels. We’re making a bet.</p><p>And that’s ultimately why it works. We are not trying to build a god-like solver for all possible universes. We are building tools for <em>this</em> universe, which does have structure, patterns, and regularities. By carefully choosing our inductive bias, by making an educated guess about the nature of our problem, we narrow the search space from an impossible “everything” to a manageable “things that are likely to be true.” The reason a CNN can recognize a cat so well isn’t just that it learned from a million cat pictures; it’s that its architectural soul was already primed to understand the visual world. The learning process is just the refinement of a very good, pre-existing hunch.</p><h3>Seeing the Bias in Action: Neural Networks</h3><p>Take dense feedforward networks. Their connectivity assumes that every output depends on all inputs through layers of features. That architecture biases them toward learning hierarchical, compositional representations: build simple features and combine them to form complex ones. That’s an assumption about the kind of structure the data has.</p><p>Now look at convolutional neural networks, the canonical example. Their architecture literally encodes assumptions about images.</p><ul><li>Locality. Convolutional kernels look at small neighbourhoods. That encodes the idea that nearby pixels interact more strongly than distant ones.</li><li>Translation invariance. The same kernel is applied across the image. That encodes the idea that a feature is useful wherever it appears.</li><li>Spatial hierarchy. Stacking layers and using pooling creates progressively larger receptive fields. That encodes the idea that simple local patterns compose into larger structures.</li></ul><p>They are explicit inductive biases. Because images actually obey those properties to a large extent, CNNs get a huge head start. They do not have to learn translation invariance from scratch. The architecture gives it to them. That’s why a properly designed convolutional net tends to work very well on vision tasks.</p><p>A quick contrast: if you took the same CNN architecture and applied it to sequences where locality and translation invariance don’t hold, you’d expect worse results. The bias no longer matches the structure of the problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*2V9_R52PJIBnrA1vE_fQPw.png" /><figcaption>Examples of inductive bias</figcaption></figure><h3>Closing Thoughts: The learning part</h3><p>Putting this together changed how I think about models. The NFL theorem tells us there is no free lunch. Fine. Inductive bias tells us how to choose our meal. Every model carries a story about the world written into its design. When that story matches the data-generating process, you get a head start. When it does not, the model struggles. So rather than asking which algorithm is universally best, I now ask which story fits my problem. That question is where the real design work happens.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae8720744855" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agents go brrrrrrr]]></title>
            <link>https://blog.devgenius.io/agents-go-brrrrrrr-6075eb6fc1ba?source=rss-285c7ae18b08------2</link>
            <guid isPermaLink="false">https://medium.com/p/6075eb6fc1ba</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Ankit K Pandey]]></dc:creator>
            <pubDate>Sat, 04 Oct 2025 14:01:23 GMT</pubDate>
            <atom:updated>2025-10-10T12:50:36.721Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*gSr0n7op14id4znKuap1FQ.png" /></figure><p>It is amazing how many problems can be solved by agents now but getting them right is still a pain as they are pretty bleeding edge right now. This article is some of the learnings that I had with agents since past year or so. These may or may not work for you, but it’s good to share these insights so that rational choices can be made while building agents. Idea is that you:</p><h3>1. Use agents only when needed</h3><p>Main idea: not needed for orchestration tasks where no need to decide next steps. Eg if task flows like step1 → step2 → LLM → step3, no need of agent, use foundation models directly.</p><p>Remember fundamental rule of decision (applies to humans too). Do not decide when you don’t have to. Why? Making decision is tedious, mental energy is limited. Every decision has cognitive load, takes mental resources. Time spent on trivial decisions (opportunity cost) is time not spent on important ones. Too many decisions leads to fatigue, you are spending more time on frivolous stuff rather than one which really need attention. Plus context switching overhead, switching between decisions has cost.</p><p>For agents, same problems exist. Decision fatigue = token budget depletion. Cognitive load = context window filling up with decision logic (mostly useless), attention mechanism may not work out in our favour. Each decision point is also potential failure point where agent might pick wrong option.</p><p>Also on same line, if it’s possible to do job X without agents, just do it. Deterministic systems (plain old code) &gt; uncertain systems (agent).</p><h3>2. Make decisions simple</h3><p>From decision theory, decision under uncertainty is tricky as you don’t know probabilities of outcomes, just that multiple outcomes exist. In agents, this happens when tool returns vague error, external API might be down, or you don’t know if user input is valid: agent has to decide next step without knowing what will work (how can it recover from unusual error? should it ask user for clarification or make assumptions?). You have bunch of strategies:</p><p>minimax/maximin: minimize worst loss or maximize worst gain (pick option where worst-case scenario is least bad, like choosing restaurant where even their worst dish is edible, how agents are really supposed to decide that? This might be somewhat alleviated by good defaults, eg if user’s intent is not clear, do X)</p><p>min regret: minimize maximum regret (pick option you’ll regret least if wrong, like limit=10 in API GET calls or some SQL query)</p><p>Problem is, agents can’t compute these properly, unless we set some sensible default and getting that ‘sensible’ default requires domain expertise or at least good knowledge of business context in which agent is operating.</p><p>Instead try to convert decision under uncertainty to decision under risk (where probabilities are known) or even better, decision under certainty. For example, by having tools return structured options with clear outcomes. Eg if any API call fails, instead of returning vague error, tool may capture it and simply return ‘Service unavailable, redirect to fallback’ (risk with known-ish outcomes). This transforms unbounded search space into finite choice set.</p><h3>3. Always set defaults (reduce choices to make)</h3><p>Do not decide where you don’t have to, eg setting batch size or limit in API. Why? Every parameter is additional entropy. If 90% of time limit=100 works, making agent decide this every time is waste of time, cost and context window. Remember each token in context window should be for solving problem.</p><h3>4. Offload work to plain old code</h3><p>Whether it’s fixed sequences or bookkeeping tasks, if you know what needs to happen, don’t make agent figure it out.</p><p>Eg if something requires step1 → step3 in fixed order, just write code that does it. If agent always needs init stuff, cleanup, or reporting, do it yourself (before/after calling agent). Why? Faster, less chance of error, less decisions for LLM, easier to use dumber models.</p><p>From complexity perspective, you’re reducing from O(n) decisions to O(1). Each decision costs latency + tokens + error probability. Fixed sequences and deterministic operations are just state machines — using agent for them is like using ML to add 2+2.</p><p>This is about separation: agents handle policy (what to do), code handles mechanism (how to do it). Running mechanical, deterministic operations through probabilistic system is wasteful. It’s like using random number generator to compute pi (which is as useful as mining bitcoin…wait, I take my words back).</p><h3>5. Keep track of context length</h3><p>Instead of returning raw values from tools, parse it and return only relevant. Eg there may be sql_query tool, it maybe have query like select * from xyz and that might return 1000 rows, you can just limit output to say 10 rows and say more and let LLM decide if they need any specific filtering.</p><p>Why matters: LLMs perform worse as context fills up. Eg some interesting papers like “Lost in the Middle” shows models struggle to retrieve info from middle of long contexts, degrading to &lt;60% accuracy at full context. NoLiMa benchmark shows even GPT-4.1 drops from 95.6% at 1K tokens to 64.7% at 128K (effective length only ~16K), GPT-4o even worse: 98.1% at 1K to 56.0% at 128K (effective length ~8K). More irrelevant tokens = more noise = worse decisions.</p><p>Tool outputs should do progressive disclosure returning summary + samples, not full dumps. Let agent request specifics if needed (lazy evaluation).</p><h3>6. Agent is only as good as its tools</h3><p>Keep tools as dumb as possible (minimum arguments, pydantic types instead of dict, ambiguity next to none etc). Eg once I’ve seen a tool call function get_projects(…)-&gt; None | list[Projects], name itself doesn’t make sense to me, will it get me one project or multiple? I need to handle None too, blah blah. Keeping it simple and dumb like get_project, list_project makes it pretty obvious what tool does, and helps agent to decide quickly. Also thoroughly test tools and add all retry in tool rather than leave it up to agent. Eg if tool is summarize_text(text)-&gt; str, whether to retry and not should be up to summarize_text, no need to bother agent with internal details (how can agent even decide that? eg say token is expired, agent has no way to recover that).</p><p>Overall, make decision as dumb as possible, make it easy to decide, do as much as possible yourself and leave only things that depend on dynamic conditions to agent.</p><p>This is my favorite approach in solving any agentic problem: put yourself in agent’s shoes. If for given conditions/environments, if I have trouble solving the problem and can’t decide what to do next (next toolcall or reply back etc), no way agent can do that. Then my way out is — how can I make my life easier? Once I do that, I arrive at pretty dumb and simple solution.</p><p>Here’s the mental model: imagine you’re the agent, you’re lazy (as you should be), you don’t want to make unnecessary decisions, and you’d rather use existing solutions than figure things out from scratch. What would make your life easiest? That’s your design principle.</p><p>Many cases once you make decision dumb and simple, it actually becomes simple orchestration call and you just need to make llm call somewhere (and use smaller models like gpt-5-mini instead of sonnet 4.5 which you had planned). You’re minimizing entropy of system: less uncertainty = more reliability, lower costs, better performance.</p><p>Make the work dumb, stupid, and simple. Simplicity is hard to achieve but it’s the only thing that reliably works.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6075eb6fc1ba" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/agents-go-brrrrrrr-6075eb6fc1ba">Agents go brrrrrrr</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A short guide to setting up Server Sent Events]]></title>
            <link>https://blog.devgenius.io/a-short-guide-to-setting-up-server-sent-events-0bfaf97cc0cd?source=rss-285c7ae18b08------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bfaf97cc0cd</guid>
            <category><![CDATA[server-sent-events]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[rest]]></category>
            <dc:creator><![CDATA[Ankit K Pandey]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 15:25:54 GMT</pubDate>
            <atom:updated>2025-02-27T16:38:56.055Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*59GDUsdgjaVggb-al_Z1sw.jpeg" /></figure><p><strong>What and why SSE?</strong></p><p>SSE (Server-Sent Events) enables a one-way connection from the server to the client, allowing real-time data streaming as it becomes available. This is quite useful for applications like chat interfaces, where LLMs (Large Language Models) can stream responses instead of waiting for the entire result to be generated. By these sending partial results to the frontend as they arrive, the app appears more responsive and provides users the ability to cancel requests if the output is not as per as expectations.</p><p>Note that you can’t send events from a client to a server, this is what separates it from websocket which allows bidirectional data flow.</p><p><strong>Backend</strong><br>Backend implementation is quite straightforward. Suppose you are going to implement it in Litestar, you can start by importing <a href="https://docs.litestar.dev/2/reference/response/sse.html"><em>ServerSentEvent </em></a>and passing it with generator.</p><pre>from litestar.response.sse import ServerSentEvent<br><br># your API<br>return ServerSentEvent(content=&lt;generator&gt;)</pre><p>For example:</p><pre>from typing import Generator<br>import time<br><br>from litestar.response.sse import ServerSentEvent<br>from litestar import Litestar, get<br>from litestar.config.cors import CORSConfig<br><br><br>def read_file() -&gt; Generator[str, None, None]:<br>    with open(&quot;file.txt&quot;, &quot;r&quot;) as f:<br>        while True:<br>            line = f.readline()<br>            if line:<br>                yield line<br>            else:<br>                time.sleep(1)<br><br><br>@get(&quot;/&quot;)<br>async def get_text() -&gt; ServerSentEvent:<br>    return ServerSentEvent(content=read_file())<br><br>cors_config = CORSConfig(allow_origins=[&quot;http://localhost:5173&quot;], allow_credentials=True)<br>app = Litestar([get_text], cors_config=cors_config)</pre><p>Here, read_file returns a generator, but it can be any function that <em>yields</em>. Note that this can also be async generator.</p><p><strong>Frontend</strong></p><p>Assuming that axios is used. Creating its instance.</p><pre>const baseURL = &#39;API&#39; // sse API<br><br>const API = axios.create({<br>  baseURL,<br>  timeout: 300000, // this needs to be long time because connections are <br>  // alive for long period<br>})</pre><p>Call the API.</p><pre>  const response = await API.get(&quot;/&quot;, {  <br>    responseType: &#39;stream&#39;,  // Required to get stream of data<br>    headers: {<br>      &#39;Content-Type&#39;: &#39;application/json&#39;,<br>      &#39;Accept&#39;: &#39;text/event-stream&#39; // expects to receive a server-sent event stream<br>    },<br>    adapter: &#39;fetch&#39;, // see https://github.com/axios/axios/issues/5806<br>  });</pre><p>Setting <em>responseType </em>as stream returns result as <a href="https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream">ReadableStream</a> which can be decoded via <em>TextDecoderStream</em>. This is required because stream is sequence of bytes.</p><p>Once the reader is present, it can be iterated to get individual chunks of response.</p><pre>  const stream = response.data;<br>  const reader = stream.pipeThrough(new TextDecoderStream()).getReader();<br>  let buffer = &#39;&#39;; // this is where you can store your results<br>  while (true) {<br>    const { done, value } = await reader.read(); // loop over chunks<br>    if (done) break;<br><br>    buffer += value;<br>    const lines = buffer.split(&#39;\n&#39;);<br>    buffer = lines.pop() || &#39;&#39;;<br><br>    lines.forEach(line =&gt; {<br>      if (line.startsWith(&#39;data:&#39;)) { // sse adds &#39;data:&#39; prefix before content<br>        const dataContent = line.substring(5).trim(); // remove &#39;data:&#39;<br>        msg.value += dataContent + &#39;\n&#39;; // consume each chunk<br>        // ... update DOM<br><br><br>      }<br>    });<br>  }</pre><p>Refer demo repo for an sample demo: <a href="https://github.com/ankitkpandey1/sse-demo">https://github.com/ankitkpandey1/sse-demo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bfaf97cc0cd" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/a-short-guide-to-setting-up-server-sent-events-0bfaf97cc0cd">A short guide to setting up Server Sent Events</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Paging]]></title>
            <link>https://blog.devgenius.io/understanding-paging-a0152898df61?source=rss-285c7ae18b08------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0152898df61</guid>
            <category><![CDATA[assembly]]></category>
            <category><![CDATA[paging]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[x86]]></category>
            <category><![CDATA[kernel]]></category>
            <dc:creator><![CDATA[Ankit K Pandey]]></dc:creator>
            <pubDate>Sat, 07 Oct 2023 17:17:01 GMT</pubDate>
            <atom:updated>2023-10-11T14:38:55.331Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we’ll take a closer look at how paging works in the x86 architecture. We are going to focus on a very specific use case and grasp concepts while implementing it in code.</p><p>Let’s get started.</p><h3>What and Why?</h3><p><strong>What is paging?</strong></p><p>Quoting from CHAPTER 4 PAGING from Intel’s <a href="https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html">reference Manual</a> Vol 3.</p><blockquote>Paging (or linear-address translation) is the process of translating linear addresses so that they can be used to access memory or I/O<br>devices. Paging translates each linear address to a physical address and determines, for each translation, what accesses to the linear address are allowed (the address’s access rights) and the type of caching used for such<br>accesses (the address’s memory type).</blockquote><p>For example, consider two programs running on system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xtk4MqX-w_6-lSFDoZWVhQ.jpeg" /></figure><ol><li>Each program has its own address space (from 0 to 4 GB addresses). This is called virtual address.</li><li>Each program have access to full 4 GB of memory (virtually).</li><li>Memory address referred by programs can be overlapped.</li><li>Address which program sees as no relation with address which gets allocated in RAM (called physical address.</li></ol><p>Beside these, there are also memory protection schemes. All of these can be implemented via paging.</p><p><strong>Why do we need paging?</strong></p><p>Whenever system (any x86 CPU based computer) boots up, it always starts in 8086 mode (called as real mode). This is legacy mode which was created during initial days of 32 bit system (80386) to provide backward compatibility so that old software written for 8086 can run on new system based on 80386. Unfortunately, this backward compatibility stayed on even now. So, whenever newer systems boots up, it is booted into legacy mode. Issue in this mode is that 8086 had 20 address lines, which means it can refer to maximum 2 to the power 20 addresses i.e. 1 MB, this made sense in 80s but not now. Modern 32 bit system can refer up-to 4 GB of memory and 64 bit systems can go much higher. Issue is how do we change real mode (1 MB addressable) to full 4 GB addressable mode (this is called protected mode). This problem is solved by paging.</p><p>This allows all programs to start from 0x00000000 and refer all way upto 4 GB. It also allows to set permissions to different pages.</p><p>Thus, paging serves following purposes:</p><ol><li>Provide full access to all available address space.</li><li>Provide protection mechanism (as an alternative to segmentation).</li><li>Provide cache control and other features (huge pages etc).</li></ol><p><strong>How many types of paging are there?</strong></p><p>There are four paging modes available. This article is focused on 32 bit paging (for 4 KB pages). For rest of the modes (which includes multi level paging, PAE (Physical Address Extension) paging etc), refer Intel Manual.</p><h3>Terms</h3><p>There are some definitions which would make understanding paging lot easier.</p><p><strong>Page table entry (PTE)</strong></p><p>A row in page table mapping 4K addresses (thus called 4K page).</p><p>Page table entry looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BK0nVWAkQR1PCLMUHZHsuw.png" /><figcaption>PTE: 4k Page</figcaption></figure><p>Size of each PTE is 32 bits (4 byte).</p><p>More on flags are below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4_SrUskjYB9XqDNHBjzfnQ.png" /><figcaption>PTE for 4K page</figcaption></figure><p>Let’s consider bits from 31 to 12, as rest of the bits are using for setting up flag, PTE might look like (last 12 bits are 0, imagine multiplying whatever address you want to access by 0x1000)</p><p>PTE1: 0x00000000</p><p>PTE2: 0x00001000</p><p>Difference between PTE2-PTE1 = 0x1000 which is nothing but 2 to power 12 or 4K (4096).</p><p>Each PTE represent 4K addresses which is why it is called as 4K page. In application world, it means that you can get (or allocate) memory in multiples for 4K with 4K as smallest unit. If you need 10 KB of memory, you will require 100/4 = 25 4KB pages. If you need 101k, you will get 26 4K pages.</p><p>It is possible to refer 4 MB pages, 2 MB pages or even 1 GB pages, all called as huge pages.</p><p><strong>Page table</strong></p><p>Page table is collection of 1024 page table entries. It can visualized as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aTV60PqEw1t2mjUVV73ETA.jpeg" /><figcaption>Page table</figcaption></figure><p>Each row in Page table is a PTE (which occupies 32 bits or 4 bytes). As you can see, to represent 1024 PTE, it will require 4 bytes x 1024 = 4 KB of memory. Therefore, each page table (which occupies 4 KB of memory) can represent or map 4 MB of address space.</p><p><strong>Page directory</strong></p><p>Page directory is collection of 1024 page tables (called PDE). As each page can represent 4 MB of address space and thus, page directory can address full 4 GB of address space.</p><p>Page directory can both some 4 KB pages or 4 MB pages (or other huge pages). Each page table can have different sets of permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gAFsI616sujajsIQdqBewg.png" /><figcaption>Page directory for 4M page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yjl_eVuz0xwOJc7oGo6unw.png" /><figcaption>Page directory for 4K page</figcaption></figure><p>Once we start implementing paging, above flags will make more sense. Don’t worry about these now.</p><p>Important takeaway for page directory are:</p><ol><li>If we represent full 4 GB of memory by 4K pages only, it will need 4096*1024K/4K of memory, which is 1 MB. This is not much if system has 4 GB of memory but if we are running some embedded system which has 16 MB or 32 MB, 1 MB just for this is bit too much.</li><li>Since we can easily enable/disable pages by bit 0, we can allocate and enable pages per need basis. At any given time, all 1024 entries in page directory need to be filled.</li></ol><p>Notice how bits 31–12 are physical address of 4 K page table. We need difference of 4 K between each page table because each page table takes 1024 * 4 bytes.</p><p><strong>Translation lookaside buffer (TLB)</strong></p><p>Only reason I am bringing this up is to explain difference between 4 KB and 4 MB pages (see below). As you can see, whenever we request for any virtual/linear address, it needs to be looked up in page directory, then page table and finally PTE to find exact physical address. This is lot of work. For performance reason, this lookup is cached in memory cache called Translation lookaside buffer (TLB). It is part of MMU and reside somewhere between CPU and CPU cache. Whenever any memory address is requested, it is first checked in TLB for responding cache, if cache is missed, then lookup happen.</p><p>Important thing to consider here is that whenever you update page directory, ensure TLB gets invalidated using <a href="https://www.felixcloutier.com/x86/invlpg">invlpg</a> command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/0*h-fYBJnNAacor89A.png" /><figcaption>TLB</figcaption></figure><p><em>What is difference between 4 KB page and 4 MB page?</em></p><p>As far as implementation is concerned, nothing much. In case of 4 MB page, instead of mapping a page table (containing 1024 4KB page entries), we map just one entry for page table, which maps whole 4 MB.</p><p>Main reason why we need 4 MB pages is performance impact of 4 KB pages on TLB.</p><p>Consider that you need to allocate 100 MB. If you use 4KB pages, you will need 100*1024/4 which is some 25.6k pages. That is lot of entries for TLB to cache (remember they are going to take 102 KB of memory, which is a lot as far caching is concerned). Instead of using 4KB pages, if you use 4MB pages, you will need only 25 page, this will easily fit in cache and performance will be lot better than 4 K pages. But in case of 4 MB pages, there can be lot of wasteful resources. Eg, if you need 4.1 MB, you will be getting 2 4M pages, which is 8 MB of memory. Almost 50% of memory is wasted.</p><p>In real world, you will be using some 4KB pages and some 4 MB pages and assigning them as per as demand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*Kw0JsgnLzsYpfgq0G2DG9A.png" /><figcaption>Linear Address translation in case of 4KB page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*r7KqvfZnRtiv0I9jEbykiA.png" /><figcaption>Linear Address translation in case of 4MB page</figcaption></figure><p>In case of 4MB pages, you can clearly see page directory directly refer to 4 MB address space, instead of going it via 1024 4KB PTE.</p><h3>Use case</h3><p>Above all is just gravy, let’s jump into actual stuff. Consider following use case:</p><ol><li>Enable paging.</li><li>Map first 0–1 MB and higher half (0xC0100000) to first 1 MB.</li><li>Leave other pages as not present.</li></ol><p>Wait what?</p><p>Since paging maps virtual/linear address (this is address what program sees) to physical address (this is address what is mapped to RAM), therefore we can map first 4 MB of physical memory to both, uh..first 4 MB of virtual memory and 0xC0000000 (which is 3 GB). In other words, physical address 0x00010000 can be mapped to both 0x00100000 and 0xC0100000 virtual addresses.</p><h3><strong>Approach</strong></h3><p>In order to solve aforementioned use case, we need to:</p><ol><li>Fill two pages (corresponding to first 4 MB and 3 GB).</li><li>Copy address of above pages to page directory.</li><li>Enable paging.</li></ol><p>For sake of simplicity, we will be using 4KB pages.</p><h3>Implementation</h3><p>We will be setting up paging using assembly (NASM). Doing it in C is bit easier but this has to be done in assembly if you are designing higher half kernel (which is what this use case is about). Also, it helps to understand mechanism in much better way as you are in fine grain control the setup process.</p><p><strong>Step 1: Map up first 4 MB using 4K pages</strong></p><p><em>Figuring out bits of PTE</em></p><p>Recall structure of 4KB PTE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*x4dDeITlLucbYXa3fiPvkQ.png" /></figure><p>bit 0: 1</p><p>bit 1: 1, let’s allow read and write</p><p>bit 2: 0, only super user can access</p><p>bit 3: 0, Page-level write-through</p><p>as per as docs:</p><blockquote>PWT — Page-level write-through. The state of this flag is driven on the PWT# pin during bus cycles that are not paged, such as interrupt acknowledge cycles, when paging is enabled. The PWT# pin is used to control write<br>through in an external cache on a cycle-by-cycle basis.</blockquote><p>Whatever it is, we don’t need this, let’s keep it as 0.</p><p>bit 4: 0, Page-level cache disable: let’s not worry about this</p><p>bit 5: 0</p><p>bit 6: 0,</p><p>Above bits are for accessed or dirty, is getter bits, not setter bit.</p><p>bit 7: 0, <a href="https://www.kernel.org/doc/html/next/x86/pat.html">page-attribute table</a>: some exotic caching related stuff</p><p>bit 8: 0, for global translation. Not worrying about this either.</p><p>bits 11:9: ignored, so 0</p><p>bits: 31:12 physical address which we want to map</p><p>based on above, things looks like this:</p><p>0x&lt;physical address&gt;003</p><p>Therefore, first PTE will be mapping to address:</p><p>0 to 4K-1, we take first address as entry to PTE.</p><p>0* 0x1000= 0x00000000 i.e. all address between 0x00000000 to 0x00000FFF</p><p>will be mapped to this page.</p><p>Add flag (0x3) to above address (which is 4K aligned)</p><p>PTE= 0x00000003 (0x00000000 + 0x003)</p><p>Let’s see the second PTE as well.</p><p>1*0x1000 = 0x0001000 is starting address of 2nd PTE and it maps address between 0x00001000 to 0x00001FFF</p><p>Corresponding PTE = 0x00001003 and so on.</p><p>Last PTE in first page table;</p><p>(1024–1)*0x1000=0x003FF000 (4 MB-4KB)</p><p>PTE will be, PTE=0x003FF003</p><p>If someone wants to access 0x003FFFFF + 1 th address, they will have to access next page.</p><p>Above logic is implemented below.</p><pre>        xor ecx, ecx            ; ecx=0<br>        mov edi, page_table     ; copy address of page table<br>fill_page_table:<br>        xor eax, eax            ; reset eax<br>        mov eax, ecx            ; copy counter<br>        imul eax, 4096          ; counter will become 4k address<br>        or eax, 3               ; add flag<br>        mov [edi+4*ecx], eax    ; save result to page at correct index<br>        inc ecx                 ; increment counter<br>        cmp ecx, 1023           ; do while pages from 0-1023 are mapped<br>        jne fill_page_table</pre><p>Let’s run through code:</p><pre>xor ecx, ecx </pre><p>Reset ecx to 0. ecx is mainly used for counting which what we are using here as well. It is going to be incremented from 0 upto 1023 (where loop breaks).</p><pre>mov edi, page_table;</pre><p>Move page_table address to edi. page_table symbol need to be defined somewhere. In current case, it is defined in LINKER script (see link.ld in repo given below).</p><pre>fill_page_table: <br>        xor eax, eax<br>        mov eax, ecx ; i <br>        imul eax, 4096</pre><p>fill_page_table is first page table. In above code, we are copying counter (running from 0 to 1023) and multiplying by 4k or 0x1000.</p><pre>or eax, 3</pre><p>Once we have 4K physical address in eax, set bit flags for pages (which we determined to be 0x3). Add this to above address and you will get a PTE which is stored in eax.</p><pre>mov [edi+4*ecx], eax</pre><p>edi points to page table so here we are copying our PTE to page table location in memory + offset of current PTE. This means</p><p>PTE1 → address of page table</p><p>PTE2 -&gt; address of page table + 4 bytes</p><p>PTE3 -&gt; address of page table + 4 bytes + 4 bytes</p><p>Thus for Nth PTE, address will be page table address + (N-1)*4</p><p>Since, in code, we are starting from 0 (not from 1), we can directly put it as address of page + count*4.</p><pre>        inc ecx<br>        cmp ecx, 1023<br>        jne fill_page_table</pre><p>Increment loop counter, check if it equal to 1023, if not, jump to fill_page_table label else continue (its do while loop).</p><p><strong>Step 2: Map 0xC0100000 to 0x0010000</strong></p><p>Rinse and repeat same process as above.</p><p>Idea is to map first 4 MB again to <strong>0xC0000000.</strong></p><p>We know that we need to set 0x&lt;physical address&gt;003</p><p>Find page which contains 0xC0000000 (divide by 4 MB as each page maps 4 MB)</p><p>0xC0000000/0x0400000 = 768th Page</p><p><em>OR simply do 0xC0000000 &gt;&gt; 22</em></p><p>This page will be located at 768th * 4 bytes from start of page directory location (recall each page directory entry takes 4 bytes).</p><p>First PTE for 768th page will be as follows:</p><p>PTE768_1= 0x0000003 (0x0000000 + 0x003)</p><p>Next</p><p>PTE768_2= 0x0001003 (0x0001000 + 0x003)</p><p><em>This means if we request address from 768*4M (which is </em>0xC0000000<em> in virtual memory) to 768*4MB + 4MB-1 (which is 0xC00FFFFF), it will be mapped from 0x0000000 to 0x0000000</em>+<em>4MB-1 in physical memory.</em></p><p>Rest of the steps are same as step #1, keep adding 4K, 1024 times</p><pre>        xor ecx, ecx            ; ecx=0<br>        mov edi, 0x00000000     ; map first 4 MB<br>fill_page_table768:<br>        xor eax, eax<br>        mov eax, edi            ; copy address<br>        or eax, 3               ; add page flag<br>        mov [page_table+4*ecx+4096], eax  ; add to page with offset<br>        add edi, 4096           ; get next 4K address<br>        inc ecx                 ; increment counter<br>        cmp ecx, 1023           ; do till all 0-1023 entries are filled<br>        jne fill_page_table768</pre><p>Let’s quickly walk through.</p><pre>mov ecx, ecx ; ecx=0</pre><p>Reset counter as usual before starting.</p><pre>mov edi, 0x00000000     ; map first 4 MB</pre><p>Since we want to map first 4 MB to 3 GB, we will use same starting address of 0x00000000 so that first 4 MB gets mapped.</p><pre>fill_page_table768:<br>        xor eax, eax<br>        mov eax, edi ;<br>        or eax, 3<br>        mov [page_table+4*ecx+0x1000]<br>        </pre><p>Same as before, add 0x3 to physical address which we are mapping and then it is added to page table.</p><p>Most interesting part here is we are adding it to page table address + 4096 (or 0x1000). This is because first page used up entries from (page table + 0) to (page table + 4095). Hence, we are using offset 4096 to add entry for page which is going to map 3 GB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eD94bW8NXnl_XvtqsvM0yw.jpeg" /></figure><pre>        add edi, 4096</pre><p>Add 4K to offset address which we are mapping.</p><pre>        inc ecx<br>        cmp ecx, 1023<br>        jne fill_page_table768</pre><p>Continue loop until all 1024 pages are mapped.</p><p><strong>Step 3: Add entries in page directory</strong></p><p>It is two step process. Filling up page directory and then adding two tables.</p><pre>        xor ecx, ecx ; ecx=0<br>        mov edi, page_directory<br><br>fill_page_directory:<br>        mov eax, 0x00000000        ; set flag as not present    <br>        mov [edi+4*ecx], eax<br>        inc ecx<br>        cmp ecx, 1023              ; fill all 0-1023 PDE as not present<br>        jne fill_page_directory<br><br>        mov eax, page_table        ; copy first page table    <br>        or eax, 0x3                ; add PDE flag<br>        mov [page_directory], eax  ; add entry in page directory<br><br>        mov eax, page_table+4096    ; 768 page table is at page table + 4K<br>        or eax, 0x3                 ; add flag<br>        mov [page_directory+4*768], eax ; fill in directory at 768 pos</pre><p>Again, looking into code.</p><pre>        xor ecx, ecx ; ecx=0<br>        mov edi, page_directory</pre><p>Set counter (ecx register) to 0. Copy address of page directory to edi register.</p><pre>fill_page_directory:<br>        mov eax, 0x00000000;<br>        mov [edi+4*ecx], eax<br>        inc ecx<br>        cmp ecx, 1023<br>        jne fill_page_directory</pre><p>PDE (or page entry in page directory) is defined as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jkbeu9kw9DtPa0bjeUuKRA.png" /><figcaption>PDE for 4K page</figcaption></figure><p>bits 0 to 11 are used for flags, rest are address of page table.</p><p>Initially, we disable all 1024 pages by setting flags as 0x0 (bit 0: is 0 meaning disabled, rest of flags can be ignored).</p><pre>mov [edi+4*ecx], eax</pre><p>This is done by adding page directory address with 4 bytes for each entries and setting it all as zero (this means we have to allocate full 4 KB of memory for page directory). There no need to put address of page table as it disabled in current case but it is entirely possible to have correct page entry in page directory and simply setting use flags (bit 0) as 0 to disable it.</p><p>Let’s determine flag for each page by looking at <em>PDE for 4K page</em>.</p><p>bit 0: 1, present</p><p>bit 1: 1, write allowed</p><p>bit 2: 0, user mode is not allowed, doesn’t matter much in current case as we are in super user mode.</p><p>bit 3: 0, PWT, leave as disabled.</p><p>bits 4–6: 0, don’t care about these</p><p>bits 7: 0, ignore</p><p>bits 8–11: 0 ignore</p><p>So, we get page directory flag as 0x3 again.</p><pre>        mov eax, page_table<br>        or eax, 0x3<br>        mov [page_directory], eax</pre><p>Now that we have flag with us, we can easily OR address of page_table with flag and copy it to page directory.</p><p>Similarly, 768th page can be copied to page_directory + 4*768 bytes.</p><pre>        mov eax, page_table+4096<br>        or eax, 0x3<br>        mov [page_directory+4*768], eax</pre><p>Just a sanity check, if you see <strong>step 2 above </strong>where we are filling table 768.</p><pre>fill_page_table768:<br>        xor eax, eax<br>        mov eax, edi ;<br>        or eax, 3<br>        mov [page_table+4*ecx+0x1000]</pre><p>It can be seen that page 768 is at [page_table + 0x1000] (where ecx is 0 in when loop is started). We can have page tables anywhere, as long as their physical address is properly mapped to PDE, things will work fine. In current case, we are pushing this page entry to page directory at 768th position.</p><p><strong>Step 4: Enable paging</strong></p><p>It is very standard process. Load page directory to cr3 and enable paging by setting 31st bit in cr0 as 1.</p><p>Also, here we have enabled PSE (<a href="https://en.wikipedia.org/wiki/Page_Size_Extension">Page Size Extension</a>) by setting 4th bit to 1 in cr4 register to enable 4 MB huge pages (although not implemented).</p><pre>        ; Load the page directory base address<br>        mov eax, page_directory<br>        mov cr3, eax<br>        mov ebx, cr4               ; read current cr4<br>        or ebx, 0x00000010         ; set PSE<br>        mov cr4, ebx               ; update cr4<br>        mov ebx, cr0               ; read current cr0<br>        or ebx, 0x80000000         ; set PG<br>        mov cr0, ebx;              ; enables paging</pre><p>Implemented code can be found here: <a href="https://github.com/itsankitkp/paging_demo">https://github.com/itsankitkp/paging_demo</a></p><h3><strong>Conclusion</strong></h3><p>Setting up paging is pretty straightforward task but it does require some thought to correctly map addresses. In this article, we have barely scratch the surface of paging as there are lots of things that can be done (multi level paging, huge pages etc.) but it is hoped that setting those up will be bit easier from now on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0152898df61" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/understanding-paging-a0152898df61">Understanding Paging</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating your own kernel: Part 1 Genesis]]></title>
            <link>https://medium.com/@ankitkpandey1/creating-your-own-kernel-part-1-genesis-8cabad8dc448?source=rss-285c7ae18b08------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cabad8dc448</guid>
            <category><![CDATA[c-programming]]></category>
            <category><![CDATA[kernel]]></category>
            <category><![CDATA[assembly]]></category>
            <category><![CDATA[bootloader]]></category>
            <category><![CDATA[operating-systems]]></category>
            <dc:creator><![CDATA[Ankit K Pandey]]></dc:creator>
            <pubDate>Wed, 23 Aug 2023 18:34:24 GMT</pubDate>
            <atom:updated>2023-08-24T17:59:34.557Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>When I started reading Lion’s Book (<a href="https://www.google.com/search?client=ubuntu-sn&amp;sca_esv=558560939&amp;channel=fs&amp;cs=0&amp;q=A+Commentary+on+the+UNIX+Operating+System&amp;stick=H4sIAAAAAAAAAEWQv2_TQBTHfZVqnEsrxY4QUiYrCKlksX1xnGRKqwASVUulNkgwRY59_oF9vtR3Sm2P_AURQ-eKCST-gg4VYiNIHTowIMTAxgQjEyIZ4r7pfb7v-96TvtJmU9KIpvdfzSwED0KaMHVCabQApbwAcNVaLnH1swXY1nzNMCYd0rO6mbEAWytGE1Lkqa-vx17Ua7uIFGsOimiaFt2sZNOMXLMT365ngcm667FjkDE_7d_aU6sz9rOk_N499fSUx-W7mT_2zLOg9PccNu1l1pqZM4uyvl7eD5BlJDPDL7nNAxRZwU_wHVRrv_7-qDduwJsPn7-CLwDWDihlOM6PcWxz7I6ocg-KjxMe8lzZblRhZZVOGyHdVfZg9QTzET2kbujlClJ0WDnEZIJTduQp9yEc0jjGDl_GrNxt1KGsOaWgrWJnzZfoyeXN-bW4KwvL-nN1vNvYaclQfESJHSbyv-jBcOf9t0GrDqWRndGEklxm12Nh_87vQbNSWe6o84uPg5Yw3wCvr959EiUJ1AS0IQmFsPV28-GeOqSE4ITbaa7SROUBVp8_e_pCPZri1OZh4qsnOeOYzEXwHyoAzXAdAgAA&amp;sa=X&amp;ved=2ahUKEwj3q5LUr-uAAxU34jgGHTDnAooQ7fAIegQIABBi">A Commentary on the UNIX Operating System</a>), one thing quickly caught my eyes, actual implementation of some very common functions like putc were given there, which directly communicated with CPU (some PDP based minicomputers). As I always liked to do things while reading, I started to wonder, how exactly I can write my own version of putc (or any other function for that matter) which allows me to run arbitrary commands on CPU. Answer was simple, bare-bone kernel.</p><p>After spending much of time in reading and figuring things out, I was surprised that how much content on this was available on the internet, it is not an exclusive knowledge, everyone apparently builds one). Issues that I found with many existing articles was that most of these articles are bit dated or they missed few fundamental things. This inspirited me to write this article. Although it is not exhaustive as some other tutorials, it aims to address some most fundamental things (and give useful reference) in kernel development.</p><p>At end of this article, reader should have some knowledge about bootstrapping a kernel and what things that are needed to be considered before starting building your DIY kernel.</p><h3><strong>Pre-requisite</strong></h3><p>All code in this article are tested on Ubuntu 22.04, but feel free to use any distro of your choice as long as you have access to following packages:</p><ol><li>build-essential (for gcc and associated libraries)</li><li>qemu-system (for emulation of i386 system)</li><li>nasm (Assembler of choice)</li><li>mtools (it is used for manipulating MS-DOS files, nasm apparently needs this for some reason)</li><li>gcc-multilib (needed to cross compile 32 bit code on 64 bit host)</li><li>vim/git/vscode (fav editor, versioning tool etc.)</li></ol><p>Apart from these, lots of reading :)</p><p>Let’s get started!</p><h3>Simple program</h3><p>Let’s write a simple code in assembly as test.asm</p><pre>jmp 0x1234</pre><p>We are not much interested in running, rather aim is to analyze it piece by piece, hence such simplicity.</p><p>Compile it via</p><pre>nasm -f bin test.asm</pre><p>-f bin specifies output to be raw binary</p><blockquote>The bin format does not produce object files: it generates nothing in the output file except the code you wrote.</blockquote><p>Reason that we want to see raw binary is to know exactly what we are getting as output when we write a code. There no <em>façade</em> or runtime environment that comes with normal program.</p><p>Let’s look at hexdump of output</p><pre>hd test</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*uLjf_3XIRmJYsF2UEElumQ.png" /></figure><p>We can see three bytes e9 31 12, starting at address 0</p><p>Looking up Intel docs, we can see that E9 is opcode of JMP (specifically E9 cw section because we haven’t specified BITS, so it has build code as 16 bit code).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*eub-d77wp0abTmLPJLArjQ.png" /><figcaption>JMP instruction</figcaption></figure><p>Now, let’s try building 32 bit code</p><pre>BITS 32<br>add eax, ebx</pre><p>Result of hex dump</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*6vTuqwjjz2OHObZ_-_QwwA.png" /><figcaption>Short and sweet</figcaption></figure><p>Notice how it takes only two bytes. First byte is opcode</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*CXst7YcLsmcwq1DEwhJifQ.png" /></figure><p>What does d8 signify here? Let’s look up architecture format</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*a7Rlqex3H3S5oDbSOedarQ.png" /><figcaption>Intel 64 and IA-32 Architectures Instruction Format</figcaption></figure><p>We already know 01 is our opcode for add, d8 must be ModR/M.</p><blockquote>ModR/M: Many instructions that refer to an operand in memory have an addressing-form specifier byte (called the ModR/M<br>byte) following the primary opcode. The ModR/M byte contains three fields of information:<br>• The mod field combines with the r/m field to form 32 possible values: eight registers and 24 addressing modes.<br>• The reg/opcode field specifies either a register number or three more bits of opcode information. The purpose<br>of the reg/opcode field is specified in the primary opcode.<br>• The r/m field can specify a register as an operand or it can be combined with the mod field to encode an addressing mode. Sometimes, certain combinations of the mod field and the r/m field are used to express<br>opcode information for some instructions.</blockquote><p>Lookup table for ModR/M is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*I2k6ScTRwF-NFqTsaLQRMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*PDIfDs_neDWuH5Uq4SMgOw.png" /><figcaption>32-Bit Addressing Forms with the ModR/M Byte</figcaption></figure><p>In above chart, if we look at d8, we can see row as eax. Column provide another operand (if any). Here, we can see from column that next operand is ebx.</p><p>Similarly if we have code like below:</p><pre>BITS 32<br>sub eax, ebx</pre><p>Hex dump will contain same d8 as modR/M with opcode for SUB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*Q_y_YaVub4TR48u09HGfpg.png" /></figure><p>Let’s try something more complicated</p><pre>BITS 32<br>jmp [eax*2 + ebx]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*ox7B3kp5gJK4NdyRson83Q.png" /></figure><p>ff is opcode of jump, 24 is modR/M byte as usual. Looking up <em>32-Bit Addressing Forms with the ModR/M Byte</em> table again for 24.</p><p>Row shows [ — ][ — ] which means a SIB follows the ModR/M byte</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*WWDDDUnZdCBc-oEKpSZNdw.png" /><figcaption>32-Bit Addressing Forms with the SIB Byte</figcaption></figure><p>SIB byte is 43, which shows row as EAX*2 and column as EBX.</p><p>Apart from this, we can also see hex dump by, comes handy sometimes.</p><pre>nasm -l/dev/stdout test.asm</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*yU5EPN7KwYh98aj2x0LRAg.png" /></figure><p>At this point, you must have some idea how to look up hex dump of instructions and refer Intel manuals to understand what a particular instruction is upto (and if it is same as what we intended). It may seen over the top, it can come handy while debugging some very subtle bugs.</p><h3>ELF format</h3><p>There exists a certain executable format called ELF which is very popular in UNIX based/inspired systems. Understanding of ELF is important because it allows us to define entry point of our program, storage space and various other things</p><p>Technically speaking, ELF is format for storing program (or a fraction of program) in a disk after compilation and linking. ELF file is divided into number of sections, most important being:</p><ol><li>.text:</li></ol><p>This section contains code of the program.</p><p>2. .data</p><p>Data section for storing global variable.</p><p>Local (auto) variables are stored in stack.</p><p>3. .rodata</p><p>Read only data is stored here, eg strings</p><p>4. bss</p><p>Uninitialized data (uninitialized variables and arrays etc.)</p><p>Other sections of debugging and other purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*ffGXvpLQ5C_1HRF0.png" /></figure><p>More on this can be read on <a href="https://wiki.osdev.org/ELF">ELF</a> article in OSDev. These sections are discussed in details later in the article.</p><h3>ELF in action</h3><p>Having already seen basic structure of ELF format. Let’s see how it is put into practice.</p><p>Consider following (bit weird) program:</p><pre>int add(int a, int b)<br>{<br>        return a+b;<br>}<br>int main(int argc, char* argv)<br>{<br>        char* s=&quot;Hello World!&quot;;<br><br>        int sum;<br>        int list[]={1,2,3};<br>        return 0;<br>}<br></pre><p>Let’s compile and link it:</p><pre>gcc -m32 hello.c -o hello</pre><p>Let’s examine it now:</p><pre>readelf -hW hello</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*4OXHTzx3o3gaCD9PYgKlcw.png" /></figure><p>Above figure shows entries in file header of ELF file (-h option in readelf). First header, which is magic bytes, is used to identify if file is ELF complaint or not.</p><p>Since our program is complied as 32 bit program on GNU/Linux system, it shows required field as expected from such program (more on this at <a href="https://www.cs.cmu.edu/afs/cs/academic/class/15213-f00/docs/elf.pdf">ELF</a>).</p><p>As per as standard, ELF file looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*ujhWw5l5c4iuL2Y7oI6m-A.png" /><figcaption>ELF file layout</figcaption></figure><p>What we just saw was first section of the file, ELF header. Doing hex dump on program, we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*bdJuo1nB02lqiubtEz6zzQ.png" /></figure><p>This is in line with ELF file layout which says ELF executable/object file should start with ELF header.</p><p>The magic number in first line, i.e. 7f 45 4c 46 i.e. first four bytes identify file as ELF file.</p><p><em>7f 45 4c 46 </em>01 01 01 00 00 00 00 00 00 00 00 00</p><p>Next byte identifies machine size and so on</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*m-5TodOOGFfCb5CljgDHzw.png" /></figure><p>All of these are given in ELF specification</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*uGgy8dpEYEKsqcSQNFnMRA.png" /></figure><p>Internally, ELF file header is based on following struct:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*os_5s74A0ut67s0c8OVnuQ.png" /><figcaption>ELF Header Struct</figcaption></figure><p>There isn’t much interesting here (except for some obvious information) but main point of interest is e_entry, which defines entry point of our program.</p><p><em>e_entry: This member gives the virtual address to which system first transfers the control, thus starting the process. If the file has no associated enter point, this member holds zero.</em></p><p>In above program, entry point address is 0x1070. Question arises, what instruction do we have at this address? To know this, let’s generate assembly code of our hello.c.</p><pre>objdump -S hello</pre><p>Opening corresponding generated hello.s and looking at address 0x1070</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*flXDlOu6l8zg_RCEJvNESg.png" /></figure><p>This is not our main, this is something called _start. Not going into much details (refer <a href="https://wiki.osdev.org/Creating_a_C_Library">osdev entry</a> for this) but what is does is to initialize runtime environment for main. This includes stack initialization, some setup and calling <em>exit(main(argc, argv))</em>. All these things are came from something called crt0.o, which is inline assembly code containing c runtime initialization. This is important thing to know because when we roll out our kernel, we will need to similar setup get our C code working.</p><p>Moving forward, let&#39;s view program headers.</p><pre> readelf -lW hello</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mIPl_MZZwRXWnUdN_opt5g.png" /></figure><blockquote>Program header is array of structures which describes segment or information which system needs to prepare program for execution.</blockquote><p>PHDR provides program header information. INTERP contain path name of interpreter (/lib/ld-linux.so.2 here), whenever this program is loader, system creates initial process image from interpreter’s file segments, which means instead of using original executable file segment image, system composes memory image for interpreter, which then provides runtime environment for our program.</p><p>LOAD contains basically loadable elements (which gets loaded into memory, notice PHDR and INTERP are NOT something which we want into memory).</p><p>Section headers can be viewed by</p><pre>readelf -SW hello</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*j8qgbAUZ_1ruNx_3CuMdlQ.png" /></figure><p>Sections contains all the information for linking. Important sections are</p><blockquote><strong>.bss </strong>This section holds uninitialized data that contributes to<br> the program’s memory image. By definition, the system<br> initializes the data with zeros when the program begins to<br> run. This section is of type SHT_NOBITS. The attribute<br> types are SHF_ALLOC and SHF_WRITE.</blockquote><blockquote><strong>.data</strong> This section holds initialized data that contribute to the<br> program’s memory image. This section is of type<br> SHT_PROGBITS. The attribute types are SHF_ALLOC and<br> SHF_WRITE.</blockquote><blockquote><strong>.rodata</strong> This section holds read-only data that typically<br> contributes to a nonwritable segment in the process image.<br> This section is of type SHT_PROGBITS. The attribute used<br> is SHF_ALLOC.</blockquote><blockquote><strong>.text</strong> This section holds the “text”, or executable instructions,<br> of a program. This section is of type SHT_PROGBITS. The<br> attributes used are SHF_ALLOC and SHF_EXECINSTR.</blockquote><p>Let’s view some of the sections, before doing this, recompile program (with source symbols) as</p><pre>gcc -m32 -g hello.c -o hello</pre><p>Let’s look at assembly code</p><pre>objdump  -S hello</pre><p>Looking at .text section</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*UdGYu9JZF0FLr4XalK_jHw.png" /></figure><p>It can be seen that it begins at 0x1070</p><p>Add function is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*bvLKLEuVS3wdXheydWSdfQ.png" /></figure><p>main function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*QigXLmMZ9XUgKcqP4GsBbg.png" /></figure><p>.rodata section which contains string, “hello world”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*ZOa5Bm6awuUcA-FZ_MGRpA.png" /><figcaption>run objdump -s hello for this</figcaption></figure><p>At this point, we have some idea which section does what and how are they mapped into process image.</p><h3>Writing your own DIY boot loader</h3><p>Here it begins, actual kernel writing stuff. We will start by writing a bootloader in order to understand how kernel gets bootstrapped.</p><p>A bootloader is software which needs to perform following functions:</p><ol><li>Create runtime environment for the kernel.</li><li>Load the kernel into memory.</li><li>Transfer program control flow to kernel.</li></ol><p>Before we start with bootloaders, let’s understand <a href="https://wiki.osdev.org/Boot_Sequence">boot process</a> first.</p><p><a href="https://manybutfinite.com/post/how-computers-boot-up/">Boot process</a> consists of following steps:</p><ul><li>Press the power button on the compute (don’t say).</li><li>Motherboard initializes firmware (chipset and whatnot) and get the CPU running.</li><li>In a multi-processor system one CPU is dynamically chosen to be the bootstrap processor (BSP) that runs all of the BIOS and kernel initialization code. The remaining processors, called application processors (AP) at this point, remain halted until later on when they are explicitly activated by the kernel.</li><li>In this primitive power up state the processor is in real mode with memory paging disabled (all hail 8086!).</li><li>Most registers in the CPU have well-defined values after power up, EIP holds 0xFFFFFFF0 -&gt; reset vector.</li><li>The motherboard ensures that the instruction at the reset vector is a <em>jump</em> to the memory location mapped to the BIOS entry point.</li><li>The CPU then starts executing BIOS code, which initializes some of the hardware in the machine.</li><li>Afterwards the BIOS kicks off the Power-on Self Test (POST) which tests various components in the computer.</li><li>The POST involves a mixture of testing and initialization, including sorting out all the resources — interrupts, memory ranges, I/O ports — for PCI devices.</li><li>After the POST the BIOS wants to boot up an operating system, which must be found somewhere: hard drives, CD-ROM drives, floppy disks, etc.</li><li>The BIOS now reads the first 512-byte sector (sector zero) of the disk image if it contains magic number (0x55AA). This is called the Master Boot Record.</li><li>BIOS loads the contents of the MBR into memory location 0x7c00 and jumps to that location to start executing whatever code is in the MBR.</li></ul><p>So, in order to write our bootloader, we need to add our code at 0x7c00 and magic number at 510 and 511 byte offset (last two bytes).</p><p>Let’s create bootloader.asm</p><pre>BITS 16<br>ORG 0x7c00<br><br>MOV AL, 65<br>MOV AH, 0x0E ;Tell BIOS that we need to print one charater on screen.<br>MOV BH, 0x00 ;Page no.<br>MOV BL, 0x07 ;Text attribute 0x07 is lightgrey font on black background<br>INT 0x10<br>JMP $<br><br>TIMES 510 - ($ - $$) db 0<br>DW 0xAA55 ; Boot Signiture</pre><p>Its relatively simple code, first section is about bits, we are going to start with 16 bit program for sake of simplicity. Important line in this code is ORG 0x7c00. This means our code should start at 0x7c00. This is required as BIOS will handover control to us at this address.</p><pre>MOV AL, 65<br>MOV AH, 0x0E ;Tell BIOS that we need to print one charater on screen.<br>MOV BH, 0x00 ;Page no.<br>MOV BL, 0x07 ;Text attribute 0x07 is lightgrey font on black background<br>INT 0x10</pre><p>First four lines is done for preparation of interrupt<a href="https://en.wikipedia.org/wiki/INT_10H"> 0x10</a> . This interuppt provides access to video(display) services.</p><p>AH=0Eh means we want to set output as Teletype output, because we want to write a character to the screen. Character needs to be set at AL, which is 65 aka ‘A’, BH = Page Number, BL = <a href="https://en.wikipedia.org/wiki/BIOS_Color_Attributes">Color</a>. Page number is used for double buffering. if you want to write lot of content, you can write stuffs on different page. It won’t show in screen but you can then call interrupt to quickly show different page.</p><pre>JMP $<br>TIMES 510 - ($ - $$) db 0<br>DW 0xAA55 ; Boot Signiture</pre><p>$ in <a href="https://www.nasm.us/doc/nasmdoc3.html#section-3.5">NASM</a> points to current address, so <em>JMP $</em> creates an infinite loop.</p><p>The TIMES prefix causes the instruction to be assembled multiple times. Eg. <em>TIMES 64 db 0</em> will define 64 bytes with value 0. $$ defines beginning of session. So, ($ — $$) can tell how far you are into the section you are by using.</p><p>At current position, we have already used some bytes (equal to $ — $$, from starting to now), we need to fill rest of the bytes, upto 510 with zeroes. This is done by <em>TIMES 510 — ($ — $$) db 0.</em></p><p>Last two bytes are magic number, which defines that current sector is boot-able.</p><p>Compile and run by</p><pre>nasm -f bin bootloader.asm -o bootloader<br>qemu-system-i386 bootloader</pre><p>By default it assumes we are booting from hard disk, since our code is at right place, it prints ‘A’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*jBV8VkYZphucX37UayJOGg.png" /><figcaption>A small step</figcaption></figure><p>hexdump of bootloader looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*8gJw7UxeXNpcLBwB0FYgew.png" /></figure><p>You can notice that magic bytes before last are 55 and AA. Size of this file should be precisely 512 bytes.</p><p>Now, instead of running it as raw binary, let’s add it our bootloader to a disk image. Reason why we want to be doing this is that we want to load our kernel executable from this bootloader, and for that we need some storage space where we can add bootloader in first sector (first 512 bytes), followed by our kernel.</p><pre>dd if=bootloader of=disk.img bs=512 count=1 conv=notrunc # save to disk image<br>qemu-system-i386 -machine q35 -fda disk.img # run qemu again</pre><p>It would read our disk as floppy disk and print ‘A’ again</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*ohQSTOdyEXRkk1F69IFRmw.png" /></figure><p>Now, lets create another code, think of it as our kernel code. Idea is to bootloader should, well..boot and then call kernel code.</p><p>Create another bootloader.asm.</p><pre>BITS 16<br>ORG 0x7c00<br>mov ax, 0x50 ; Set up the data segment (es) to 0x5000<br>mov es, ax<br>xor bx, bx<br>mov al, 2 ; read 2 sector<br>mov ch, 0 ; track 0<br>mov cl, 2 ; sector to read (The second sector)<br>mov dh, 0 ; head number<br>mov dl, 0 ; drive number<br>mov ah, 0x02 ; read sectors from disk<br>int 0x13 ; call the BIOS routine<br>jmp 0x50:0x0 ; jump and execute the sector!<br>TIMES 510 - ($ - $$) db 0<br>DW 0xAA55 ; Boot Signiture</pre><p>Above got is similar to bootloader that we wrote before. <a href="https://en.wikipedia.org/wiki/INT_13H">int 0x13</a> is just a gravy. It provides sector-based hard disk and floppy disk read and write services using <a href="https://en.wikipedia.org/wiki/Cylinder-head-sector">cylinder-head-sector</a> (CHS) addressing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*wHsU7cyHviZxwyadWi3Y2A.png" /></figure><p>Data will be stored in ES:BX, which is data buffer.</p><pre>mov ax, 0x50 ; Set up the data segment (es) to 0x5000<br>mov es, ax<br>xor bx, bx</pre><p>Above lines simply set es as 0x50 and bx as 0x0, so data which is read (this contains our instructions) will be stored at 0x50:0 or 0x500. This is why we make jump to 0x500 and effectively handing over execution to our new code.</p><p>Let’s write another program which our bootloader can call, this will be our kernel. kernel.asm</p><pre>MOV AL, 66<br>MOV AH, 0x0E ;Tell BIOS that we need to print one charater on screen.<br>MOV BH, 0x00 ;Page no.<br>MOV BL, 0x07 ;Text attribute 0x07 is lightgrey font on black background<br>INT 0x10<br>JMP $</pre><p>Let’s compile both</p><pre>nasm -f bin bootloader.asm -o bootloader<br>nasm -f bin kernel.asm -o kernel</pre><p>Hex dump of kernel looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*EP1T5fpyMBYVEgq_IO3wCA.png" /></figure><p>Let’s copy both to the disk image. First sector will contain bootloader (MBR) and second sector will contain kernel.</p><pre>dd if=bootloader of=disk.img bs=512 count=1 conv=notrunc # first sector<br>dd if=kernel of=disk.img bs=512 count=1 seek=1 # second sector</pre><p>Let’s look at final disk image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*Xa0dJcH8wpyAueyvRnRtzA.png" /></figure><p>Notice kernel hex (b0 42 b4 0e b7 00 b3 07 cd 10 eb fe) at the end of disk.img, which verifies that we have kernel in sector two.</p><p>If you run it now, you will get character B, which is emitted from kernel code, not character A as earlier.</p><pre>qemu-system-i386 -machine q35 -fda disk.img # run qemu again</pre><p>Now, that we know little bit about boot loaders, it is time to roll out somewhat <em>real kernel, </em>which can do things other than printing A or B. Before we start, it is very much apparent how complicated it is to bootstrap and here we did it only for simple storage like floppy, trying same for other storage like Hard disk will take its own effort, something which is not motive of this article. Take away point from this section to get an idea how bootstrapping is done and how we get trampolined into our kernel code.</p><h3>Bootstrapping your DIY kernel</h3><p>Real kernel code contains combination of high level code in C and low level architecture specific code in assembly. This section is focused on building more realistic kernel in C, with some section of assembly code (based on NASM Syntax) and linker script (to ensure proper layout in memory). For bootloading, we will be using grub2.</p><p>As we have already seen, C code can not run without proper runtime (recall _start in dissembled C code). We need to implement our own version of crt0 before we can run our kernel code in c.</p><p>Recap, what crt0 does is:</p><ol><li><strong><em>Initializes everything in your program that needs it</em></strong></li><li>Set up space for the stack and grab a chunk of memory.</li><li>Initializes .bss section</li><li>calls main function</li></ol><p>In order to setup these things, we will need linker scripts.</p><p>Let’s start by creating simple kernel code again.</p><p>loader.asm</p><pre>bits 32<br><br>MAGIC_NUMBER equ 0x1BADB002<br>ALIGN_MODULES equ 0x00000001<br><br>; calculate the checksum (all options + checksum should equal 0)<br>CHECKSUM equ -(MAGIC_NUMBER + ALIGN_MODULES)<br>section .multiboot               ;according to multiboot spec<br>        dd MAGIC_NUMBER           ;set magic number for<br>                                 ;bootloader<br>        dd ALIGN_MODULES         ;set flags<br>        dd CHECKSUM  ;set checksum<br><br>section .text<br>global start<br>extern main                      ;defined in the C file<br><br>start:<br>        cli                      ;block interrupts<br>        mov esp, stack_space     ;set stack pointer<br>        mov ebp, stack_space     ;set stack pointer<br>        push ebx<br>        call main<br>        hlt                      ;halt the CPU<br><br>section .bss<br>resb 8192                        ;8KB for stack<br>stack_space:</pre><p>link.ld</p><pre>OUTPUT_FORMAT(elf32-i386)<br>ENTRY(start)<br>SECTIONS<br> {<br>   . = 1M;<br>   .text ALIGN(4K):<br>   {<br>       *(.multiboot)<br>       *(.text)<br>   }<br>   .data : { *(.data) }<br>   .bss  : { *(.bss)  }<br> }</pre><p>kernel.c</p><pre><br>int main()<br>{<br>    return 0;<br>}</pre><p>grub.cfg</p><pre>set timeout=1<br><br>menuentry &quot;DIY Kernel&quot; {<br>        multiboot /boot/kernel.elf<br>}</pre><p>Makefile</p><pre>CC = gcc<br>CFLAGS = -m32 -nostdlib -nostdinc -fno-builtin -fno-stack-protector \<br>-nostartfiles -nodefaultlibs -Wall -Wextra -Werror -Wno-error=main -ggdb -c<br>LDFLAGS = -T link.ld -melf_i386<br>AS = nasm<br>ASFLAGS = -f elf<br>OBJS = kernel.o loader.o<br>all: kernel iso<br><br>kernel: $(OBJS)<br> ld $(LDFLAGS) $(OBJS) -o kernel.elf<br><br>iso: kernel<br> mkdir -p iso<br> mkdir -p iso/boot<br> mkdir -p iso/boot/grub<br> cp kernel.elf iso/boot/kernel.elf<br> cp grub.cfg iso/boot/grub/grub.cfg<br> grub-mkrescue -o os.iso iso/<br><br>run: iso<br> qemu-system-i386 -boot d -cdrom os.iso -m 512 <br><br>%.o: %.c<br> $(CC) $(CFLAGS) $&lt; -o $@<br><br>%.o: %.asm<br> $(AS) $(ASFLAGS) $&lt; -o $@<br><br>clean:<br> rm -rf $(OBJS)<br> rm -rf os.iso<br> rm -rf kernel.elf</pre><p>To make life easy, .gdbinit</p><pre>define hook-stop<br> # Translate the segment:offset into a physical address<br> printf &quot;[%4x:%4x] &quot;, $cs, $eip<br> x/i $cs*16+$eip<br>end<br>layout asm<br>layout reg<br>set architecture i8086<br>target remote localhost:1234<br><br>set history save on<br>set history size 1000</pre><p>Run whole thing by</p><pre>make run</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*aKbPdGNZr6CobdNzMv-BvQ.png" /><figcaption>Nothing</figcaption></figure><p>To actually see what is happening, run</p><pre>make debug</pre><p>In new tab (on current working directory), run</p><pre>gdb kernel.elf</pre><p>In gdb, type<em> b main </em>and<em> press c. </em>It should break/stop at your main function in C code. If it does, congratulation, you have booted your first realistic kernel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M3Cbq1snATPHPEU3MU5ZBw.png" /><figcaption>Pretty neat!</figcaption></figure><p>Now, let’s go into each files one by one.</p><p>Note: Code can be found at <a href="https://github.com/itsankitkp/kernel_learn/tree/main/ch2">https://github.com/itsankitkp/kernel_learn/tree/main/ch2</a></p><p>loader.asm</p><pre>bits 32<br></pre><p>First line defines that our code is 32 bit code.</p><p>Let’s read lines from OS image specific as <a href="https://www.gnu.org/software/grub/manual/multiboot/html_node/OS-image-format.html#OS-image-format">required</a> by grub (which we want to use)</p><blockquote>An OS image must contain an additional header called <em>Multiboot header</em>, besides the headers of the format used by the OS image. The Multiboot header must be contained completely within the first 8192 bytes of the OS image, and must be longword (32-bit) aligned.</blockquote><p>Also, layout of multiboot header should look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*zVxbZp7MxWTVQWYzIBdqfw.png" /></figure><p>So, in order for multiboot to work, we should have <em>Multiboot header, </em>with atleast 3 fields viz magic, flags and checksum. This section must be contained completely within the first 8192 bytes of the OS image, and must be longword (32-bit) aligned.</p><p>More on magic fields <a href="https://www.gnu.org/software/grub/manual/multiboot/html_node/Header-magic-fields.html">here</a>.</p><p>Phew!, now how it is put to practice. Look at code rest of the code in loader.asm again</p><pre>MAGIC_NUMBER equ 0x1BADB002<br>ALIGN_MODULES equ 0x00000001<br><br>; calculate the checksum (all options + checksum should equal 0)<br>CHECKSUM equ -(MAGIC_NUMBER + ALIGN_MODULES)<br>section .multiboot               ;according to multiboot spec<br>        dd MAGIC_NUMBER           ;set magic number for<br>                                 ;bootloader<br>        dd ALIGN_MODULES         ;set flags<br>        dd CHECKSUM  ;set checksum</pre><p>A section called multiboot is defined and inside it, we have defined 3 double word (DWORD). Why double word you ask?</p><p>Refer NASM <a href="https://nasm.us/doc/nasmdoc3.html">docs</a> for variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*ub78lSP1VfaafThwVVBiRw.png" /></figure><p>Byte is, well a byte (8 bits), word is 16 bits, dword is 32 bits. As multiboot specs need all these three variables in 32 bits, we ought to use dword.</p><pre>section .text<br>global start<br>extern main                      ;defined in the C file<br><br>start:<br>        cli                      ;block interrupts<br>        mov esp, stack_space     ;set stack pointer<br>        mov ebp, stack_space     ;set stack pointer<br>        push ebx<br>        call main<br>        hlt                      ;halt the CPU<br></pre><p>Above code contains .text section, which contains our code. As mentioned earlier, we can not call c code directly in bare metal without setting up runtime environment. This code does that by setting stack pointer (ESP), EBP points to stack segment, think of it as local stack in current frame (here it means stack which will be used locally by main function).</p><p>Once all these are done, we can call main function (which is external function as far as this code is concerned and needs to be resolved during relocation).</p><p>A <em>stack_space</em> , which is stack size, is defined as 8kB below .bss section. Resb is used to define uninitialized storage space in bytes.</p><blockquote>RESB, RESW, RESD, RESQ, REST, RESO, RESY and RESZ are designed to be used in the BSS section of a module: they declare <em>uninitialized</em> storage space. Each takes a single operand, which is the number of bytes, words, doublewords or whatever to reserve.</blockquote><pre>section .bss<br>resb 8192                        ;8KB for stack<br>stack_space:</pre><p>You can check value of stack_space by:</p><pre>readelf -s kernel.elf | grep stack_space</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*7ZQlXTguiHQUyibUFApkUA.png" /></figure><p>This is properly set can be verified by adding breakpoint at main (run <em>make debug</em> and open <em>gdb kernel.elf</em>, type <em>b main)</em></p><p>and running:</p><pre>info registers ebp</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*PTzDWOJqBdtJVTElII3dGg.png" /></figure><pre>info registers esp</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*srgz5kylhRuRMpquW5YiTA.png" /></figure><p>Notice how esp is lower than ebp, this is because stack grows downwards and some things are pushed into stack.</p><p>This is all for loader.asm</p><p>Let’s move to next file link.ld. This is used by linker to, quoting man page</p><blockquote><strong>ld</strong> combines a number of object and archive files, relocates their data and ties up symbol references.</blockquote><p>This is pretty straightforward.</p><pre>OUTPUT_FORMAT(elf32-i386)<br>ENTRY(start)<br>SECTIONS<br> {<br>   . = 1M;<br>   .text ALIGN(4K):<br>   {<br>       *(.multiboot)<br>       *(.text)<br>   }<br>   .data : { *(.data) }<br>   .bss  : { *(.bss)  }<br> }</pre><p>OUTPUT_FORMAT defines type of binary. ENTRY point specifies that if we run this code, from where should be start executing.</p><p>If you see entry point address in ELF header on kernel.elf</p><pre>readelf -h kernel.elf</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*ZofTFBN89MKEvCJtek46vQ.png" /></figure><p>and checking corresponding address in symbol table</p><pre>readelf -s kernel.elf | grep 100010</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*QIpb2aEMlSXj18dOKRjbvw.png" /></figure><p>It will be seen that it is pointing to start function. This all happened because of <em>ENTRY(start).</em></p><pre>SECTIONS<br> {<br>   . = 1M;<br>   .text ALIGN(4K):<br>   {<br>       *(.multiboot)<br>       *(.text)<br>   }<br>   .data : { *(.data) }<br>   .bss  : { *(.bss)  }<br> }</pre><p>Sections defines output section of executable. <strong><em>. = 1M</em> </strong>sets entry point to .text/kernel code at address 1 MB (0x100000, 5 zeroes after 1) . This is purely a convention on bootloader side (they don’t really know where our code is, same reason why we have a reserved address of <em>0x7C00</em> used by cpu to load first instruction after reset/boot).</p><p>ALIGN means</p><blockquote>Return the location counter (.) or arbitrary expression aligned to the next align boundary.</blockquote><p>It ensures that address of our text segment is in multiple of 4K.</p><p>Text segment begins with multiboot header (as required by multiboot specification) followed by .text segment of loader, which contains code.</p><p>.data and .bss segment is defined as it is. These sections can be viewed by</p><pre>objdump -hw kernel.elf</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*639uB1dsb7kM56l8hIXbnw.png" /></figure><p>Notice there is no .data section, as we have no data (read global variables) yet.</p><pre>objdump -s -j .data kernel.elf </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*-3zHgYz0QSdzvzBgpy4KMg.png" /></figure><p>If you add any global variable to main, say a like this</p><pre><br>static int a=10;<br>int main()<br>{<br>    return a;<br>}</pre><p>Run <em>make</em> and check <em>objdump</em> again</p><p>We would see .data section created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AGueFw5T-dJ-iUcJN2I6iA.png" /></figure><p>Notice that it is before .bss section, as per as linker script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*o99OB8QKCB10OM2jVqwz2g.png" /></figure><p>Next file is kernel.c</p><pre>int main()<br>{<br>    return 0;<br>}</pre><p>There is not much to see here, we don’t have standard library available for our bare bone system and thus we have to write all basic functions like printf etc. from scratch. But iy is not required now, at the moment we need to ensure that we reach main function, rest of the functions can be build over this.</p><p>Next is makefile, although we could have lived without creating a makefile now, writing it makes our life extremely convenient.</p><p>Makefile</p><pre>CC = gcc<br>CFLAGS = -m32 -nostdlib -nostdinc -fno-builtin -fno-stack-protector \<br>-nostartfiles -nodefaultlibs -Wall -Wextra -Werror -Wno-error=main -ggdb -c<br>LDFLAGS = -T link.ld -melf_i386<br>AS = nasm<br>ASFLAGS = -f elf<br>OBJS = kernel.o loader.o<br>all: kernel iso<br><br>kernel: $(OBJS)<br> ld $(LDFLAGS) $(OBJS) -o kernel.elf<br><br>iso: kernel<br> mkdir -p iso<br> mkdir -p iso/boot<br> mkdir -p iso/boot/grub<br> cp kernel.elf iso/boot/kernel.elf<br> cp grub.cfg iso/boot/grub/grub.cfg<br> grub-mkrescue -o os.iso iso/<br><br>run: iso<br> qemu-system-i386 -boot d -cdrom os.iso -m 512 <br><br>%.o: %.c<br> $(CC) $(CFLAGS) $&lt; -o $@<br><br>%.o: %.asm<br> $(AS) $(ASFLAGS) $&lt; -o $@<br><br>clean:<br> rm -rf $(OBJS)<br> rm -rf os.iso<br> rm -rf kernel.elf</pre><p>Makefiles are not my specialty so I will leave out fine details (plenty of docs available on the internet for this). Its basic structure can be explained like this:</p><p>Say we want to do write make file for tea</p><p><em>make tea</em></p><p>Its recipe will look like this</p><pre>comman_to_boil = add<br>ingredients = tea milk sugar<br><br>tea: boil # how to boil is defined elsewhere<br><br>boil: <br>    $(command_to_boil) $(ingredients)  # variables and commands<br></pre><p>So, if you call <em>make tea</em>, it will see if it can be fulfilled i.r. if <em>boil</em> is available, if not then it will run boil section and so on. At bottom of stack, we will have actual implementation for each steps.</p><p>Now let’s go over the makefile.</p><pre>CC = gcc<br>CFLAGS = -m32 -nostdlib -nostdinc -fno-builtin -fno-stack-protector \<br>-nostartfiles -nodefaultlibs -Wall -Wextra -Werror -Wno-error=main -ggdb -c<br>LDFLAGS = -T link.ld -melf_i386<br>AS = nasm<br>ASFLAGS = -f elf<br>OBJS = kernel.o loader.o</pre><p>These are variables defined in this file. It can be accessed by calling $(var_name). CC is for gcc which compiles our C code, CFLAGS are flag given to gcc. -m32 again specifies that it is 32 bit code, rest of flags are given below:</p><blockquote>-nostdlibDo not use the standard system startup files or libraries when linking. No startup files and only the libraries you specify will be passed to the linker. The compiler may generate calls to memcmp, memset, memcpy and memmove. These entries are usually resolved by entries in libc. These entry points should be supplied through some other mechanism when this option is specified.</blockquote><blockquote>-nostdinc Do not search the standard system directories for header files.</blockquote><blockquote>-fno-builtin Don’t recognize built-in functions that do not begin with ‘__builtin_’ as prefix.</blockquote><p>For -fno-stack-protector, we can see stack protector flag is used to add stacking protection logic, which we are explictly saying that we dont want.</p><blockquote>-fstack-protector Emit extra code to check for buffer overflows, such as stack smashing attacks.</blockquote><blockquote>-nostartfiles Do not use the standard system startup files when linking</blockquote><blockquote>-nodefaultlibs Do not use the standard system libraries when linking. Only the libraries you specify are passed to the linker, and options specifying linkage of the system libraries, such as -static-libgcc or -shared-libgcc, are ignored.</blockquote><p>-Wall basically enables all warnings</p><blockquote>-Wall This enables all the warnings about constructions that some users consider questionable, and that are easy to avoid (or modify to prevent the warning), even in conjunction with macros.</blockquote><blockquote>-Wextra This enables some extra warning flags that are not enabled by -Wall.</blockquote><p>-Werror makes all warning as error. This is needed because kernel code is very delicate and no warning should be ignored.</p><blockquote>-Werror Make all warnings into errors.</blockquote><p>-Wno-error=main is added to ignore error about main function (as it doesn’t have standard syntax), which we can ignore for now.</p><blockquote>-ggdb Produce debugging information for use by GDB. This means to use the most expressive format available (DWARF, stabs, or the native format if neither of those are supported), including GDB extensions if at all possible.</blockquote><p>More information is available at gcc <a href="https://gcc.gnu.org/onlinedocs/gcc.pdf">docs</a>.</p><p>LD flags are used by ld command.</p><p>LDFLAGS = -T link.ld -melf_i386</p><p>where -T specifies linker script and -m specifies elf format, which is i386 (32 bits).</p><p>NASM is used as assembler (as specified in ASM), again ASFLAGS</p><p>specifies format -f as elf.</p><p>Further in makefile</p><pre>all: kernel iso<br><br>kernel: $(OBJS)<br> ld $(LDFLAGS) $(OBJS) -o kernel.elf<br><br>iso: kernel<br> mkdir -p iso<br> mkdir -p iso/boot<br> mkdir -p iso/boot/grub<br> cp kernel.elf iso/boot/kernel.elf<br> cp grub.cfg iso/boot/grub/grub.cfg<br> grub-mkrescue -o os.iso iso/<br><br>run: iso<br> qemu-system-i386 -boot d -cdrom os.iso -m 512<br><br>debug: iso<br> qemu-system-i386 -boot d -cdrom os.iso -m 512 -s -S<br><br>%.o: %.c<br> $(CC) $(CFLAGS) $&lt; -o $@<br><br>%.o: %.asm<br> $(AS) $(ASFLAGS) $&lt; -o $@</pre><p><em>all</em> provides recipe for <em>make all, </em>similarly <em>make kernel</em>, <em>make iso</em>, <em>make run</em> and <em>make debug</em> can be used.</p><p>Let’s consider case of <em>make all</em>, if make all is called, it needs kernel and iso to be done, therefore kernel is build first and then iso.</p><p>Again, kernel requires OBJS files to exist, which is taken care by</p><pre>%.o: %.c<br> $(CC) $(CFLAGS) $&lt; -o $@<br><br>%.o: %.asm<br> $(AS) $(ASFLAGS) $&lt; -o $@</pre><p>‘%.c’ as a pattern matches any file name that ends in ‘.c’. Same is for %.asm as well (which matches assembly files).</p><p>%&lt; and %@ are <a href="https://www.gnu.org/software/make/manual/html_node/Automatic-Variables.html#Automatic-Variables">automatic</a> variables</p><blockquote>$&lt; The name of the first prerequisite.</blockquote><blockquote>$@The file name of the target of the rule.</blockquote><p>In above code, first prerequisite is .o (which is our c/asm files), and target is object files (*.o).</p><p>After running make file, you must have seen output like this (assuming there is no object files, run make clean to clean those up, remember makefiles starts from pending steps, if object files are already there, it won’t run it again),</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uYh8X56OQX0yzXQEAvfY-w.png" /></figure><p>As you can see, first two line generates object files (from assembly and from C), followed by linking it into elf executable.</p><pre>nasm -f elf loader.asm -o loader.o<br>gcc -m32 -nostdlib -nostdinc -fno-builtin -fno-stack-protector -nostartfiles -nodefaultlibs -Wall -Wextra -Werror -Wno-error=main -ggdb -c kernel.c -o kernel.o<br>ld -T link.ld -melf_i386 loader.o kernel.o -o kernel.elf</pre><p>We finally got our kernel executable as kernel.elf. Now, we need to tell grub this is our executable file. This is done in grub.cfg</p><pre>set timeout=1<br><br>menuentry &quot;DIY Kernel&quot; {<br>        multiboot /boot/kernel.elf<br>}<br></pre><blockquote>menuentry: This defines a GRUB menu entry named title. When this entry is selected from the menu, GRUB will set the chosen environment variable to value of — id if — id is given, execute the list of commands given within braces, and if the last command in the list returned successfully and a kernel was loaded it will execute the boot command.</blockquote><blockquote>multiboot: Load a multiboot kernel image from file. The rest of the line is passed verbatim as the <em>kernel command-line</em>. Any module must be reloaded after using this command</blockquote><p>So, whenever user selects <a href="https://www.gnu.org/software/grub/manual/grub/grub.html#index-menuentry">menuentry</a> (named as “DIY Kernel”), it runs sections under the braces, which calls multiboot to load kernel image, which is our elf file. Notice location as /boot/kernel.elf. This is directory layout of iso image which we create, as given in Makefile. And copy grub.cfg and kernel code.</p><pre> mkdir -p iso<br> mkdir -p iso/boot<br> mkdir -p iso/boot/grub<br> cp kernel.elf iso/boot/kernel.elf<br> cp grub.cfg iso/boot/grub/grub.cfg</pre><p>Why do we store grub config at /boot/grub/grub.cfg?</p><p>Referring docs again:</p><blockquote>GRUB’s normal start-up procedure involves setting the ‘prefix’ environment variable to a value set in the core image by grub-install, setting the ‘root’ variable to match, loading the ‘normal’ module from the prefix, and running the ‘normal’ command (see <a href="https://www.gnu.org/software/grub/manual/grub/grub.html#normal">normal</a>). This command is responsible for reading <strong>/boot/grub/grub.cfg</strong>, running the menu, and doing all the useful things GRUB is supposed to do.</blockquote><p>Once grub.cfg and kernel image is put at correct location in iso directory, we invoke <a href="https://www.gnu.org/software/grub/manual/grub/grub.html#Making-a-GRUB-bootable-CD_002dROM">grub-mkrescue</a>.</p><blockquote>GRUB supports the <em>no emulation mode</em> in the El Torito specification. This means that you can use the whole CD-ROM from GRUB and you don’t have to make a floppy or hard disk image file, which can cause compatibility problems.</blockquote><blockquote>If desired, make the config file grub.cfg under iso/boot/grub (see <a href="https://www.gnu.org/software/grub/manual/grub/grub.html#Configuration">Configuration</a>), and copy any files and directories for the disc to the directory iso/.</blockquote><blockquote>The root device will be set up appropriately on entering your grub.cfg configuration file, so you can refer to file names on the CD without needing to use an explicit device name. This makes it easier to produce rescue images that will work on both optical drives and USB mass storage devices.</blockquote><p>Sweet! We make rescue disk by running</p><pre>grub-mkrescue -o os.iso iso</pre><p><em>iso</em> is folder containing our kernel and grub config.</p><p>Rescue disk can be run by (this is same as <em>make run</em>)</p><pre>qemu-system-i386 -boot d -cdrom os.iso -m 512</pre><p>-m specifies RAM size, boot is from cdrom where os is defined (which is os.iso, subtle).</p><p>If you want to enable <a href="https://www.qemu.org/docs/master/system/gdb.html">gdb</a> debugger, simply pass -S -s</p><blockquote>The -s option will make QEMU listen for an incoming connection from gdb on TCP port 1234, and -S will make QEMU not start the guest until you tell it to from gdb.</blockquote><p>This is same as make debug.</p><pre>qemu-system-i386 -boot d -cdrom os.iso -m 512 -s -S</pre><p>To attach debugger, run</p><pre>gdb kernel.elf</pre><p>In gdb, run</p><pre> target remote localhost:1234<br></pre><p>Now, you can add breakpoints (say at main or at start) and whatnot! To make life easier (typing target remote.. becomes annyoing very quickly), lets add .gdbinit file as well.</p><p>.gdbinit</p><pre>define hook-stop<br> # Translate the segment:offset into a physical address<br> printf &quot;[%4x:%4x] &quot;, $cs, $eip<br> x/i $cs*16+$eip<br>end<br>layout asm<br>layout reg<br>set architecture i8086<br>target remote localhost:1234<br><br>set history save on<br>set history size 1000</pre><p>That’s it! You have successfully booted into you kernel. Take some time and cherish your accomplishment.</p><h3>Moving on</h3><p>Next steps will be setting up GDT, Interrupt handlers and paging, followed by handing heap, and loading other programs/multitasking. I won’t say we can call it a day until we can run some hello world program in our kernel. It is long road which will need lots of dedication and work, but end result will worth it. More articles will follow up, meanwhile I am mentioning immensely useful references with TON of information.</p><h3>References</h3><p><a href="https://users.informatik.haw-hamburg.de/~krabat/FH-Labor/gnupro/7_GNUPro_Embedded_Development/embcrt0_the_main_startup_file.html">crt0, the main startup file</a></p><p><a href="https://raw.githubusercontent.com/tuhdo/os01/master/Operating_Systems_From_0_to_1.pdf">https://raw.githubusercontent.com/tuhdo/os01/master/Operating_Systems_From_0_to_1.pdf</a></p><p>This is bible of OS development, unfortunately it is not finished yet. This article is quick summary of nothing but this book.</p><p><a href="https://wiki.osdev.org/Expanded_Main_Page">Expanded Main Page</a></p><p>OSDev, if you can’t find OS related resources here, you will not find it anywhere ;)</p><p><a href="http://www.jamesmolloy.co.uk/tutorial_html/">JamesM&#39;s kernel development tutorials</a></p><p>Bit dated but it has lots of theory</p><p><a href="http://littleosbook.github.io/">The little book about OS development</a></p><p>Very good book about OS development, this is where I started by journey of learning OS.</p><p><a href="https://samypesse.gitbook.io/how-to-create-an-operating-system">Introduction</a></p><p>Excellent book, with actual code by someone who created kernel in high school project (I could barely do algebra then). Only issue is that the code is in French and C++ :)</p><p><a href="https://cdrdv2.intel.com/v1/dl/getContent/671200"><strong><em>Intel Manuals</em></strong></a></p><p>Ofcourse.</p><p><em>Feel free to add feedback and suggestions in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cabad8dc448" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the fundamentals of Asynchronous Programming with Prototype Code]]></title>
            <link>https://tech.mammoth.io/understanding-the-fundamentals-of-asynchronous-programming-with-prototype-code-f253ab1062a6?source=rss-285c7ae18b08------2</link>
            <guid isPermaLink="false">https://medium.com/p/f253ab1062a6</guid>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Ankit K Pandey]]></dc:creator>
            <pubDate>Fri, 02 Jun 2023 19:19:44 GMT</pubDate>
            <atom:updated>2023-06-25T11:00:04.329Z</atom:updated>
            <content:encoded><![CDATA[<p>Asynchronous I/O (Async I/O) is pervasive, utilized in various contexts such as frontend development with future/promises, backend systems handling APIs and distributed task processing. Its efficiency and popularity, particularly in web applications, is unmatched. My personal exploration into this realm began when I encountered an uncommon network error, prompting me to look deeper into gevent. This concurrency library was employed extensively throughout the backend stack, with gunicorn and Celery utilizing gevent workers. Understanding gevent was a crucial initial step on this journey, which eventually led me to discover libuv — one of an event loop which powers gevent.</p><p>However, the most effective way to learn any concept is to attempt building it oneself. This realization inspired me to construct Async I/O at its core, employing system calls and simple C programming. As I started the writing the code, the true essence of Async I/O became much clearer, and through this article, my aim to share the knowledge that I have gained from this exploration.</p><p>This article is divided into three major sections:</p><ol><li>Introduction</li></ol><p>Provides some history and sets up context for this article.</p><p>2. Writing synchronous client-server application</p><p>This would make us acquainted with core APIs used in socket IO. Socket IO is chosen because this is easiest and most common IO operation that we would encounter in web application. Beside this, other IOs like async disk IO is bit involved. Read <a href="https://blog.libtorrent.org/2012/10/asynchronous-disk-io/">this </a>article for some interesting information.</p><p>3. Writing asynchronous client-server application</p><p>This will expose use to O_NONBLOCK flag and fcnt syscall (which is really intriguing). Additionally, we will explore the unique nature of handling async functions, as they differ from the typical program control flow with synchronous functions.</p><p>4. Using epoll to improve efficiency of Async IO</p><p>This section will bring us closer to event driven programming that we have known and love. This section will set stage where event loops (like libuv), will start making sense.</p><h3>History</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/0*6iIo8NVYaaLaHu2h" /><figcaption>C10k problem</figcaption></figure><p>During dot com bloom, <a href="https://en.wikipedia.org/wiki/C10k_problem">C10k </a>problem was plaguing web developers. It was problem of handling tens of thousand of concurrent web connections. Existing methods of using threads or process for handling each connection were not scalable enough for such problem because:</p><ol><li>Each connection is short lived. Even now, API connection lasting for more than few ms is frowned upon (unless in very specific cases). Threads creation (and cleanup) couldn’t match such high churn.</li><li>High context switches.</li></ol><p>Process based parallelism was out of question (being more heavy than thread) and there was need of highly scalable architecture to handle this new kind of challenge.</p><p>At that time (around 2004) while existing web server (Apache) was struggling to meet such high demand, new server NGINX came into the market with some interesting architecture and it scaled very well. More on this in this <a href="https://www.nginx.com/blog/inside-nginx-how-we-designed-for-performance-scale">article </a>by nginx .</p><p>On the similar line, there was some guy Ryan Dahl, who was frustrated by slow performance of servers and developed nodejs based on Async IO. To quote:</p><blockquote>“Dahl criticized the limited possibilities of the most popular web server in 2009, Apache HTTP Server, to handle a lot of concurrent connections (up to 10,000 and more) and the most common way of creating code (sequential programming), when code either blocked the entire process or implied multiple execution stacks in the case of simultaneous connections.”</blockquote><p>— Wikipedia, History of Node.js</p><p>Problem of C10k pointed to common issues like:</p><ol><li>Blocked code</li><li>Lack of scalability</li></ol><p>And above issues were mostly handled by Async IO (as seen in Nginx and nodejs), making it most commonly used pattern (to date).</p><p>Let’s take a brief look at javascript/nodejs architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*uY-AfkIBBWMPLpTF" /></figure><p>Lot’s of nuts and bolts are involved here but core pieces of this architecture is blocking and non blocking ops. Thus, understanding of async IO (which was what non blocking io means) will further help us to understand how such system works. Let’s get started!</p><h3>Introduction to Sockets</h3><p>Since we are primarily dealing with async IO via socket, it is good to give some background of how socket IO actually works.</p><p>We will consider most general use-case, client-server model.</p><p>List of socket system calls are given below:</p><ol><li><em>socket</em>: returns file descriptor which can be used for communication.</li><li><em>bind</em>: binds socket to an address which is used be client to connect to server.</li><li><em>listen</em>: allows a socket to accept connection.</li><li><em>accept</em>: allows listening socket to accept connection from client</li><li><em>connect</em>: establish connection from one socket to another.</li></ol><p>Sockets facilitate communication between clients and servers. It is means of Inter-process communication (another very common method of IPC is pipes). The initial step in socket I/O communications involves creating a socket and binding it to an address for server. For client, once socket is created, it is ready for connection. The socket can be created using the <em>socket </em>system call (hereby referred as syscall) , which returns a file descriptor that can be utilized for subsequent operations.</p><p>Prototype:</p><pre>#include &lt;sys/socket.h&gt;<br>int socket(int domain, int type, int protocol);</pre><p>Connection domain defines method to identify a socket and range of communication (same host or remote computer). Most OS supports at least following domains:</p><ol><li><em>AF_UNIX</em> (Unix Domain socket): This domain allows communication in same host.</li><li><em>AF_INET/AF_INET6</em>: Allows communication between application in same or different hosts via IPv4/IPv6.</li></ol><p>AF stands for address family.</p><p>For AF_UNIX, address structure is defined as <em>sockaddr_un</em>. For AF_INET and AF_INET6, address structure used are <em>sockaddr_in </em>and <em>sockaddr_in6 </em>respectively.</p><p>Socket types are of two types:</p><ol><li><em>SOCK_STREAM</em>: stream socket, which are reliable , byte-stream channel with bidirectional data flow. As these operate in pair, they are called as connection oriented. Analogy for this will be talking to a person via phone.</li><li><em>SOCK_DGRAM</em>: datagram sockets, which allows data to be exchanged as messages (called as datagram). These are not reliable, can be out of order. This is also called as connection-less socket. Think of this as email were both sender and receiver don’t need to be active at same time, message may not be delivered.</li></ol><p>Protocol argument is specified as 0. It is used for sockets eg, IPPROTO_RAW. Some common protocols are defined as:</p><pre>/* Standard well-defined IP protocols.  */<br>enum<br>  {<br>    IPPROTO_IP = 0,    /* Dummy protocol for TCP.  */<br>#define IPPROTO_IP  IPPROTO_IP<br>    IPPROTO_ICMP = 1,    /* Internet Control Message Protocol.  */<br>#define IPPROTO_ICMP  IPPROTO_ICMP<br>    IPPROTO_IGMP = 2,    /* Internet Group Management Protocol. */<br>#define IPPROTO_IGMP  IPPROTO_IGMP<br>    IPPROTO_IPIP = 4,    /* IPIP tunnels (older KA9Q tunnels use 94).  */<br>#define IPPROTO_IPIP  IPPROTO_IPIP<br>    IPPROTO_TCP = 6,    /* Transmission Control Protocol.  */<br>/* snip */<br>}</pre><p>This can referred in /usr/include/netinet/in.h.</p><p>Rest of socket syscalls will be discussed later as we proceed through code.</p><h3>SOCKET IO</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*JgALQMneqXNeqDng7x_7cw.png" /><figcaption>Fig 1. Overview of streaming IO in sockets</figcaption></figure><p>Server is called passive socket as it is passive, it waits for something to connect. Client is known as active socket as it is actively looking to open connection, do some work (transfer data) and then close.</p><p>Technically, socket with connect is active (called as active open) and socket with listen is passive (called passive open). By default, socket is active.</p><h3>Writing synchronous SOCKET IO</h3><p>Let’s write server code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff6f6e32ff1366628a7de6cb046a0e7b/href">https://medium.com/media/ff6f6e32ff1366628a7de6cb046a0e7b/href</a></iframe><p>Let’s go in details for each of these function calls. If you notice main function, it is based exactly as per as Fig 1. Create, bind, listen, accept, handle request and close are called exactly in same order.</p><pre>int main(int argc, char *argv[])<br>{<br>    int sockfd = create_socket();<br>    bind_address(sockfd);<br>    if (listen(sockfd, BACKLOG) == -1)<br>    {<br>        printf(&quot;ERROR on listen&quot;);<br>        exit(1);<br>    }<br>    int afd = accept_connection(sockfd);<br>    handle_client_request(afd);<br>    close_socket(sockfd);<br>    return 0;<br>}</pre><p>First thing that needs to be done is creation of socket (this applies to both server and client). It is done by calling socket syscall.</p><pre>    int sockfd = socket(AF_INET, SOCK_STREAM, 0);</pre><p>Argument AF_INET defines domain as IPv4 and SOCK_STREAM set socket as streaming socket, protocol is set a 0. This syscall returns socket <em>file descriptor</em> which is stored in sockfd. About file descriptor-</p><blockquote>File descriptor, a small, nonnegative integer that is an index to an entry in the process’s table of open file descriptors. The file descriptor is used in<br> subsequent system calls (read(2), write(2), lseek(2), fcntl(2),<br> etc.) to refer to the open file. The file descriptor returned by<br> a successful call will be the lowest-numbered file descriptor not<br> currently open for the process.</blockquote><p>— Man page for open(2) for file descriptor</p><p>Once socket is created, it is needed to be bound to an address. Recall that we are creating a server application and client should know IP and port in order to access this application. <em>Bind</em> solves this problem.</p><pre>void bind_address(int sockfd)<br>{<br>    struct sockaddr_in serv_addr;<br>    serv_addr.sin_family = AF_INET;<br>    serv_addr.sin_port = htons(PORT);<br>    serv_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); // use 127.0.0.1<br><br>    if (bind(sockfd, (struct sockaddr *)&amp;serv_addr, sizeof(serv_addr)) &lt; 0)<br>    {<br>        printf(&quot;ERROR on binding&quot;);<br>        exit(1);<br>    }<br>}</pre><p>Arguments of bind are socket file descriptor, which we already have as sockfd. Second and third parameters are socket address and length of socket address.</p><p>Socket address is defined by structure sockaddr_in (sockaddr_un can be used for AF_UNIX type of domain):</p><pre>struct sockaddr_in serv_addr;<br>serv_addr.sin_family = AF_INET;<br>serv_addr.sin_port = htons(PORT);<br>serv_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); // use 127.0.0.1</pre><p>This needs to be cast to <em>struct sockaddr * </em>as that is what bind expect. This is <em>polymorphism </em>which allows same parameter of bind (with type <em>struct sockaddr *</em>) accept different address types.</p><p>htons/htonl converts host byte order to network byte order. This is required because LSB/MSB varies from architecture to architecture (little endian/big endian) but network needs uniform way to know LSB and MSB in order to understand the data. Hence, these convenience functions allows such conversions to happen easily.</p><p>Now we are done with binding to address, server can start listening by listen syscall.</p><pre>    if (listen(sockfd, BACKLOG) == -1)<br>    {<br>        printf(&quot;ERROR on listen&quot;);<br>        exit(1);<br>    }</pre><p>Backlog parameter defines number of connections that can be queued for acceptance. Important thing to note here is that listen doesn’t block. So, if you are planning to create web server which can handle multiple client connection, socket setup from creation of socket until listen would remain same. Whatever commands comes below this, that is what needs to be scaled.</p><p>Next comes <em>accept</em> syscall, which is defined as:</p><pre>int accept_connection(int sockfd)<br>{<br>    printf(&quot;Listening\n&quot;);<br>    int afd = accept(sockfd, NULL, 0);<br>    if (afd &lt; 0)<br>    {<br>        printf(&quot;ERROR on accept&quot;);<br>        exit(1);<br>    }<br>    return afd;<br>}</pre><p>The second and third parameter is used to get client address.</p><p>Prototype of accept can be found by man 2 accept (man 2 refers to man pages about APIs, refer man man for more details).</p><p>The <em>accept </em>syscall is blocking and until any client connects, it won’t proceed ahead. Once client connects, it creates a new connected socket and returns a file descriptor referring to this socket. The newly created socket is not in the listening state (as sockfd). The original socket sockfd is unaffected by this call.</p><p>New socket file descriptor afd can now be used for subsequent communication with client. It is important to note that original socket is free and can be used for accepting another connections but it can not be done as program is currently busy serving the client (this is important distinction which will ultimately allows us to scale the application if we can decouple listening logic and serving client logic).</p><p>handle_client_request functions handles communication with the client.</p><pre>void handle_client_request(int afd)<br>{<br>    char buf[BUF_SIZE];<br>    char write_buf[BUF_SIZE] = &quot;Greetings from server \n&quot;;<br><br>    ssize_t bytes_read = read(afd, buf, READ_BUF);<br>    if (bytes_read &lt; 0)<br>    {<br>        printf(&quot;ERROR reading from socket&quot;);<br>        exit(1);<br>    }<br>    printf(&quot;%.*s\n&quot;, (int)bytes_read, buf);<br><br>    ssize_t bytes_written = write(afd, write_buf, sizeof(write_buf));<br>    if (bytes_written != sizeof(write_buf))<br>    {<br>        printf(&quot;ERROR writing to socket&quot;);<br>        exit(1);<br>    }<br>    printf(&quot;Send response to client&quot;);<br>}</pre><p>It reads data upto READ_BUF length and store it to buf and then writes data stored in write_buf to client. All of this is done by connected socket which is referred nu afd.</p><p>You can compile above code by saving it as file_name.c (let say sv.c) and running:</p><pre>gcc -g sv.c -o sv</pre><p>If you don’t have gcc, you will need to install this. For ubuntu/debain based system, it can be installed by sudo apt install build-essential. After installation instruction as per as your environment. GCC flag -g installs debug symbols (in case you want to run through this via gdb) and -o specify output file, which is sv.</p><p>Run the application by</p><pre>./sv</pre><p>You would see output like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*F4z6Ir18xfqhhVRaszdnng.png" /></figure><p>Nothing really happens, program is stuck at accept syscall (this can be verified by running this program as sudo gdb sv and pressing r and stepping through code). We would need to create client program to connect to our server.</p><p>Client code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/243024a7f02002a8514a48f86daf0aad/href">https://medium.com/media/243024a7f02002a8514a48f86daf0aad/href</a></iframe><p>Client works in similar way as the server. Firstly, we create socket and then we call connect syscall to connect to server.</p><pre>void connect_to_server(int sockfd)<br>{<br>    struct sockaddr_in serv_addr;<br>    serv_addr.sin_family = AF_INET;<br>    serv_addr.sin_port = htons(PORT);<br>    serv_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);<br><br>    if (connect(sockfd, (struct sockaddr *)&amp;serv_addr, sizeof(serv_addr)) &lt; 0)<br>    {<br>        printf(&quot;ERROR on connect&quot;);<br>        exit(1);<br>    }<br>}</pre><p>Connect syscall accepts socket file descriptor and address structure where we want to connect and its length. Address structure is defined similar to as it as it done for the server.</p><p>Now, compile above code</p><pre>gcc cl.c -o cl</pre><p>Run both client and server. Server should be run first. If you run client before running server, there won’t be any application listening to port which client will try to connect. Leading to error as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*uf8go-UIcZVGWrozIC-J-Q.png" /></figure><p>Once you run ./sv, server would wait until client connects to it. End result would look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*18QRXMOXWoZsq_0Mh9RiBQ.png" /></figure><p>Above issue with this code is that at any given time, it can at most serve only one client. We may scale this by using threads and handle accept inside a thread (one thread for each connection) but let’s handle it in better way.</p><h3>Asynchronous Socket IO</h3><p>In this section, we will be making server logic asynchronous so that it can handle more than one connection. There are two ways to do this, instead of <em>accept</em> syscall, use <em>accept4</em>, which uses flags in 4th argument, where we can pass SOCK_NONBLOCK flag. Another way is to call <em>fcntl</em> to change file descriptor (sockfd) to non blocking. In this section, we are going to use later method for asynchronous IO.</p><p>Let’s look at modified server code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a9995f36205fda215fa3bb5a1e21799/href">https://medium.com/media/0a9995f36205fda215fa3bb5a1e21799/href</a></iframe><p>Only difference between this code and synchronous code is as given below:</p><pre>void set_socket_nonblocking(int sockfd)<br>{<br>    int flags = fcntl(sockfd, F_GETFL, 0); // get old flags<br>    flags |= O_NONBLOCK;<br>    if (fcntl(sockfd, F_SETFL, flags) &lt; 0)<br>    {<br>        printf(&quot;Fail to make socket non-blocking&quot;);<br>        exit(1);<br>    }<br>}</pre><p>Above code add current flags set on file descriptor sockfd by calling <em>fcntl</em> syscall and passing F_GETFL, which returns flags on specified descriptor. New flag O_NONBLOCK is ORed (added) to existing flag and set by calling <em>fnctl</em> again using F_SETFL. More details on flag can be read <a href="https://www.gnu.org/software/libc/manual/html_node/Open_002dtime-Flags.html">here</a> and fcntl man pages (man 2 fcntl).</p><p>If you compile and run above code (remember only server code, we are not going to make any changes in client, we will reusing same client code again and again), you will something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*nFNDVJ78rk99yN27ufNMXQ.png" /></figure><p>Notice, accept didn’t wait for a client to connect, call simply went through, and instead of returning connected socket file descriptor (afd), it returned error i.e. -1 which we caught and displayed above error. Learnings from this code is that once we make function call asynchronous or non blocking, we need to put additional mechanism to handle the async-y case, what we usually expect won’t show up in first function call. Whenever resource (here, network IO or socket), becomes available, we would need to react to it, hence it is<strong><em> Reactor pattern.</em></strong></p><p>Let’s make it functional, look at modified code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cc996b7b72824e7068d786ddeea4872/href">https://medium.com/media/7cc996b7b72824e7068d786ddeea4872/href</a></iframe><p>Changed lines are around <em>accept</em> syscall (and an added loop):</p><pre>int accept_connection(int sockfd)<br>{<br>    int afd = accept(sockfd, NULL, 0);<br>    if (afd &lt; 0)<br>    {<br>        if (errno == EAGAIN)<br>        {<br>            sleep(1); // Can do something useful here<br>            return -1;<br>        }<br>        else<br>        {<br>            printf(&quot;ERROR on accept&quot;);<br>            exit(1);<br>        }<br>    }<br>    return afd;<br>}</pre><p>Important point to note here while working with syscalls with O_NONBLOCK flag is that as these calls do not wait for IO to finish, they return corresponding failure value in return (afd is returned as -1) and global <strong><em>errno</em></strong> constant is set to EAGAIN, which means, try again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*sYrqD9AejC7ifWnKvEfx2g.png" /><figcaption>error-base.h</figcaption></figure><p>Idea is to keep trying <em>accept</em> syscall again and again until we get some output (or we get interrupted, which is not handled here) i.e. afd != -1, when afd is valid file descriptor pointing to socket.</p><p>If you run above code, you will notice that it works same as synchronous code as it is able to handle only one connection. As it is on loop, it can process more accept requests (again sequentially and one at a time). Main thing to focus here is these line.</p><pre>if (errno == EAGAIN)<br>{<br>    sleep(0.1); // Can do something useful here<br>    return -1;<br>}</pre><p>Here, instead of sleeping, <em>if</em> we can do something useful, things would get much more better.</p><p>Now that <em>something useful</em> could be, <strong><em>processing another request</em></strong>.</p><p>Let’s try another iteration of code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a63f3610b20e75e88edf78d7c0f4497/href">https://medium.com/media/3a63f3610b20e75e88edf78d7c0f4497/href</a></iframe><p>In above code, we are maintaining list of active socket file descriptors (as returned by accept whenever accept syscall gets a connection (i.e. valid afd). Connection is not immediately processed, instead it is done in next loop whenever accept returns -1 and <em>errno</em> is <strong>EAGAIN</strong>, that is, we need to try again, we can do processing of request (which is done by process_client function. Once processing is done, we remove file descriptor corresponding to that active socket. In this way, instead of sleeping and doing nothing (as it was done earlier), we are doing something useful.</p><p>Notice this approach is bit cumbersome, we have handle active file descriptors, addition and removal is bit tricky and in above code, it hardly scales much (owning to limited array size and not so great descriptor management).</p><p>Running same profiling command again:</p><pre>time seq 900 | xargs -I {} -P 0 sh -c &#39;./cl&#39;</pre><p>Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*0cRUEtDtl3B7W0s6iBclLw.png" /></figure><p>This is really interesting, we made few changes (mainly changing file descriptor for socket from synchronous to NON blocking and some book-keeping mechanism to maintain active socket) and our program which could serve one request at a time earlier, is now easily serving 900 requests without much fuss.</p><p>At this point, we have somewhat semblance of callbacks. <em>process_client is a callback function which gets called when corresponding IO is available (future is resolved).</em></p><h3>Enter EPOLL</h3><p>The epoll API is a Linux-specific interface that enables monitoring multiple file descriptors simultaneously to determine if any of them are ready for I/O operations. Compared to manually monitoring file descriptors, as discussed in the previous section, epoll offers several advantages:</p><p>a) epoll reduces latency by minimizing the delay between polling and detecting ready I/O. When using manual polling, there may be a significant time gap between each poll, leading to high latency.</p><p>b) epoll is more efficient in terms of CPU usage as it avoids the need for continuously polling in a tight loop. If we polling in tight loop in our code to avoid issue mentioned in #1, there will be waste of cpu cycles (<em>busy waiting</em>).</p><p>c) epoll minimizes the number of system calls to the kernel. With manual polling, multiple system calls may be required to check the status of each file descriptor individually. In contrast, epoll consolidates these operations, resulting in fewer system calls and improving overall performance.</p><p>epoll consists of three syscalls:</p><ol><li>epoll_create(): create epoll instance</li><li>epoll_ctl(): add or remove file descriptor which we want to monitor</li><li>epoll_wait(): wait till file descriptors being monitored are ready</li></ol><p>Refer new server code with epoll taken into account:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0df8ed48e425970d86db4abf978ab04/href">https://medium.com/media/b0df8ed48e425970d86db4abf978ab04/href</a></iframe><p>Notice active_fds array from previous code is removed here and hence there is no such limitation on number of async call this server can run.</p><p>Let’s go into code one by one</p><pre>    int epfd, ready, j;<br>    struct epoll_event ev;<br>    struct epoll_event evlist[MAX_EVENTS];<br>    epfd = epoll_create(5000);<br>    if (epfd == -1)<br>        printf(&quot;epoll_create&quot;);</pre><p>In above snippet epoll_create is called, which create epoll instance and returns file descriptor to access this instance. Argument to this method is size, which is hint for number of file descriptor that are needed to be monitored (it is generally ignored). Rest of the data structure, namely evlist are used later for storing information related to file descriptor of interested and similarly ev specifies which file descriptor to monitor and under which event.</p><p>Whenever new connection comes, we add its corresponding socket file descriptor into epoll instance as given below:</p><pre>        ev.data.fd = afd;<br>        ev.events = EPOLLIN;<br>        if (epoll_ctl(epfd, EPOLL_CTL_ADD, afd, &amp;ev) == -1)<br>            printf(&quot;epoll_ctl add failed&quot;);</pre><p>As seen above, file descriptor return by <em>accept</em> is stored in ev.data.fd and ev.events specify which events we are interested in.</p><p>EPOLLIN event is raised when the associated file descriptor is available for <a href="https://man7.org/linux/man-pages/man2/read.2.html">read</a> operations. For more details refer man 2 epoll_ctl. This is event we are interested in as we are going to do read operation from socket (write operation is not covered for sake of simplicity, but it can be done by EPOLLOUT event)</p><blockquote>EPOLLIN -The associated file is available for read(2) operations.</blockquote><blockquote>EPOLLOUT -The associated file is available for write(2) operations.</blockquote><blockquote>EPOLLRDHUP-Stream socket peer closed connection, or shut down writing half of connection.</blockquote><blockquote>EPOLLPRI -There is an exceptional condition on the file descriptor. See the discussion of POLLPRI in poll(2).</blockquote><blockquote>EPOLLERR -Error condition happened on the associated file descriptor. This event is also reported for the write end of a pipe when the read end has been closed.</blockquote><blockquote>EPOLLHUP-Hang up happened on the associated file descriptor.</blockquote><p>— Available events as per as man 2 epoll_ctl</p><p>epoll_ctl is used to add (with EPOLL_CTL_ADD) this new event and associated file descriptor for monitoring.</p><p>This is where actual thing happens:</p><pre>ready = epoll_wait(epfd, evlist, MAX_EVENTS, 0.01);</pre><p>Once this function is called, epoll waits untill the registered file descriptors becomes ready (last argument is timeout, -1 means wait till infinity, here as timeout is 0.01, it will returns all file descriptors which gets ready by that time). <em>ready</em> variable stores number of file descriptor which are ready for IO. <em>evlist</em> is used to store information regarding these active file descriptors. Once we have this information, we can loop through it.</p><pre>for (j = 0; j &lt; ready; j++)<br>{<br>    if (evlist[j].events &amp; EPOLLIN)<br>    {<br>        int ready_afd = evlist[j].data.fd;<br>        process_client(ready_afd);<br>        if (epoll_ctl(epfd, EPOLL_CTL_DEL, ready_afd, NULL) == -1)<br>            printf(&quot;epoll_ctl remove failed&quot;);<br>        close(ready_afd);<br>        count--;<br>        printf(&quot;Total processed messages %d\n&quot;, total_processed);<br>    }<br>}</pre><p>The corresponding processing is performed on the ready file descriptor, and once it is used, we need to delete it from the list of interested file descriptors in epoll. This deletion is accomplished by making another call to <em>epoll_ctl</em> with the EPOLL_CTL_DEL parameter.</p><p>Let’s compile and run above program against C100k problem.</p><pre>time seq 100000 | xargs -I {} -P 0 sh -c &#39;./cl&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*iDrluaYIv7qzxIYgXuJ8QA.png" /></figure><p>Timing result is really cool. It runs through 100k requests in less than a minute. I know it is not true 100k simultaneous connection (VM which I am running code, hardly has 4 vCPUs) but point is, this is dramatically better than what we begin with.</p><h3>Conclusion</h3><p>In this article, we went through Async IO programming and apart from seeing obvious performance improvement, we got glimpse of callback function in action (as process_client ). This callback function gets called whenever IO is ready, exactly as seen in other high level languages but in low level system APIs. We can spend some effort and rewrite above logic in side loop as:</p><p>run_handler(socket_IO, <em>callback_function</em>)</p><p>This could easily fill in different use cases of socket IO operation. We would just need to register our callback function and run loop (refer main loop while(1)). This would essential make a stepping stone around which event loops are build, which powers most of the high performance software on internet (nodejs, nginx etc).</p><h3><em>Next</em></h3><p>Go ahead and clone libuv (<a href="https://github.com/libuv/libuv">https://github.com/libuv/libuv</a>). Search for <em>epoll_wait. </em><strong><em>Backtrace from there as you know exactly what is happening at that point.</em></strong></p><p>Look at event loop flowchart below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0XeQSo1aabAF8DrB" /></figure><p>Most of things would make sense now as we have discussed Poll I/O internals in this articles which gives us good foundation to explore the rest.</p><p>References:</p><ol><li>The Linux Programming Interface by Michael Kerrisk</li><li>man pages</li><li>Example of epoll: <a href="https://web.archive.org/web/20120504033548/https://banu.com/blog/2/how-to-use-epoll-a-complete-example-in-c/">https://web.archive.org/web/20120504033548/https://banu.com/blog/2/how-to-use-epoll-a-complete-example-in-c/</a></li><li>Linux source code</li><li>Libuv docs and source code</li></ol><p><em>Feel free to add any suggestions in the comments or reach me out at itsankitkp@gmail.com.</em></p><p><em>Special thanks to Alankrita Gupta (goldi1395@gmail.com) for additional inputs.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f253ab1062a6" width="1" height="1" alt=""><hr><p><a href="https://tech.mammoth.io/understanding-the-fundamentals-of-asynchronous-programming-with-prototype-code-f253ab1062a6">Understanding the fundamentals of Asynchronous Programming with Prototype Code</a> was originally published in <a href="https://tech.mammoth.io/">Technology at Mammoth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stepping through PostgreSQL]]></title>
            <link>https://blog.devgenius.io/stepping-through-postgresql-f40990685a56?source=rss-285c7ae18b08------2</link>
            <guid isPermaLink="false">https://medium.com/p/f40990685a56</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[gdb]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Ankit K Pandey]]></dc:creator>
            <pubDate>Mon, 31 Oct 2022 16:07:17 GMT</pubDate>
            <atom:updated>2022-11-04T18:19:52.305Z</atom:updated>
            <content:encoded><![CDATA[<p>Postgres is one of most loved, most used and most wanted database in the world and it is no brainer that some of us do what to see how it makes all magic happen. While looking for the same, I was surprised how easy it is to walk through Postgres codebase by stepping through postgres backend process. This article can be used as reference guide to explore postgres codebase quickly.</p><p>Note: I highly recommend setting up a testing machine (vm) and running live Postgres system as you read this article.</p><p><strong>Quick guide to GDB</strong></p><ol><li>To attach to a process:<em> sudo gdb -p &lt;PID&gt;</em></li><li>Attach breakpoint: <em>break &lt;file&gt;:&lt;line no&gt;</em></li><li>Run until breakpoint: <em>c</em></li><li>Single step <em>into</em> the function: <em>s</em></li><li>Step <em>over</em> the function: <em>n</em></li><li>Print a value: <em>p &lt;variable&gt;</em> or <em>p *&lt;variable&gt;</em></li><li>Call a function:<em> call &lt;func&gt;</em></li><li>Print postgres node: <em>call pprint(&lt;mem address&gt;)</em></li><li>Pressing <em>enter </em>key repeats last command.</li></ol><p>Note: While reading the article, you may (or will) get lost, in such case, finish current execution, add a new breakpoint on function where you supposed to be, execute query and run debugger again.</p><h3><strong>Setup</strong></h3><p>Let’s clone latest postgres (16devel in my case) and build it with debug symbols. Before starting ensure that you have proper build tools (gcc via build-essentials etc).</p><pre>git clone <a href="https://git.postgresql.org/git/postgresql.git">https://git.postgresql.org/git/postgresql.git</a></pre><pre># I highly recommend checking out this commit so that<br># functions/files which I mention here remains consistent<br>git checkout 5543677ec90a15c73dab5ed4f0902b3b920f0b87</pre><pre>./configure   --enable-debug<br>make -j4<br>sudo make install</pre><pre>sudo adduser postgres<br>sudo mkdir /usr/local/pgsql/data<br>chown postgres /usr/local/pgsql/data</pre><pre># start postgres with output to stdout (keep this terminal open)<br>/usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data <br></pre><p>Prepare psql client:</p><pre>sudo su postgres</pre><pre># create a dummy db<br>/usr/local/pgsql/bin/createdb test</pre><pre># open psql<br>/usr/local/pgsql/bin/psql test</pre><p>Create a dummy table and insert some values:</p><pre>create table t(id int);</pre><pre>insert into t values(1);<br>insert into t values(2);<br>insert into t values(10);</pre><p>Postgres main backend process is defined at <em>PostgresMain </em>in src/backend/tcop/postgres.c. Initialization of backend process happens here. Let’s read code a bit.</p><pre>InitPostgres(dbname, InvalidOid,   /* database to connect to */<br>username, InvalidOid,  /* role to connect as */<br>!am_walsender, /* honor session_preload_libraries? */<br>false,         /* don&#39;t ignore datallowconn */<br>NULL);         /* no out_dbname */</pre><p>Main loop:</p><pre>for (;;)<br>{</pre><pre>...</pre><p>Set connection status</p><p><em>set_ps_display(“idle in transaction”)</em> or <em>set_ps_display(“idle”)</em> depending on <em>IsTransactionOrTransactionBlock().</em></p><p>and so on.</p><p>We are good to go now, let’s start:</p><pre>SELECT pg_backend_pid();</pre><p>This will give us postgres backend process id. We will be attaching this to gdb.</p><p>In new terminal, run</p><pre>sudo gdb -p &lt;pid from above&gt;</pre><p>It should properly load debug symbols:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9N1qB1XCaYWnXk6pIikidQ.png" /></figure><p>Add a breakpoint, for example, <em>firstchar = ReadCommand(&amp;input_message) </em>which<em> </em>is located at src/backend/tcop/postgres.c:4483</p><pre>break src/backend/tcop/postgres.c:4483</pre><p>In psql, run some query, say:</p><pre>select * from t where id &gt; 1 and id &lt; 10;</pre><p>You can either <em>continue </em>to breakpoint (press c) or watch how things unfold from beginning itself (keep pressing n).</p><p>In later case, you would see some WaitEvents and network i/o to receive input packets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*jvCkHDkHlBHOImaz3O7opg.png" /></figure><p>You can continue pressing n (or pressing enter) and watch the control flow. You will notice lot of <em>CHECK_FOR_INTERRUPTS</em>().</p><p>Interrupt handling is defined in <em>ProcessInterrupts</em> in src/backend/tcop/postgres.c.</p><p>Anyways, moving ahead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*hjTOoggu6LO95P9s5JJfnQ.png" /><figcaption>Printing firstchar</figcaption></figure><p>Remember <em>firstchar = ReadCommand(&amp;input_message)? </em>It reads our input and dumps<em> firstchar</em> (which is 81)</p><p>Decimal 81 is character Q in ASCII.</p><pre>switch (firstchar)<br>  {<br>   case &#39;Q&#39;:   /* simple query */<br>    {<br>     const char *query_string;</pre><pre>/* Set statement_timestamp() */<br>     SetCurrentStatementStartTimestamp();</pre><pre>query_string = pq_getmsgstring(&amp;input_message);<br>     pq_getmsgend(&amp;input_message);</pre><pre>if (am_walsender)<br>     {<br>      if (!exec_replication_command(query_string))<br>       exec_simple_query(query_string);<br>     }<br>     else<br>      exec_simple_query(query_string);</pre><pre>send_ready_for_query = true;<br>    }<br>    break;</pre><p>Here, we are going to case ‘Q’. We can verify our query string here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*3gAO_B0RIz6fpITr7FPkDQ.png" /></figure><p>Finally <em>exec_simple_query(query_string)</em> gets called. We need to step into this (press s )</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*eC2Dbcx_UEjPET6crgOe5g.png" /></figure><p>Step twice and you will find pgstat_report_activity(STATE_RUNNING, query_string). pgstat_report_activity is defined in src/backend/utils/activity/backend_status.c.</p><p>Backend status is defined as enum:</p><pre>typedef enum BackendState<br>{<br> STATE_UNDEFINED,<br> STATE_IDLE,<br> STATE_RUNNING,<br> STATE_IDLEINTRANSACTION,<br> STATE_FASTPATH,<br> STATE_IDLEINTRANSACTION_ABORTED,<br> STATE_DISABLED<br>} BackendState;</pre><p>which conveniently get transformed into usual notation in pg_stat_get_activity() defined in src/backend/utils/adt/pgstatfuncs.c.</p><pre>switch (beentry-&gt;st_state)<br>   {<br>    case STATE_IDLE:<br>     values[4] = CStringGetTextDatum(&quot;idle&quot;);<br>     break;<br>    case STATE_RUNNING:<br>     values[4] = CStringGetTextDatum(&quot;active&quot;);<br>     break;<br>    case STATE_IDLEINTRANSACTION:<br>     values[4] = CStringGetTextDatum(&quot;idle in transaction&quot;);<br>     break;<br>    case STATE_FASTPATH:<br>     values[4] = CStringGetTextDatum(&quot;fastpath function call&quot;);<br>     break;<br>    case STATE_IDLEINTRANSACTION_ABORTED:<br>     values[4] = CStringGetTextDatum(&quot;idle in transaction (aborted)&quot;);<br>     break;<br>    case STATE_DISABLED:<br>     values[4] = CStringGetTextDatum(&quot;disabled&quot;);<br>     break;<br>    case STATE_UNDEFINED:<br>     nulls[4] = true;<br>     break;<br>   }</pre><p>Alright, query status is running now.</p><p>We reach <em>start_xact_command</em> (defined in src/backend/tcop/postgres.c)</p><pre>/*<br> * Convenience routines for starting/committing a single command.<br> */<br>static void<br>start_xact_command(void)<br>{<br> if (!xact_started)<br> {<br>  StartTransactionCommand();</pre><pre>xact_started = true;<br> }</pre><pre>/*<br>  * Start statement timeout if necessary.  Note that this&#39;ll intentionally<br>  * not reset the clock on an already started timeout, to avoid the timing<br>  * overhead when start_xact_command() is invoked repeatedly, without an<br>  * interceding finish_xact_command() (e.g. parse/bind/execute).  If that&#39;s<br>  * not desired, the timeout has to be disabled explicitly.<br>  */<br> enable_statement_timeout();</pre><pre>/* Start timeout for checking if the client has gone away if necessary. */<br> if (client_connection_check_interval &gt; 0 &amp;&amp;<br>  IsUnderPostmaster &amp;&amp;<br>  MyProcPort &amp;&amp;<br>  !get_timeout_active(CLIENT_CONNECTION_CHECK_TIMEOUT))<br>  enable_timeout_after(CLIENT_CONNECTION_CHECK_TIMEOUT,<br>        client_connection_check_interval);<br>}</pre><p>Alright, makes sense. Moving ahead, we come across <em>memoryContext</em> which switches to <em>unnamed prepared statement (</em>pretty neat)! Keep stepping through until you reach <em>parsetree_list = pg_parse_query(query_string)</em></p><p>Call n (instead of stepping in, as we are not going to look how parsing works), and <em>p parsetree_list</em> to get its address. Now let’s print parsetree.</p><p><em>call pprint(&lt;mem_address&gt;)</em> and look into output of postgres process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*bMRARoeZqr8AfRUSXqvjBg.png" /></figure><p>In postgres backend stdout:</p><pre>(<br>   {RAWSTMT <br>   :stmt <br>      {SELECTSTMT <br>      :distinctClause &lt;&gt; <br>      :intoClause &lt;&gt; <br>      :targetList (<br>         {RESTARGET <br>         :name &lt;&gt; <br>         :indirection &lt;&gt; <br>         :val <br>            {COLUMNREF <br>            :fields (<br>               {A_STAR<br>               }<br>            )<br>            :location 7<br>            }<br>         :location 7<br>         }<br>      )<br>      :fromClause (<br>         {RANGEVAR <br>         :schemaname &lt;&gt; <br>         :relname t <br>         :inh true <br>         :relpersistence p <br>         :alias &lt;&gt; <br>         :location 14<br>         }<br>      )<br>      :whereClause <br>         {BOOLEXPR <br>         :boolop and <br>         :args (<br>            {A_EXPR <br>            :name (&quot;&gt;&quot;)<br>            :lexpr <br>               {COLUMNREF <br>               :fields (&quot;id&quot;)<br>               :location 22<br>               }<br>            :rexpr <br>               {A_CONST <br>               :val 1 <br>               :location 27<br>               }<br>            :location 25<br>            }<br>            {A_EXPR <br>            :name (&quot;\&lt;&quot;)<br>            :lexpr <br>               {COLUMNREF <br>               :fields (&quot;id&quot;)<br>               :location 33<br>               }<br>            :rexpr <br>               {A_CONST <br>               :val 10 <br>               :location 38<br>               }<br>            :location 36<br>            }<br>         )<br>         :location 29<br>         }<br>      :groupClause &lt;&gt; <br>      :groupDistinct false <br>      :havingClause &lt;&gt; <br>      :windowClause &lt;&gt; <br>      :valuesLists &lt;&gt; <br>      :sortClause &lt;&gt; <br>      :limitOffset &lt;&gt; <br>      :limitCount &lt;&gt; <br>      :limitOption 0 <br>      :lockingClause &lt;&gt; <br>      :withClause &lt;&gt; <br>      :op 0 <br>      :all false <br>      :larg &lt;&gt; <br>      :rarg &lt;&gt;<br>      }<br>   :stmt_location 0 <br>   :stmt_len 40<br>   }<br>)</pre><p>This is raw parse tree (known as abstract syntax tree, AST in short). Let’s keep moving ahead until we reach to <em>RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*0Exlk8Eyrm4BvhHQphDx5w.png" /></figure><p>In present case, <em>lfirst_node </em>is same as parsetree printed before (so we have just a single node).</p><p><em>commandTag = CreateCommandTag(parsetree-&gt;stmt)</em></p><p>where commandTag is CMDTAG_SELECT, which gets passed to set_ps_display(GetCommandTagName(commandTag)) for use in status display.</p><p>We finally reach <em>BeginCommand(commandTag, dest), </em>recall commandTag=CMDTAG_SELECT, and dest=DestRemote. Since we are not passing parsetree into this, this must be doing some other stuffs.</p><blockquote>BeginCommand — initialize the destination at start of command</blockquote><pre>void<br>BeginCommand(CommandTag commandTag, CommandDest dest)<br>{<br> /* Nothing to do at present */<br>}</pre><p>BeginCommand is defined in src/backend/tcop/dest.c. Unless I am missing something, it is not doing anything impressive. Moving on!</p><p>We find another start_xact_command() and CHECK_FOR_INTERRUPTS, which is good. Postgres has parsed our query but not have yet created plans or started any execution.</p><p>A very important comment is seen at this point.</p><blockquote>/*<br> * If using an implicit transaction block, and we’re not already in a<br> * transaction block, start an implicit block to force this statement<br> * to be grouped together with any following ones. (We must do this<br> * each time through the loop; otherwise, a COMMIT/ROLLBACK in the<br> * list would cause later statements to not be grouped.)<br> */</blockquote><p>We reach at <em>querytree_list = pg_analyze_and_rewrite_fixedparams(parsetree, query_string, NULL, 0, NULL)</em></p><p>Let’s see how this tree looks like after analyze and rewrite.</p><pre>(<br>   {QUERY <br>   :commandType 1 <br>   :querySource 0 <br>   :canSetTag true <br>   :utilityStmt &lt;&gt; <br>   :resultRelation 0 <br>   :hasAggs false <br>   :hasWindowFuncs false <br>   :hasTargetSRFs false <br>   :hasSubLinks false <br>   :hasDistinctOn false <br>   :hasRecursive false <br>   :hasModifyingCTE false <br>   :hasForUpdate false <br>   :hasRowSecurity false <br>   :isReturn false <br>   :cteList &lt;&gt; <br>   :rtable (<br>      {RANGETBLENTRY <br>      :alias &lt;&gt; <br>      :eref <br>         {ALIAS <br>         :aliasname t <br>         :colnames (&quot;id&quot;)<br>         }<br>      :rtekind 0 <br>      :relid 16389 <br>      :relkind r <br>      :rellockmode 1 <br>      :tablesample &lt;&gt; <br>      :lateral false <br>      :inh true <br>      :inFromCl true <br>      :requiredPerms 2 <br>      :checkAsUser 0 <br>      :selectedCols (b 8)<br>      :insertedCols (b)<br>      :updatedCols (b)<br>      :extraUpdatedCols (b)<br>      :securityQuals &lt;&gt;<br>      }<br>   )<br>   :jointree <br>      {FROMEXPR <br>      :fromlist (<br>         {RANGETBLREF <br>         :rtindex 1<br>         }<br>      )<br>      :quals <br>         {BOOLEXPR <br>         :boolop and <br>         :args (<br>            {OPEXPR <br>            :opno 521 <br>            :opfuncid 147 <br>            :opresulttype 16 <br>            :opretset false <br>            :opcollid 0 <br>            :inputcollid 0 <br>            :args (<br>               {VAR <br>               :varno 1 <br>               :varattno 1 <br>               :vartype 23 <br>               :vartypmod -1 <br>               :varcollid 0 <br>               :varlevelsup 0 <br>               :varnosyn 1 <br>               :varattnosyn 1 <br>               :location 22<br>               }<br>               {CONST <br>               :consttype 23 <br>               :consttypmod -1 <br>               :constcollid 0 <br>               :constlen 4 <br>               :constbyval true <br>               :constisnull false <br>               :location 27 <br>               :constvalue 4 [ 1 0 0 0 0 0 0 0 ]<br>               }<br>            )<br>            :location 25<br>            }<br>            {OPEXPR <br>            :opno 97 <br>            :opfuncid 66 <br>            :opresulttype 16 <br>            :opretset false <br>            :opcollid 0 <br>            :inputcollid 0 <br>            :args (<br>               {VAR <br>               :varno 1 <br>               :varattno 1 <br>               :vartype 23 <br>               :vartypmod -1 <br>               :varcollid 0 <br>               :varlevelsup 0 <br>               :varnosyn 1 <br>               :varattnosyn 1 <br>               :location 33<br>               }<br>               {CONST <br>               :consttype 23 <br>               :consttypmod -1 <br>               :constcollid 0 <br>               :constlen 4 <br>               :constbyval true <br>               :constisnull false <br>               :location 38 <br>               :constvalue 4 [ 10 0 0 0 0 0 0 0 ]<br>               }<br>            )<br>            :location 36<br>            }<br>         )<br>         :location 29<br>         }<br>      }<br>   :mergeActionList &lt;&gt; <br>   :mergeUseOuterJoin false <br>   :targetList (<br>      {TARGETENTRY <br>      :expr <br>         {VAR <br>         :varno 1 <br>         :varattno 1 <br>         :vartype 23 <br>         :vartypmod -1 <br>         :varcollid 0 <br>         :varlevelsup 0 <br>         :varnosyn 1 <br>         :varattnosyn 1 <br>         :location 7<br>         }<br>      :resno 1 <br>      :resname id <br>      :ressortgroupref 0 <br>      :resorigtbl 16389 <br>      :resorigcol 1 <br>      :resjunk false<br>      }<br>   )<br>   :override 0 <br>   :onConflict &lt;&gt; <br>   :returningList &lt;&gt; <br>   :groupClause &lt;&gt; <br>   :groupDistinct false <br>   :groupingSets &lt;&gt; <br>   :havingQual &lt;&gt; <br>   :windowClause &lt;&gt; <br>   :distinctClause &lt;&gt; <br>   :sortClause &lt;&gt; <br>   :limitOffset &lt;&gt; <br>   :limitCount &lt;&gt; <br>   :limitOption 0 <br>   :rowMarks &lt;&gt; <br>   :setOperations &lt;&gt; <br>   :constraintDeps &lt;&gt; <br>   :withCheckOptions &lt;&gt; <br>   :stmt_location 0 <br>   :stmt_len 40<br>   }<br>)</pre><p>Impressive! Notice how RAWSTMT from earlier got converted into QUERY.</p><p>Next up ahead: <em>plantree_list = pg_plan_queries(querytree_list, query_string,<br> CURSOR_OPT_PARALLEL_OK, NULL)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*wia3XF-2wAZx6NbSOzzYdQ.png" /></figure><p><em>plantree_list </em>looks like this:</p><pre>(<br>   {PLANNEDSTMT <br>   :commandType 1 <br>   :queryId 0 <br>   :hasReturning false <br>   :hasModifyingCTE false <br>   :canSetTag true <br>   :transientPlan false <br>   :dependsOnRole false <br>   :parallelModeNeeded false <br>   :jitFlags 0 <br>   :planTree <br>      {SEQSCAN <br>      :scan.plan.startup_cost 0 <br>      :scan.plan.total_cost 48.25 <br>      :scan.plan.plan_rows 13 <br>      :scan.plan.plan_width 4 <br>      :scan.plan.parallel_aware false <br>      :scan.plan.parallel_safe true <br>      :scan.plan.async_capable false <br>      :scan.plan.plan_node_id 0 <br>      :scan.plan.targetlist (<br>         {TARGETENTRY <br>         :expr <br>            {VAR <br>            :varno 1 <br>            :varattno 1 <br>            :vartype 23 <br>            :vartypmod -1 <br>            :varcollid 0 <br>            :varlevelsup 0 <br>            :varnosyn 1 <br>            :varattnosyn 1 <br>            :location 7<br>            }<br>         :resno 1 <br>         :resname id <br>         :ressortgroupref 0 <br>         :resorigtbl 16389 <br>         :resorigcol 1 <br>         :resjunk false<br>         }<br>      )<br>      :scan.plan.qual (<br>         {OPEXPR <br>         :opno 521 <br>         :opfuncid 147 <br>         :opresulttype 16 <br>         :opretset false <br>         :opcollid 0 <br>         :inputcollid 0 <br>         :args (<br>            {VAR <br>            :varno 1 <br>            :varattno 1 <br>            :vartype 23 <br>            :vartypmod -1 <br>            :varcollid 0 <br>            :varlevelsup 0 <br>            :varnosyn 1 <br>            :varattnosyn 1 <br>            :location 22<br>            }<br>            {CONST <br>            :consttype 23 <br>            :consttypmod -1 <br>            :constcollid 0 <br>            :constlen 4 <br>            :constbyval true <br>            :constisnull false <br>            :location 27 <br>            :constvalue 4 [ 1 0 0 0 0 0 0 0 ]<br>            }<br>         )<br>         :location 25<br>         }<br>         {OPEXPR <br>         :opno 97 <br>         :opfuncid 66 <br>         :opresulttype 16 <br>         :opretset false <br>         :opcollid 0 <br>         :inputcollid 0 <br>         :args (<br>            {VAR <br>            :varno 1 <br>            :varattno 1 <br>            :vartype 23 <br>            :vartypmod -1 <br>            :varcollid 0 <br>            :varlevelsup 0 <br>            :varnosyn 1 <br>            :varattnosyn 1 <br>            :location 33<br>            }<br>            {CONST <br>            :consttype 23 <br>            :consttypmod -1 <br>            :constcollid 0 <br>            :constlen 4 <br>            :constbyval true <br>            :constisnull false <br>            :location 38 <br>            :constvalue 4 [ 10 0 0 0 0 0 0 0 ]<br>            }<br>         )<br>         :location 36<br>         }<br>      )<br>      :scan.plan.lefttree &lt;&gt; <br>      :scan.plan.righttree &lt;&gt; <br>      :scan.plan.initPlan &lt;&gt; <br>      :scan.plan.extParam (b)<br>      :scan.plan.allParam (b)<br>      :scan.scanrelid 1<br>      }<br>   :rtable (<br>      {RANGETBLENTRY <br>      :alias &lt;&gt; <br>      :eref <br>         {ALIAS <br>         :aliasname t <br>         :colnames (&quot;id&quot;)<br>         }<br>      :rtekind 0 <br>      :relid 16389 <br>      :relkind r <br>      :rellockmode 1 <br>      :tablesample &lt;&gt; <br>      :lateral false <br>      :inh false <br>      :inFromCl true <br>      :requiredPerms 2 <br>      :checkAsUser 0 <br>      :selectedCols (b 8)<br>      :insertedCols (b)<br>      :updatedCols (b)<br>      :extraUpdatedCols (b)<br>      :securityQuals &lt;&gt;<br>      }<br>   )<br>   :resultRelations &lt;&gt; <br>   :appendRelations &lt;&gt; <br>   :subplans &lt;&gt; <br>   :rewindPlanIDs (b)<br>   :rowMarks &lt;&gt; <br>   :relationOids (o 16389)<br>   :invalItems &lt;&gt; <br>   :paramExecTypes &lt;&gt; <br>   :utilityStmt &lt;&gt; <br>   :stmt_location 0 <br>   :stmt_len 40<br>   }<br>)</pre><p>Notice type PLANNEDSTMT. Lot’s of interesting stuff is happening here. We can revisit it later. After few steps forward, we reach portal creation.</p><pre>/*<br> * Create unnamed portal to run the query or queries in. If there<br> * already is one, silently drop it.<br> */<br>portal = CreatePortal(&quot;&quot;, true, true);</pre><p>followed by <em>PortalStart(portal, NULL, 0, InvalidSnapshot)</em></p><blockquote>Prepare a portal for execution.</blockquote><p>Still preparations! Let’s check what’s going on here (press s). <em>PortalStart</em> is defined in src/backend/tcop/pquery.c. Let’s keep stepping through</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*lNwJSdgHIeEOPsK1D3htxg.png" /></figure><p>QueryDesc gets created: <em>queryDesc = CreateQueryDesc(…). </em>This is defined in same file, i.e. src/backend/tcop/pquery.c</p><pre>/*<br> * CreateQueryDesc<br> */<br>QueryDesc *<br>CreateQueryDesc(PlannedStmt *plannedstmt,<br>    const char *sourceText,<br>    Snapshot snapshot,<br>    Snapshot crosscheck_snapshot,<br>    DestReceiver *dest,<br>    ParamListInfo params,<br>    QueryEnvironment *queryEnv,<br>    int instrument_options)<br>{<br> QueryDesc  *qd = (QueryDesc *) palloc(sizeof(QueryDesc));</pre><pre>qd-&gt;operation = plannedstmt-&gt;commandType; /* operation */<br> qd-&gt;plannedstmt = plannedstmt; /* plan */<br> qd-&gt;sourceText = sourceText; /* query text */<br> qd-&gt;snapshot = RegisterSnapshot(snapshot); /* snapshot */<br> /* RI check snapshot */<br> qd-&gt;crosscheck_snapshot = RegisterSnapshot(crosscheck_snapshot);<br> qd-&gt;dest = dest;   /* output dest */<br> qd-&gt;params = params;  /* parameter values passed into query */<br> qd-&gt;queryEnv = queryEnv;<br> qd-&gt;instrument_options = instrument_options; /* instrumentation wanted? */</pre><pre>/* null these fields until set by ExecutorStart */<br> qd-&gt;tupDesc = NULL;<br> qd-&gt;estate = NULL;<br> qd-&gt;planstate = NULL;<br> qd-&gt;totaltime = NULL;</pre><pre>/* not yet executed */<br> qd-&gt;already_executed = false;</pre><pre>return qd;<br>}</pre><p>Finally we reach <em>ExecutorStart(queryDesc, myeflags). </em>ExecutorStart is defined in src/backend/executor/execMain.c. Enter into ExecutorStart, at some point: <em>queryDesc-&gt;estate = estate</em></p><p>where estate is an EState object</p><blockquote>/* — — — — — — — — <br> * CreateExecutorState<br> *<br> * Create and initialize an EState node, which is the root of<br> * working storage for an entire Executor invocation.<br> *<br> * Principally, this creates the per-query memory context that will be<br> * used to hold all working data that lives till the end of the query.<br> * Note that the per-query context will become a child of the caller’s<br> * CurrentMemoryContext.<br> * — — — — — — — — <br> */</blockquote><p>After some stepping through, we reach InitPlan. InitPlan is defined in src/backend/executor/execMain.c</p><blockquote>/* — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br> * InitPlan<br> *<br> * Initializes the query plan: open files, allocate storage<br> * and start up the rule manager<br> * — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br> */</blockquote><p>Opens file huh, let’s see. Step into initPlan. Stepping through we reach ExecInitNode defined in src/backend/executor/execProcnode.c.</p><blockquote>/* — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br> * ExecInitNode<br> *<br> * Recursively initializes all the nodes in the plan tree rooted<br> * at ‘node’.<br> *<br> * Inputs:<br> * ‘node’ is the current node of the plan produced by the query planner<br> * ‘estate’ is the shared execution state for the plan tree<br> * ‘eflags’ is a bitwise OR of flag bits described in executor.h<br> *<br> * Returns a PlanState node corresponding to the given Plan node.<br> * — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br> */</blockquote><p><em>ExecInitNode</em> takes node as param, let’s see how it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*TbvWdF8GgLBVfGIlH7cH4A.png" /></figure><pre>{SEQSCAN <br>   :scan.plan.startup_cost 0 <br>   :scan.plan.total_cost 48.25 <br>   :scan.plan.plan_rows 13 <br>   :scan.plan.plan_width 4 <br>   :scan.plan.parallel_aware false <br>   :scan.plan.parallel_safe true <br>   :scan.plan.async_capable false <br>   :scan.plan.plan_node_id 0 <br>   :scan.plan.targetlist (<br>      {TARGETENTRY <br>      :expr <br>         {VAR <br>         :varno 1 <br>         :varattno 1 <br>         :vartype 23 <br>         :vartypmod -1 <br>         :varcollid 0 <br>         :varlevelsup 0 <br>         :varnosyn 1 <br>         :varattnosyn 1 <br>         :location 7<br>         }<br>      :resno 1 <br>      :resname id <br>      :ressortgroupref 0 <br>      :resorigtbl 16389 <br>      :resorigcol 1 <br>      :resjunk false<br>      }<br>   )<br>   :scan.plan.qual (<br>      {OPEXPR <br>      :opno 521 <br>      :opfuncid 147 <br>      :opresulttype 16 <br>      :opretset false <br>      :opcollid 0 <br>      :inputcollid 0 <br>      :args (<br>         {VAR <br>         :varno 1 <br>         :varattno 1 <br>         :vartype 23 <br>         :vartypmod -1 <br>         :varcollid 0 <br>         :varlevelsup 0 <br>         :varnosyn 1 <br>         :varattnosyn 1 <br>         :location 22<br>         }<br>         {CONST <br>         :consttype 23 <br>         :consttypmod -1 <br>         :constcollid 0 <br>         :constlen 4 <br>         :constbyval true <br>         :constisnull false <br>         :location 27 <br>         :constvalue 4 [ 1 0 0 0 0 0 0 0 ]<br>         }<br>      )<br>      :location 25<br>      }<br>      {OPEXPR <br>      :opno 97 <br>      :opfuncid 66 <br>      :opresulttype 16 <br>      :opretset false <br>      :opcollid 0 <br>      :inputcollid 0 <br>      :args (<br>         {VAR <br>         :varno 1 <br>         :varattno 1 <br>         :vartype 23 <br>         :vartypmod -1 <br>         :varcollid 0 <br>         :varlevelsup 0 <br>         :varnosyn 1 <br>         :varattnosyn 1 <br>         :location 33<br>         }<br>         {CONST <br>         :consttype 23 <br>         :consttypmod -1 <br>         :constcollid 0 <br>         :constlen 4 <br>         :constbyval true <br>         :constisnull false <br>         :location 38 <br>         :constvalue 4 [ 10 0 0 0 0 0 0 0 ]<br>         }<br>      )<br>      :location 36<br>      }<br>   )<br>   :scan.plan.lefttree &lt;&gt; <br>   :scan.plan.righttree &lt;&gt; <br>   :scan.plan.initPlan &lt;&gt; <br>   :scan.plan.extParam (b)<br>   :scan.plan.allParam (b)<br>   :scan.scanrelid 1<br>   }</pre><p>Here we can see that the node type is SEQSCAN. In the current function (<em>ExecInitNode</em>), we can find giant switch which computes the result.</p><pre>switch (nodeTag(node))<br> {<br>   /*<br>    * control nodes<br>    */<br>  case T_Result:<br>   result = (PlanState *) ExecInitResult((Result *) node,<br>              estate, eflags);<br>   break;<br>...</pre><p>We quickly jump into <em>ExecInitSeqScan</em> for our node SEQSCAN. Step inside <em>ExecInitSeqScan</em> (defined in src/backend/executor/nodeSeqscan.c).</p><p>Step through, until we reach <em>ExecOpenScanRelation</em>(defined in src/backend/executor/execUtils.c), step into this and then into <em>ExecGetRangeTableRelation</em>. Keep stepping until you reach</p><p><em>rel = table_open(rte-&gt;relid, NoLock)</em></p><p><em>table_open </em>is defined in src/backend/access/table/table.c.</p><blockquote>/* — — — — — — — — <br> * table_open — open a table relation by relation OID<br> *<br> * This is essentially relation_open plus check that the relation<br> * is not an index nor a composite type. (The caller should also<br> * check that it’s not a view or foreign table before assuming it has<br> * storage.)<br> * — — — — — — — — <br> */</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*Y5BO7oTRLuC0gJ3_a0tnnA.png" /><figcaption>relationId is useful later</figcaption></figure><p>This calls <em>relation_open</em>, step inside this function.</p><p><em>relation_open </em>is defined in src/backend/access/common/relation.c (don’t get confused with another relation.c defined in different path).</p><p><em>relation_open </em>first take a lock:</p><pre>/* Get the lock before trying to open the relcache entry */<br> if (lockmode != NoLock)<br>  LockRelationOid(relationId, lockmode);</pre><pre>/* The relcache does all the real work... */<br>r = RelationIdGetRelation(relationId);</pre><p>and then do real work. Let’s see what <em>RelationIdGetRelation</em> does, step into this function. <em>RelationIdGetRelation </em>is defined in src/backend/utils/cache/relcache.c.</p><blockquote>/*<br> * RelationIdGetRelation<br> *<br> * Lookup a reldesc by OID; make one if not already in cache.<br> *<br> * Returns NULL if no pg_class row could be found for the given relid<br> * (suggesting we are trying to access a just-deleted relation).<br> * Any other error is reported via elog.<br> *<br> * NB: caller should already have at least AccessShareLock on the<br> * relation ID, else there are nasty race conditions.<br> *<br> * NB: relation ref count is incremented, or set to 1 if new entry.<br> * Caller should eventually decrement count. (Usually,<br> * that happens by calling RelationClose().)<br> */</blockquote><p>Lot’s of things are happened here. Let’s keep stepping until we return from <em>ExecInitSeqScan </em>and watch how things unfolds<em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kRwpc8yi2usEfsu-jtZuzQ.png" /></figure><p>Post some more initialization,<em> scanstate-&gt;ss</em> looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZcqmMwmNJV5vws4Epr_lDA.png" /></figure><p>where <em>ss</em> is scan state defined in src/include/nodes/execnodes.h</p><blockquote>/* — — — — — — — — <br> * ScanState information<br> *<br> * ScanState extends PlanState for node types that represent<br> * scans of an underlying relation. It can also be used for nodes<br> * that scan the output of an underlying plan node — — in that case,<br> * only ScanTupleSlot is actually useful, and it refers to the tuple<br> * retrieved from the subplan.<br> *<br> * currentRelation relation being scanned (NULL if none)<br> * currentScanDesc current scan descriptor for scan (NULL if none)<br> * ScanTupleSlot pointer to slot in tuple table holding scan tuple<br> * — — — — — — — — <br> */<br>typedef struct ScanState<br>{<br> PlanState ps; /* its first field is NodeTag */<br> Relation ss_currentRelation;<br> struct TableScanDescData *ss_currentScanDesc;<br> TupleTableSlot *ss_ScanTupleSlot;<br>} ScanState;</blockquote><p>Let’s keep stepping until we return out of <em>InitPlan</em>, quite a detour ain’t it?</p><p>Moving out of <em>standard_ExecutorStart</em> and then <em>PortalStart</em>, we are back in pquery.c file. All of the above happened to a create query plan.</p><blockquote>/*<br> * Call ExecutorStart to prepare the plan for execution<br> */</blockquote><p>Quick dump of all information at this point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*diDcxUavAZ94GTKqHnzWBw.png" /><figcaption>PlannedStmt</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mHyJDMIReUMkk38UpICmYw.png" /></figure><p>Also, <em>tupleDescriptor</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kRGrmZcvttQXPkcZiAq82g.png" /></figure><p>Notice <em>attname(char*) </em>where data is id (our column name).</p><p>Stepping over, system prepares output stream (here to <em>DestRemote</em>, our psql client).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DYCJGE7kFvY6wALkit5rMg.png" /></figure><p>Let’s step into <em>PortalRun </em>(defined in src/backend/tcop/pquery.c).</p><blockquote>Run a portal’s query or queries.</blockquote><p>Keep stepping until you reach: <em>nprocessed = PortalRunSelect(portal, true, count, dest)</em></p><p>Step into <em>PortalRunSelect</em> and then ExecutorRun (defined in src/backend/executor/execMain.c).</p><blockquote>/* — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br> * ExecutorRun<br> *<br> * This is the main routine of the executor module. It accepts<br> * the query descriptor from the traffic cop and executes the<br> * query plan.<br> *<br> * ExecutorStart must have been called already.<br> *<br> * If direction is NoMovementScanDirection then nothing is done<br> * except to start up/shut down the destination. Otherwise,<br> * we retrieve up to ‘count’ tuples in the specified direction.<br> *<br> * Note: count = 0 is interpreted as no portal limit, i.e., run to<br> * completion. Also note that the count limit is only applied to<br> * retrieved tuples, not for instance to those inserted/updated/deleted<br> * by a ModifyTable plan node.<br> *<br> * There is no return value, but output tuples (if any) are sent to<br> * the destination receiver specified in the QueryDesc; and the number<br> * of tuples processed at the top level can be found in<br> * estate-&gt;es_processed.<br> *<br> * We provide a function hook variable that lets loadable plugins<br> * get control when ExecutorRun is called. Such a plugin would<br> * normally call standard_ExecutorRun().<br> *<br> * — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br> */</blockquote><p>Alright, this is main executor which fetches tuples and output to dest receiver. Actual implementation is in <em>standard_ExecutorRun</em>.</p><p>Step into <em>ExecutePlan</em> (defined in same file).</p><blockquote>/* — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br> * ExecutePlan<br> *<br> * Processes the query plan until we have retrieved ‘numberTuples’ tuples,<br> * moving in the specified direction.<br> *<br> * Runs to completion if numberTuples is 0<br> *<br> * Note: the ctid attribute is a ‘junk’ attribute that is removed before the<br> * user can see it<br> * — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br> */</blockquote><p>Infinite loop to process tuples.</p><pre>/*<br>  * Loop until we&#39;ve processed the proper number of tuples from the plan.<br>  */<br> for (;;)<br> {<br><br>   * Execute the plan and obtain a tuple<br>   */<br>  slot = ExecProcNode(planstate);</pre><pre>/*<br>   * if the tuple is null, then we assume there is nothing more to<br>   * process so we just end the loop...<br>   */<br>  if (TupIsNull(slot))<br>   break;</pre><pre>&lt;snip&gt; <br>  if (sendTuples)<br>  {<br>   /*<br>    * If we are not able to send the tuple, we assume the  destination<br>    * has closed and no more tuples can be sent. If that&#39;s the case,<br>    * end the loop.<br>    */<br>   if (!dest-&gt;receiveSlot(slot, dest))<br>    break;<br>  }</pre><p><em>ExecProcNode</em> (defind in src/include/executor/executor.h) calls <em>ExecProcNode</em> of corresponding node.</p><pre>/* ----------------------------------------------------------------<br> *  ExecProcNode<br> *<br> *  Execute the given node to return a(nother) tuple.<br> * ----------------------------------------------------------------<br> */<br>#ifndef FRONTEND<br>static inline TupleTableSlot *<br>ExecProcNode(PlanState *node)<br>{<br> if (node-&gt;chgParam != NULL) /* something changed? */<br>  ExecReScan(node);  /* let ReScan handle this */</pre><pre>return node-&gt;ExecProcNode(node);<br>}<br>#endif</pre><p>In current case, <em>ExecProcNodeFirst</em> (defined in src/backend/executor/execProcnode.c), gets called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cv5T-FPEu9TIPaWe1Ojkqg.png" /></figure><p>which in turns sets <em>node-&gt;ExecProcNode = node-&gt;ExecProcNodeReal.</em></p><p>In current case,<em> node-&gt;ExecProcNode</em> is <em>ExecSeqScan </em>(defined in src/backend/executor/nodeSeqscan.c).</p><p>ExecSeqScan:</p><blockquote>/* — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br> * ExecSeqScan(node)<br> *<br> * Scans the relation sequentially and returns the next qualifying<br> * tuple.<br> * We call the ExecScan() routine and pass it the appropriate<br> * access method functions.<br> * — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br> */</blockquote><p><em>ExecSeqScan </em>calls <em>ExecScan</em> (defined in src/backend/executor/execScan.c), don’t forget to step in. Step into ExecScanFetch(defined in src/backend/executor/execScan.c, same file) which pulls in a slot</p><pre>slot = ExecScanFetch(node, accessMtd, recheckMtd);</pre><p>Keep stepping and step in when you reach <em>table_beginscan</em> (defined in src/backend/access/heap/heapam.c). Here, <em>scandesc</em> gets populated. Step over and step into next function <em>table_scan_getnextslot </em>(defined in<em> </em>src/include/access/tableam.h), step into <em>scan_getnextslot</em> in same function.</p><p><em>scan_getnextslot </em>points to <em>heap_getnextslot</em>(defined in src/backend/access/heap/heapam.c) which calls <em>heapgettup_pagemode </em>(step into this function)<em>.</em></p><blockquote>heapgettup_pagemode — fetch next heap tuple in page-at-a-time mode</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KsCgc1R5BjrlfYCACdbIBw.png" /></figure><p>As you can see, we are at the first page.</p><p>We get into <em>heapgetpage</em> (in same file), which calls <em>ReadBufferExtended</em> (defined in src/backend/storage/buffer/bufmgr.c).</p><blockquote>ReadBufferExtended — returns a buffer containing the requested<br> block of the requested relation.</blockquote><p>which calls <em>ReadBuffer_common</em> and in turn calls <em>BufferAlloc.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*INHFsrAmwQWkY7TWdtltHw.png" /><figcaption>Traceback just in case you get lost</figcaption></figure><blockquote>/*<br> * BufferAlloc — subroutine for ReadBuffer. Handles lookup of a shared<br> * buffer. If no buffer exists already, selects a replacement<br> * victim and evicts the old page, but does NOT read in new page.<br> *<br> * “strategy” can be a buffer replacement strategy object, or NULL for<br> * the default strategy. The selected buffer’s usage_count is advanced when<br> * using the default strategy, but otherwise possibly not (see PinBuffer).<br> *<br> * The returned buffer is pinned and is already marked as holding the<br> * desired page. If it already did have the desired page, *foundPtr is<br> * set true. Otherwise, *foundPtr is set false and the buffer is marked<br> * as IO_IN_PROGRESS; ReadBuffer will now need to do I/O to fill it.<br> *<br> * *foundPtr is actually redundant with the buffer’s BM_VALID flag, but<br> * we keep it for simplicity in ReadBuffer.<br> *<br> * No locks are held either at entry or exit.<br> */</blockquote><p>Beautiful!</p><pre>/* create a tag so we can lookup the buffer */<br> InitBufferTag(&amp;newTag, &amp;smgr-&gt;smgr_rlocator.locator, forkNum, blockNum);</pre><pre>/* determine its hash code and partition lock ID */<br> newHash = BufTableHashCode(&amp;newTag);<br> newPartitionLock = BufMappingPartitionLock(newHash);</pre><pre>/* see if the block is in the buffer pool already */<br> LWLockAcquire(newPartitionLock, LW_SHARED);<br>buf_id = BufTableLookup(&amp;newTag, newHash);</pre><p><strong><em>First it tries to find page in buffer, if it is not found then some other page gets evicted and required page is loaded from the disk into buffer.</em></strong></p><pre>/*<br>  * Didn&#39;t find it in the buffer pool.  We&#39;ll have to initialize a new<br>  * buffer.  Remember to unlock the mapping lock while doing the work.<br>  */<br> LWLockRelease(newPartitionLock);</pre><pre>/* Loop here in case we have to try another victim buffer */<br> for (;;)<br> {<br>  /*<br>   * Ensure, while the spinlock&#39;s not yet held, that there&#39;s a free<br>   * refcount entry.<br>   */<br>  ReservePrivateRefCountEntry();</pre><pre>/*<br>   * Select a victim buffer.  The buffer is returned with its header<br>   * spinlock still held!<br>   */<br>  buf = StrategyGetBuffer(strategy, &amp;buf_state);</pre><pre>Assert(BUF_STATE_GET_REFCOUNT(buf_state) == 0);</pre><pre>/* Must copy buffer flags while we still hold the spinlock */<br>  oldFlags = buf_state &amp; BUF_FLAG_MASK;</pre><pre>/* Pin the buffer and then release the buffer spinlock */<br>  PinBuffer_Locked(buf);<br>&lt;snip&gt;</pre><p>Let’s see what happens in our case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*ikEa_NNYeO2QUpv7KkXMFA.png" /><figcaption>Page was found in buffer itself</figcaption></figure><p>Buf gets returned and back in <em>heapgetpage</em>, we reach at: <em>dp = BufferGetPage(buffer)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*evq-EYZrCeBlpyUFPB6dHA.png" /><figcaption>Buffer is 191</figcaption></figure><p>Let’s see how we get page from the buffer, step into <em>BufferGetPage</em> (defined in src/include/storage/bufmgr.h) which calls <em>BufferGetBlock</em>.</p><pre>/*<br> * BufferGetBlock<br> *  Returns a reference to a disk page image associated with a buffer.<br> *<br> * Note:<br> *  Assumes buffer is valid.<br> */<br>static inline Block<br>BufferGetBlock(Buffer buffer)<br>{<br> Assert(BufferIsValid(buffer));</pre><pre>if (BufferIsLocal(buffer))<br>  return LocalBufferBlockPointers[-buffer - 1];<br> else<br>  return (Block) (BufferBlocks + ((Size) (buffer - 1)) * BLCKSZ);<br>}</pre><p>where <em>BLCKSZ </em>is blocksize (defined in src/include/pg_config.h)</p><pre>/* Size of a disk block --- this also limits the size of a tuple. You can set it bigger if you need bigger tuples (although TOAST should reduce the need to have large tuples, since fields can be spread across multiple tuples).<br>BLCKSZ must be a power of 2. The maximum possible value of BLCKSZ is currently 2^15 (32768). This is determined by the 15-bit widths of the lp_off and lp_len fields in ItemIdData (see include/storage/itemid.h). Changing BLCKSZ requires an initdb. */<br>#define BLCKSZ 8192</pre><p>Let’s continue with <em>getpageitem</em>, after stepping through, we reach the line given below, step into this:</p><pre>loctup.t_data = (HeapTupleHeader) PageGetItem((Page) dp, lpp);</pre><p>where <em>PageGetItem</em> (defined in src/include/storage/bufpage.h) looks like:</p><pre>/*<br> * PageGetItem<br> *  Retrieves an item on the given page.<br> *<br> * Note:<br> *  This does not change the status of any of the resources passed.<br> *  The semantics may change in the future.<br> */<br>static inline Item<br>PageGetItem(Page page, ItemId itemId)<br>{<br> Assert(page);<br> Assert(ItemIdHasStorage(itemId));</pre><pre>return (Item) (((char *) page) + ItemIdGetOffset(itemId));<br>}</pre><p>Notice <em>loctup.t_data</em> is of type <em>HeapTupleHeader</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aDc9GOuOS7s6ChqD7SknFw.png" /><figcaption>Tuple header looks like this</figcaption></figure><p>Now, we return back to our main function <em>heapgettup_pagemode.</em></p><pre>/*<br>  * advance the scan until we find a qualifying tuple or run out of stuff to scan<br>  */<br> for (;;)<br> {<br>&lt;snip&gt;</pre><p>You can see through rest of the code or keep stepping out/exit. In the end, we see slot is sent to our remote destination. <em>set_ps_display(“idle”)</em> gets called which changes query status from active to idle. Result can now be seen in psql.</p><h3>Conclusion</h3><p>I was surprised to see how easy it is to walk through Postgres codebase while stepping through postgres (while it executes a query), and this article hopes that it makes this process even more easier. Once you step through for few queries (say joins, recursive CTE etc.), lot more insights can be gained.</p><p><strong>Reference/resources</strong></p><ol><li>Postgres setup: <a href="https://www.postgresql.org/docs/9.6/install-procedure.html">https://www.postgresql.org/docs/9.6/install-procedure.html</a></li><li>Postgres gdb: <a href="https://wiki.postgresql.org/wiki/Developer_FAQ#gdb">https://wiki.postgresql.org/wiki/Developer_FAQ#gdb</a></li></ol><p><em>Note: Please feel free to add your comment/suggestion/any correction.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f40990685a56" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/stepping-through-postgresql-f40990685a56">Stepping through PostgreSQL</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upgrading PostgreSQL version without downtime with Slony-I]]></title>
            <link>https://tech.mammoth.io/upgrading-postgresql-version-without-downtime-with-slony-1-3c701a791411?source=rss-285c7ae18b08------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c701a791411</guid>
            <category><![CDATA[slony]]></category>
            <category><![CDATA[replication]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Ankit K Pandey]]></dc:creator>
            <pubDate>Thu, 21 Jul 2022 15:38:59 GMT</pubDate>
            <atom:updated>2022-09-12T06:32:19.357Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/140/1*1NjOf5AHJaflHwb-u2ipDg.jpeg" /></figure><p>Upgrading Postgres via inbuilt mechanism <em>pg_upgrade </em>is bit of pain as it requires unknown amount of downtime. Also, if things goes wrong during upgrade process, roll back takes some time as well. This is not much of problem for a Postgres cluster storing customer data as there could be a scheduled maintenance window which can be intimated to the affected group of users. But this doesn’t apply to Postgres storing metadata like login, workspaces details and so on as this cluster needs to be up all time otherwise whole application will have to go down (way to go for SLA).</p><p>One of the most popular solution for this problem is replicating Postgres cluster where master server is running on older version of Postgres (say 9.6) and slave running on newer version of Postgres (say 14) and switching backend from master to slave, hence an upgrade. This can be done using <a href="https://www.slony.info/">Slony-I</a> . This article gives overview related to installation, configuration and running of replicas via Slony-I.</p><p>Naming convention:</p><ol><li>Master: Cluster running old version of Postgres</li><li>Slave: Cluster running new version of Postgres</li></ol><h3><strong>Installation:</strong></h3><p><strong>Postgres</strong></p><ol><li>Install a new (desired) version of Postgres on slave machine.</li><li>Configure Slave Postgres cluster to work in same manner as how it configured for in master cluster. This might involve configuring postgresql.conf and pg_hba.conf. At very minimum, it should allow network access between master and slave machine. For sanity, check if you can access slave from master instance or vice versa.</li><li>Create a superuser role (let’s call it REPLICATIONUSER) and a database (which needs replication) on slave machine.</li><li>Create tables which needs to be replicated on slave machine. You can take <a href="https://www.postgresql.org/docs/current/app-pgdump.html">pg_dump </a>-s from master cluster and restore it on slave machine or any way as suitable. Ensure this role is same as #3 (note: once upgrade is done you can remove super user attribute from the role)</li></ol><p>Sample table: test_table (in database testdb as user testuser) created on both master and slave clusters</p><pre>CREATE TABLE test_table (</pre><pre>id SERIAL primary key,</pre><pre>name varchar(40),</pre><pre>modtime timestamp DEFAULT current_timestamp</pre><pre>);</pre><ol><li>At this stage, you should be having two clusters running with an <em>identical </em>role, database and table.</li></ol><p><strong>Slony-I</strong></p><ol><li>You need to build Slony-I from the source for each Postgres cluster. Always pick latest one from <em>Slony-I Quick downloads </em>section from Slony’s website (at time of writing ver 2.2.10 worked fine). I tried other version but none of them worked (failed during compilation or gave missing c function errors).</li><li>Grab Slony from official website, eg: <em>wget </em><a href="http://main.slony.info/downloads/2.2/source/slony1-2.2.10.tar.bz2"><em>http://main.slony.info/downloads/2.2/source/slony1-2.2.10.tar.bz2</em></a></li><li>Install dependencies on both clusters, for Ubuntu/Debian based system, it will be as follows:</li></ol><p>Master:</p><pre><em>sudo apt install postgresql-server-dev-9.6 libpq-dev</em></pre><p>Slave:</p><pre><em>sudo apt install postgresql-server-dev-14 libpq-dev</em></pre><p>Change version of postgresql-server-dev-XX to required version of Postgres (XX).</p><p>4. Extract source tarball and ensure it is owned by postgres user i.e. <em>sudo chown postgres:postgres -R slony1–2.2.10</em></p><p>5. Change user to postgres and run the build, it involves running <em>./configure</em> and <em>make. </em>Switch back to normal user and run <em>sudo make install. </em>Basically configuring and compiling is done as postgres user and installation of files as root.</p><p>All above steps needs to be performed on both master and slave clusters.</p><h3>Configuration</h3><p>Configuration is two step process:</p><p>Note: Ensure config files are created as user <em>postgres</em></p><ol><li>Create cluster (Slony terminology for master-slave combination), create a set (set of tables to be replicated) and nodes (Postgres clusters).</li><li>Create a file (say <em>store</em>) as following:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29bfbacdac0e124d4021cc4602bfe99f/href">https://medium.com/media/29bfbacdac0e124d4021cc4602bfe99f/href</a></iframe><p>where cluster name can be any valid pg compatible name (and no spaces), node 1 and node 2 contains master and slave connection info, you can add ports and other details as needed (notice single quotes). Init cluster, initializes the replica clusters. Create set creates a set which contains list of table to be replicated. Refer reference-&gt; Slonik section in Slony-I docs for more commands and details. Sequences are needed to be entered as well (otherwise primary key won’t be in sync). For sequence, I usually do</p><pre>psql -d testdb -c &quot;SELECT sequence_name FROM information_schema.sequences where sequence_schema=&#39;public&#39;;&quot; &gt; /tmp/seq</pre><p>and then read each line (via a script) from generated file and dump out corresponding add sequence line. Same applies for populating tables as well.</p><p>Finally store node/path maps connection strings again.</p><p>3. Above file would just create clusters and create some namespace and store procedures, actual replication happens only when the slave is <em>subscribed</em> to the master. Create a file (say <em>replicate</em>) as following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/010ac0977f51b1dd5443afecf9772b3c/href">https://medium.com/media/010ac0977f51b1dd5443afecf9772b3c/href</a></iframe><p>Cluster name is same as name defined in the file <em>store. </em>Here, we map master to slave in <em>subscribe set</em> command. Notice that master is mentioned as provider (with corresponding node id) and slave as receiver. This can easily extend to multiple replicas by just adding more nodes and mapping entries here.</p><h3>Spinning up replica</h3><p>In above step (configuration), we have created a couple of files, now we will bring these files into the action, enter Slonik and slon.</p><p><strong>Slonik:</strong></p><p>Quoting from doc</p><blockquote>The <a href="https://www.slony.info/documentation/2.2/slonik.html">slonik</a> command processor processes scripts in a “little language” that are used to submit events to update the configuration of a Slony-I cluster. This includes such things as adding and removing nodes, modifying communications paths, adding or removing subscriptions.</blockquote><p>Slonik reads above config files, create namespaces and procedures which maps master and slave.</p><p><strong>Slon:</strong></p><p>Docs again:</p><blockquote>For each node in the cluster, there will be a <a href="https://www.slony.info/documentation/2.2/slon.html">slon</a> process to manage replication activity for that node.</blockquote><blockquote><a href="https://www.slony.info/documentation/2.2/slon.html">slon</a> is a program implemented in C that processes replication events. There are two main sorts of events:</blockquote><blockquote>Configuration events: These normally occur when a <a href="https://www.slony.info/documentation/2.2/slonik.html">slonik</a> script is run, and submit updates to the configuration of the cluster.</blockquote><blockquote>SYNC events: Updates to the tables that are replicated are grouped together into SYNCs; these groups of transactions are applied together to the subscriber nodes.</blockquote><p>So, slon keeps eye out for any configuration changes as well as shipping of data from master to slave (sync events).</p><p>These both executables can be found at (version as applicable):</p><p>Master: /usr/lib/postgresql/9.6/bin/</p><p>Slave: /usr/lib/postgresql/14/bin/</p><p>You can keep eye out for this directory while running <em>sudo make install</em> for Slony-I.</p><p><strong>Spinning things up:</strong></p><p>Run (as postgres user) :</p><pre><em>/usr/lib/postgresql/9.6/bin/slonik store</em></pre><p>where <em>store</em> is file name of config which had commands to create and init cluster.</p><p>2. Create two connections (maybe use two screens/terminals):</p><p>Connect to the master and run slon as postgres user:</p><pre><em>/usr/lib/postgresql/9.6/bin/slon Slony_test “dbname=testdb user=testuser host=10.0.13.197”</em></pre><p>You should see some initial configuration and SYNC logs.</p><p>Connect to slave and run slon as postgres user:</p><pre><em>/usr/lib/postgresql/14/bin/slon Slony_test “dbname=testdb user=testuser host=10.0.13.16”</em></pre><p>Notice IPs and connection string.</p><p>These processes should be kept running (if you use slony for replication, it is good idea to run it as a systemd service on each clusters).</p><p>Now you will have two slon daemon running on the postgres clusters. Keep these process running in background. Open up new terminal/screen to follow rest of the process.</p><p>3. Notice at this point, if you add/delete any rows on replicated table (<em>test_table</em>) in master cluster, you won’t be able to see corresponding change in the slave cluster for the same table (as matter of fact, it should be empty).</p><p>To start replication:</p><p>Run (as postgres user):</p><pre><em>/usr/lib/postgresql/9.6/bin/slonik replicate</em></pre><p>Where <em>replica </em>is config file which contains subscribe command.</p><p>Keep eye on the slon daemon on the master and the slave clusters, they should show some logs (and hopefully no errors).</p><p>Open up slave cluster and look into replicated table (here referred as <em>test_table</em>). Insert any data into replicated table on the master cluster and observe corresponding changes pushed into the replicated table in the slave cluster.</p><p>Congratulations! You have successfully replicated Postgres cluster across different version.</p><h4>Switchover</h4><p>Time to make slave as new master, this can be done by switching origin in the replication. Once this is done, you can switch your api to point to new cluster.</p><p>Run (as postgres user):</p><pre> <em>/usr/lib/postgresql/9.6/bin/slonik switchover</em></pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5bc5e8ef67cb27b40025834166c12e2/href">https://medium.com/media/a5bc5e8ef67cb27b40025834166c12e2/href</a></iframe><h3>Conclusion</h3><p>Once you have master and slave replica running and in sync, only downtime required is the time required to change mapping (hostnames) in backend from old to new Postgres cluster which can be done by turn off APIs, changing mapping in backend, start API and backend again. This would have be a lot longer (and uncertain length of time) if you wanted to do pg_upgrade as same process would have been: turn off API, do pg_upgrade and turn on API/backend (changing hostname in backend should take a constant amount of time which pg_upgrade would have been variable and longer).</p><p>Also, once replica is running, you can do sanity check if everything is proper on upgraded Postgres before rolling out switchover.</p><p>Way forward:</p><ol><li>Try out above method in some tiny EC2 machines or some VM (use two instances).</li><li>Plan out ins and outs, read docs to get further insights.</li></ol><p>Notes:</p><ol><li>Replicated table should have a primary key. This is <strong>must</strong>. It shouldn’t be much of issue in metadata postgres clusters as things like user table, account tables etc. always have primary key.</li><li>Superuser role is only needed for initializing cluster (and storing some procedures, namespaces etc.) , rest of replication can happen with non superuser role (as per as docs). Play around roles and see what looks most suitable to you.</li></ol><p>Reference:</p><p>Slony docs: <a href="http://main.slony.info/downloads/2.2/source/slony1-2.2.10-docs.tar.bz2">http://main.slony.info/downloads/2.2/source/slony1-2.2.10-docs.tar.bz2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c701a791411" width="1" height="1" alt=""><hr><p><a href="https://tech.mammoth.io/upgrading-postgresql-version-without-downtime-with-slony-1-3c701a791411">Upgrading PostgreSQL version without downtime with Slony-I</a> was originally published in <a href="https://tech.mammoth.io/">Technology at Mammoth</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>