<?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 Lahiru Chathuranga on Medium]]></title>
        <description><![CDATA[Stories by Lahiru Chathuranga on Medium]]></description>
        <link>https://medium.com/@lahiruchathuranga-85477?source=rss-a6ce32d56b94------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*a9GRXdNgdG4UmNF5SQuKcg.jpeg</url>
            <title>Stories by Lahiru Chathuranga on Medium</title>
            <link>https://medium.com/@lahiruchathuranga-85477?source=rss-a6ce32d56b94------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:52:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lahiruchathuranga-85477/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[Adding a Budget in AWS CLI]]></title>
            <link>https://lahiruchathuranga-85477.medium.com/adding-a-budget-in-aws-cli-e8b7da77514c?source=rss-a6ce32d56b94------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8b7da77514c</guid>
            <category><![CDATA[aws-budget-with-cli]]></category>
            <category><![CDATA[aws-budgets]]></category>
            <category><![CDATA[create-aws-budget]]></category>
            <dc:creator><![CDATA[Lahiru Chathuranga]]></dc:creator>
            <pubDate>Sat, 03 Aug 2024 05:51:02 GMT</pubDate>
            <atom:updated>2024-08-03T05:51:02.519Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8wEcpEVTUaklAyFQ.png" /></figure><h3>Overview</h3><p>This guide provides step-by-step instructions to create a budget in AWS using the AWS Command Line Interface (CLI). AWS Budgets allow you to set custom cost and usage budgets and receive alerts when you exceed your thresholds.</p><h3>Prerequisites</h3><ul><li>AWS CLI installed and configured with the appropriate permissions.</li><li>AWS account with the necessary IAM permissions to create budgets.</li></ul><h3>Step-by-Step Instructions</h3><h4>1. Install and Configure AWS CLI</h4><p>If you haven’t already installed and configured the AWS CLI, follow these steps:</p><h4>Install AWS CLI</h4><p>Download and install the AWS CLI from the official AWS CLI documentation.</p><p><a href="https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html">Install or update to the latest version of the AWS CLI — AWS Command Line Interface</a></p><h4>Configure AWS CLI</h4><p>Run the following command to configure your AWS CLI with your access and secret keys:</p><pre>aws configure</pre><p><strong>You will be prompted to enter your:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*bGivseeX_XFBWTc67mEJYQ.png" /></figure><ul><li>AWS Access Key ID: ( Your unique access key ID. )</li><li>AWS Secret Access Key: ( Your secret access key associated with the access key ID. )</li><li>Default region name: ( The AWS region you want to use by default (e.g., us-east-1). )</li><li>Default output format: ( The format in which you want the CLI to return your output (e.g., json, text, table).</li></ul><h3>Steps to Retrieve AWS Access Key ID and Secret Access Key</h3><ol><li>Sign In to AWS Management Console</li><li>Navigate to IAM Management Console</li><li>Select User</li><li>Create a New Access Key</li><li><em>In the user details page, click on the </em><strong><em>Security credentials</em></strong><em> tab.</em></li><li><em>Scroll down to the </em><strong><em>Access keys</em></strong><em> section.</em></li><li><em>Click the </em><strong><em>Create access key</em></strong><em> button.</em></li><li>Download Access Key ID and Secret Access Key</li></ol><h4>2. Create Budget</h4><p>First you need to create json files to store budget data. And then you can grab data for these files from <a href="https://docs.aws.amazon.com/cli/latest/reference/budgets/create-budget.html">aws budget documentation</a>.</p><p>Create budget.json</p><pre>{<br>    &quot;BudgetLimit&quot;: {<br>        &quot;Amount&quot;: &quot;100&quot;,<br>        &quot;Unit&quot;: &quot;USD&quot;<br>    },<br>    &quot;BudgetName&quot;: &quot;Example Tag Budget&quot;,<br>    &quot;BudgetType&quot;: &quot;COST&quot;,<br>    &quot;CostFilters&quot;: {<br>        &quot;TagKeyValue&quot;: [<br>            &quot;user:Key$value1&quot;,<br>            &quot;user:Key$value2&quot;<br>        ]<br>    },<br>    &quot;CostTypes&quot;: {<br>        &quot;IncludeCredit&quot;: true,<br>        &quot;IncludeDiscount&quot;: true,<br>        &quot;IncludeOtherSubscription&quot;: true,<br>        &quot;IncludeRecurring&quot;: true,<br>        &quot;IncludeRefund&quot;: true,<br>        &quot;IncludeSubscription&quot;: true,<br>        &quot;IncludeSupport&quot;: true,<br>        &quot;IncludeTax&quot;: true,<br>        &quot;IncludeUpfront&quot;: true,<br>        &quot;UseBlended&quot;: false<br>    },<br>    &quot;TimePeriod&quot;: {<br>        &quot;Start&quot;: 1477958399,<br>        &quot;End&quot;: 3706473600<br>    },<br>    &quot;TimeUnit&quot;: &quot;MONTHLY&quot;<br>}<br></pre><p>Create notifications-with-subscribers.json</p><pre>[<br>    {<br>        &quot;Notification&quot;: {<br>            &quot;ComparisonOperator&quot;: &quot;GREATER_THAN&quot;,<br>            &quot;NotificationType&quot;: &quot;ACTUAL&quot;,<br>            &quot;Threshold&quot;: 80,<br>            &quot;ThresholdType&quot;: &quot;PERCENTAGE&quot;<br>        },<br>        &quot;Subscribers&quot;: [<br>            {<br>                &quot;Address&quot;: &quot;example@example.com&quot;,<br>                &quot;SubscriptionType&quot;: &quot;EMAIL&quot;<br>            }<br>        ]<br>    }<br>]</pre><p>Run the following command to create a budget.</p><pre>aws budgets create-budget \<br>    --account-id 111122223333 \<br>    --budget file://budget.json \<br>    --notifications-with-subscribers file://notifications-with-subscribers.json</pre><p>Here</p><ul><li>--account-id</li></ul><p>Can grab</p><ol><li>Sign in to the AWS Management Console, click on your account name or avatar, select “My Account” from the dropdown menu, and your Account ID will be displayed at the top under Account Settings.</li><li>Run following command</li></ol><pre>aws sts get-caller-identity --query Account --output text</pre><h4>3. Verify the budget in AWS Management Console.</h4><ul><li><strong>Sign in to the AWS Management Console</strong>:</li><li><strong>Navigate to AWS Budgets</strong>:</li><li><strong>View Your Budgets</strong>:</li></ul><h3>Thank you …</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8b7da77514c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of an Operating System ( 9-User Mode)]]></title>
            <link>https://lahiruchathuranga-85477.medium.com/implementation-of-an-operating-system-9-user-mode-a40e7d51c2e8?source=rss-a6ce32d56b94------2</link>
            <guid isPermaLink="false">https://medium.com/p/a40e7d51c2e8</guid>
            <category><![CDATA[user-mode]]></category>
            <category><![CDATA[setting-up-for-user-mode]]></category>
            <category><![CDATA[entering-user-mode]]></category>
            <category><![CDATA[user-mode-programs]]></category>
            <dc:creator><![CDATA[Lahiru Chathuranga]]></dc:creator>
            <pubDate>Mon, 27 Sep 2021 04:59:24 GMT</pubDate>
            <atom:updated>2021-09-27T04:59:24.927Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q5mEq_bXIsF8uBSV.jpg" /></figure><p>This is my 9th article of my Implementation of an Operating System. So in this article I’m going to talk about User Mode. But first I want to inform that you, If you are a new reader for my article series, I think you must go to begging and read begging. Because If you don’t do that you can’ understand what I am saying in this chapter. You can go to the begging in<strong> </strong><a href="https://lahiruchathuranga-85477.medium.com/implementing-a-simple-operating-system-booting-the-os-6fd45a30908b"><strong><em>this link.</em></strong></a></p><p>Then first I want to see about what is the User Mode,</p><h3>User Mode</h3><p>The system is in user mode when the operating system is running a user application such as handling a text editor. The transition from user mode to kernel mode occurs when the application requests the help of operating system or an interrupt or a system call occurs.</p><p>The mode bit is set to 1 in the user mode. It is changed from 1 to 0 when switching from user mode to kernel mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/0*N-i98SxOClfQ7Jz3.PNG" /></figure><h3>Necessity of Dual Mode (User Mode and Kernel Mode) in Operating System</h3><p>The lack of a dual mode i.e user mode and kernel mode in an operating system can cause serious problems. Some of these are −</p><ul><li>A running user program can accidentaly wipe out the operating system by overwriting it with user data.</li><li>Multiple processes can write in the same system at the same time, with disastrous results.</li></ul><p>These problems could have occurred in the MS-DOS operating system which had no mode bit and so no dual mode.</p><h3>Segments for User Mode</h3><p>To enable user mode we need to add two more segments to the GDT. They are very similar to the kernel segments we added when we set up the GDT in the chapter about segmentation:</p><p><em>The segment descriptors needed for user mode.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*MK-PkHPKEYdupRlKFkDyKA.png" /></figure><p>The difference is the DPL, which now allows code to execute in PL3. The segments can still be used to address the entire address space, just using these segments for user mode code will not protect the kernel. For that we need paging.</p><p>Then you want to know about how to Setting Up For User Mode,</p><h3>Setting Up For User Mode.</h3><p>There are a few things every user mode process needs:</p><ul><li>Page frames for code, data and stack. At the moment it suffices to allocate one page frame for the stack and enough page frames to fit the program’s code. Don’t worry about setting up a stack that can be grow and shrink at this point in time, focus on getting a basic implementation work first.</li><li>The binary from the GRUB module has to be copied to the page frames used for the programs code.</li><li>A page directory and page tables are needed to map the page frames described above into memory. At least two page tables are needed, because the code and data should be mapped in at 0x00000000 and increasing, and the stack should start just below the kernel, at 0xBFFFFFFB, growing towards lower addresses. The U/S flag has to be set to allow PL3 access.</li></ul><p>It might be convenient to store this information in a struct representing a process. This process struct can be dynamically allocated with the kernel’s malloc function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*UrALyrc_KMm4m6pS.png" /></figure><h3>Entering User Mode</h3><p>how to Entering User Mode,</p><p>The only way to execute code with a lower privilege level than the current privilege level (CPL) is to execute an iret or lret instruction - interrupt return or long return, respectively.</p><p>To enter user mode we set up the stack as if the processor had raised an inter-privilege level interrupt. The stack should look like the following:</p><pre>[esp + 16]  ss      ; the stack segment selector we want for user mode<br>    [esp + 12]  esp     ; the user mode stack pointer<br>    [esp +  8]  eflags  ; the control flags we want to use in user mode<br>    [esp +  4]  cs      ; the code segment selector<br>    [esp +  0]  eip     ; the instruction pointer of user mode code to execute</pre><p>See the Intel manual [33], section 6.2.1, figure 6–4 for more information.</p><p>The instruction iret will then read these values from the stack and fill in the corresponding registers. Before we execute iret we need to change to the page directory we setup for the user mode process. It is important to remember that to continue executing kernel code after we’ve switched PDT, the kernel needs to be mapped in. One way to accomplish this is to have a separate PDT for the kernel, which maps all data at 0xC0000000 and above, and merge it with the user PDT (which only maps below 0xC0000000) when performing the switch. Remember that physical address of the PDT has to be used when setting the register cr3.</p><p>The register eflags contains a set of different flags, specified in section 2.3 of the Intel manual [33]. Most important for us is the interrupt enable (IF) flag. The assembly code instruction sti can’t be used in privilege level 3 for enabling interrupts. If interrupts are disabled when entering user mode, then interrupts can’t enabled once user mode is entered. Setting the IF flag in the eflags entry on the stack will enable interrupts in user mode, since the assembly code instruction iret will set the register eflags to the corresponding value on the stack.</p><p>For now, we should have interrupts disabled, as it requires a little more work to get inter-privilege level interrupts to work properly (see the section <a href="https://littleosbook.github.io/#system-calls">“System calls”</a>).</p><p>The value eip on the stack should point to the entry point for the user code - 0x00000000 in our case. The value esp on the stack should be where the stack starts - 0xBFFFFFFB (0xC0000000 - 4).</p><p>The values cs and ss on the stack should be the segment selectors for the user code and user data segments, respectively. As we saw in the <a href="https://littleosbook.github.io/#creating-and-loading-the-gdt">segmentation chapter</a>, the lowest two bits of a segment selector is the RPL - the Requested Privilege Level. When using iret to enter PL3, the RPL of cs and ss should be 0x3. The following code shows an example:</p><pre>USER_MODE_CODE_SEGMENT_SELECTOR equ 0x18<br>    USER_MODE_DATA_SEGMENT_SELECTOR equ 0x20<br>    mov cs, USER_MODE_CODE_SEGMENT_SELECTOR | 0x3<br>    mov ss, USER_MODE_DATA_SEGMENT_SELECTOR | 0x3</pre><p>The register ds, and the other data segment registers, should be set to the same segment selector as ss. They can be set the ordinary way, with the mov assembly code instruction.</p><p>We are now ready to execute iret. If everything has been set up right, we should now have a kernel that can enter user mode.</p><h3>Entering user mode in long mode</h3><h3>What?</h3><p>There’s four different rings in the Intel processor. Ring 0 is called kernel mode and Ring 3 is called user mode. User mode has a lot more security and restricted access to various instructions and areas of memory.</p><h3>Why?</h3><p>A rogue program running in Ring 0 can destroy the entire system, as it has almost no bounds on what it can do. This is why programs are ran in Ring 3; so that protection mechanisms can be put in place and at the very least, limit the amount of damage a virus can do. It’s also to prevent buggy code from affecting the rest of the system.</p><h3>How?</h3><p>The easiest way to enter Ring 3 is by hijacking an interrupt and pretending we were in Ring 3 to begin with, before we entered the interrupt. In exampleOS, we use the timer interrupt for this very purpose in <a href="https://github.com/Techno-coder/example_os/blob/e98b970e16662589d2b05b98f5b4990f9ac5a789/kernel/src/interrupts/handlers.rs#L44">this file</a>.</p><h3>The Global Descriptor Table</h3><p>Before paging was introduced, the main memory protection mechanism was through the use of “segmentation”. Essentially, regions of memory would be assigned a descriptor which describes the properties of that region, such as the privilege level to access it, whether it is executable, and whether it is writable. In long mode, we no longer use segmentation for protection, but it is still required. Instead, we just create two segments, for code and for data, and have it span the entire address space.</p><p>Descriptors can be marked as either Ring 0 or Ring 3. More importantly, they tell the processor what privilege mode we were in before entering an interrupt. We will use this later to jump into user mode.</p><h3>The Interrupt Stack Frame</h3><p>When an interrupt is received by the processor, two important things happen.</p><ol><li>The processor saves some data about its current state onto the stack</li><li>The processor jumps into the appropriate interrupt handler</li></ol><p>The data that is saved is called the Interrupt or Exception Stack Frame. Here’s what it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/0*lxmpzoT2C3bs_vpp.png" /></figure><p>The two important elements here are the stack and code segment. If their descriptors’ privilege level is Ring 3 then the processor thinks that we were in Ring 3 before the interrupt occurred. More importantly, when we return from the interrupt, the processor will place us into Ring 3.</p><h3>Creating the descriptors</h3><p>You’ll need to add two new descriptors to your GDT with these flags:<br>User Code Segment: USER_SEGMENT | PRESENT | EXECUTABLE | LONG_MODE | RING_USER<br>User Data Segment: USER_SEGMENT | PRESENT | WRITABLE | LONG_MODE | RING_USER</p><p>The hexadecimal version of these descriptors are:<br>User Code Segment: 0x0020_f800_0000_0000<br>User Data Segment: 0x0020_f200_0000_0000</p><p>These descriptors are almost the same as the kernel code and data descriptors except they have the RING_USER flag enabled. See exampleOS’s construction of these descriptors <a href="https://github.com/Techno-coder/example_os/blob/master/kernel/src/interrupts/gdt_descriptor.rs">here</a>.</p><h3>Referencing the descriptors</h3><p>Once you’ve added the new descriptors to the table, you’ll need their segment selectors as well.</p><p>Segment selectors act as an index into the Global Descriptor Table, as they point to a specific descriptor. They are 16 bits long. Bits 3 to 15 store the actual index into the GDT and bits 0 to 1 store the “requested privilege level” (or RPL for short). For a program to access a segment, their current descriptor’s RPL needs to be lower or equal to the current privilege level of the processor. For our purposes, all we need the RPL to be is Ring 3.</p><p>The index of a descriptor is calculated by their byte index divided by eight (because descriptors have a size of eight bytes). For example, if you already had three descriptors in the GDT (including the null descriptor), the fourth descriptor would have an index of 4.</p><p>exampleOS’s segment selectors can be found <a href="https://github.com/Techno-coder/example_os/blob/e98b970e16662589d2b05b98f5b4990f9ac5a789/kernel/src/interrupts/functions.rs#L53">here</a>.</p><h3>The FLAGS register</h3><p>The FLAGS register stores information about the state of the processor. For now, we don’t need to worry about it, but we do need to create a valid FLAGS value. The most minimal FLAGS register value is: 0x2 which only has the flag RESERVED set.</p><h3>Faking the stack</h3><p>Now we can try and get into user mode. First you need to setup an interrupt stack frame:</p><pre>pushq USER_DATA_SEGMENT_SELECTOR<br>pushq rsp<br>pushq 0x2<br>pushq USER_CODE_SEGMENT_SELECTOR<br>pushq ADDRESS_OF_FUNCTION</pre><p>Replace USER_DATA_SEGMENT_SELECTOR and USER_CODE_SEGMENT_SELECTOR with their numerical values. Replace ADDRESS_OF_FUNCTION with the address of a function you want executed in user mode. See exampleOS’s faked stack <a href="https://github.com/Techno-coder/example_os/blob/e98b970e16662589d2b05b98f5b4990f9ac5a789/kernel/src/task/loaders/stack.rs#L18">here</a>.</p><p>Finally, add this instruction at the end:</p><pre>iret</pre><p>This is the instruction for returning from an interrupt. The processor will pop off all the pushed values, and hopefully bring us into user mode.</p><h3>Now what?</h3><p>If you’re lucky, you should have either gotten a page fault or nothing happened at all. If you get a General Protection Fault, double check that all your descriptors are loaded properly, and the selectors are all correct. The address of the function should not be zero either as executing code at address zero will cause a fault.</p><h3>Interrupts are not working anymore</h3><p>If you’ve had a timer or keyboard interrupt set up, you may notice that it’s no longer firing. This is because for interrupts to work, the INTERRUPT_ENABLE flag needs to be set in the FLAGS register. If you want interrupts, this is the FLAGS value to push: 0x202</p><h3>Fixing the page fault</h3><p>The page that the function resides in must be marked as USER_ACCESSIBLE and EXECUTABLE. Additionally, the page directories needed to access the page <strong>must also be marked</strong> as USER_ACCESSIBLE. This is because when the processor resolves a virtual address, it needs to read all the page directories to access the page. exampleOS always adds the USER_ACCESSIBLE flag when <a href="https://github.com/Techno-coder/example_os/blob/e98b970e16662589d2b05b98f5b4990f9ac5a789/kernel/src/paging/page_table.rs#L41">creating a page directory</a>.</p><h3>Caveat</h3><p>We push the rsp register onto the exception stack frame. This is bad for two reasons:</p><ol><li>The stack is located in a kernel page</li><li>The user mode program shares the same stack with the kernel</li></ol><p>If you call any function, then a page fault will occur because the processor can’t write to the stack. Typically, you should have a separate stack for every user mode program. In a later post, we will fix this issue and look at how a user mode program is organised in memory.</p><h3>Using C for User Mode Programs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/0*z9BTq403wCAavI8T.jpg" /></figure><p>When C is used as the programming language for user mode programs, it is important to think about the structure of the file that will be the result of the compilation.</p><p>The reason we can use ELF [18] as the file format for for the kernel executable is because GRUB knows how to parse and interpret the ELF file format. If we implemented an ELF parser, we could compile the user mode programs into ELF binaries as well. We leave this as an exercise for the reader.</p><p>One thing we can do to make it easier to develop user mode programs is to allow the programs to be written in C, but compile them to flat binaries instead of ELF binaries. In C the layout of the generated code is more unpredictable and the entry point, main, might not be at offset 0 in the binary. One common way to work around this is to add a few assembly code lines placed at offset 0 which calls main:</p><pre>extern main</pre><pre>    section .text<br>        ; push argv<br>        ; push argc<br>        call main<br>        ; main has returned, eax is return value<br>        jmp  $    ; loop forever</pre><p>If this code is saved in a file called start.s, then the following code show an example of a linker script that places these instructions first in executable (remember that start.s gets compiled to start.o):</p><pre>OUTPUT_FORMAT(&quot;binary&quot;)    /* output flat binary */</pre><pre>    SECTIONS<br>    {<br>        . = 0;                 /* relocate to address 0 */</pre><pre>        .text ALIGN(4):<br>        {<br>            start.o(.text)     /* include the .text section of start.o */<br>            *(.text)           /* include all other .text sections */<br>        }</pre><pre>        .data ALIGN(4):<br>        {<br>            *(.data)<br>        }</pre><pre>        .rodata ALIGN(4):<br>        {<br>            *(.rodata*)<br>        }<br>    }</pre><p><em>Note</em>: *(.text) will not include the .text section of start.o again.</p><p>With this script we can write programs in C or assembler (or any other language that compiles to object files linkable with ld), and it is easy to load and map for the kernel (.rodata will be mapped in as writeable, though).</p><p>When we compile user programs we want the following GCC flags:</p><pre>-m32 -nostdlib -nostdinc -fno-builtin -fno-stack-protector -nostartfiles<br>    -nodefaultlibs</pre><p>For linking, the followings flags should be used:</p><pre>-T link.ld -melf_i386  # emulate 32 bits ELF, the binary output is specified<br>                           # in the linker script</pre><p>The option -T instructs the linker to use the linker script link.ld.</p><p>Thank you;</p><p>References:</p><p>littleosbook</p><p>You can refer this book : <a href="https://littleosbook.github.io/">https://littleosbook.github.io/</a></p><p><a href="https://techno-coder.github.io/">https://techno-coder.github.io/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a40e7d51c2e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4+1 Architectural View Model]]></title>
            <link>https://lahiruchathuranga-85477.medium.com/4-1-architectural-view-model-3bfe0fb463e5?source=rss-a6ce32d56b94------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bfe0fb463e5</guid>
            <dc:creator><![CDATA[Lahiru Chathuranga]]></dc:creator>
            <pubDate>Fri, 17 Sep 2021 15:38:56 GMT</pubDate>
            <atom:updated>2021-09-17T15:38:56.565Z</atom:updated>
            <content:encoded><![CDATA[<h3>History of 4+1 Architectural View Model</h3><p>In 1995, Philippe Kruchten was working at Rational Software Corp, at the time the pre-eminent vendor of software development tools.</p><p>With years of experience designing large scale complex software systems across telecommunications, aerospace, transport and defense, he had observed that software architecture diagrams often failed to provide clarity as to the actual system design. It was frequently confusing as to what the boxes, lines and arrows really represent, and stakeholders struggled to discover the information they needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/0*u3qI4GqNoZnsM24B.jpg" /></figure><p>He proposed a solution in a paper published that year — Architectural Blueprints — The “4+1” View Model of Software Architecture — to organize the description of a software architecture using a set of concurrent ‘views’, each addressing specific concerns, for specific stakeholders.</p><h3>Legacy</h3><p>In 1996, Kruchten was appointed the Director of Process at Rational Software where he led the development of the “Rational Unified Process” (RUP). The 4 + 1 views are a key concept in the RUP section on Analysis and Design.</p><p>While Kruchten was working at Rational, his colleagues were tackling the challenge of communicating about software on a different tack — the outcome was the Unified Modelling Language (UML).</p><p>The 4 + 1 views are a generic approach that does not prescribe any specific notation or diagramming structure (although Booch notation is used in the paper); UML fills in the blanks with prescriptive definitions of how to notate certain types of diagrams. Although the 4 + 1 views are not specifically referenced in UML, the intention of the RUP was that it would work in concert with UML as the notation for diagrams. It seems no coincidence and there is a neat alignment with the 4 + 1 views, with many UML diagrams being well suited for use in a specific view.</p><p>These days the 4 + 1 views are rarely utilised — technology and tech culture have moved on.</p><h3>Where did the 4 + 1 views go?</h3><p>Perhaps the fledgling rumblings of Service-Oriented Architecture (SOA) in 1998 heralded the end? In the context of Kruchten’s paper, systems were large complex beasts with often custom implementations of both hardware and software. The rise of SOA aligned with the web as the communications medium of choice, the adoption of commodity hardware, and increased search for ’re-usable’ components (often pre-packaged components from vendors). It’s possible that engineers started to see less value in explicitly documenting the separate views.</p><p>Or perhaps it was the rise of Extreme Programming (XP) and Agile? They have paved the way for a new kind of development process, one which eschews heavy formal frameworks like RUP (although Kruchten maintains that RUP is agile-compatible). Were the 4 + 1 views the baby thrown out with the bathwater?</p><h3>Introduction</h3><p>Have you ever worked on a microservices system experiencing challenges like these?</p><ul><li>I’ve separated my system into loosely coupled microservices — why is integration between them still so hard? I’m spending all my time implementing circuit breakers, bulkheads &amp; retry patterns when I’d rather be writing business logic!</li><li>My autonomous microservices teams are still blocking each other from delivery — why?</li><li>We still struggle with version incompatibilities between microservices… we’ve had to invest heavily in consumer driven contract testing to ensure we don’t break things</li><li>Making an update is so hard — we have to update code in multiple repositories containing our shared libraries and wait for a nuget or npm publish cycle in each of them before we can test the integration of changes</li></ul><p>Or perhaps you’re a startup who doesn’t want to over-engineer their launch solution, but also doesn’t want to end up with a big ball of mud, or unable to scale their system when the business starts doing well?</p><p>Either way — the “4 + 1 Architectural Views” may help.</p><p>This is the first in a series of posts about the views. Throughout the series, I hope to demonstrate how useful the 4 + 1 Views can be in understanding complex distributed systems, as well as facilitating more nuanced approaches to system design.</p><p>This first post will provide a brief introduction to each of the views, with deep dives into each view coming soon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/0*i4eX56QJAzUSNhEt.gif" /></figure><h3>The Views</h3><p>The “4 + 1 Architectural Views” were proposed in 1995 to solve increasing challenges communicating about software architectures.</p><p>The purpose of separating the architecture into multiple concurrent views was to isolate and illustrate different aspects of the design with information specifically oriented towards different stakeholders.</p><p>Each view should:</p><ul><li>define the system in terms of Components, Connectors and Containers</li><li>use appropriate styles, forms and patterns for each view</li><li>consider applicable constraints in each view</li><li>consider the relationship between the views</li></ul><p>For any given system, you may not need to document all the views, and there may be other, more relevant views for your system. I recommend creating the minimal documentation to explain architectural decisions, and ensure you are ready and willing to evolve your architecture (in each of the views) as your solution matures.</p><p><strong>Logical View</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/0*-JtjV2PkSuCKqfd7" /></figure><p>The logical view illustrates how the system is decomposed into specific areas of functionality. You will likely need to diagram the system at various levels of abstraction.</p><p>If you are using Domain Driven Design (DDD) then at the highest level (the most abstract) you might show domains, sub-domains and bounded contexts and the flow of events between them. In the Domain Blue Book <a href="https://devcycles.io/2019/02/27/4-1-architectural-view-model-introduction/#fn:2">2</a>, this is called the ‘context map’. At the lowest level (the most concrete), you might illustrate aggregates, aggregate roots, entities and relationships.</p><p>However, DDD is not the only way to design software — for some systems it may be better to illustrate functional modules, perhaps with a simple entity-relationship diagram.</p><p>Deep dive into the Logical View: coming soon…</p><p><strong>Process View</strong></p><p>The process view gets us to closer to an illustration of running software. Components in the process view are real executables that make up the run-time of your system.</p><p>For example, each of the following would be considered a ‘process’:</p><ul><li>IIS Web Application Pool</li><li>Single-page app running in a browser</li><li>Linux Daemon</li><li>Database engine running stored procedures or SQL scripts</li><li>etc.</li></ul><p>Processes can be thought of as a unit of ‘tactical control’. An individual process can be deployed, started, recovered, reconfigured, scaled out, and shutdown.</p><p>The purpose of the process view is to start to capture both the flow of inter-process information exchange (e.g. REST API calls, messaging via a bus) and the sequence and timing of these inter-process communications. This allows us to consider questions such as concurrency and reliability.</p><p>Deep dive into the Process View: coming soon…</p><p><strong>Physical View</strong></p><p>Even with the advent of Cloud computing and virtualised hardware, the physical architecture view still plays a critical role in understanding system performance and capacity.</p><p>Components are either processing nodes (servers, virtual machines, docker containers, serverless configurations, etc.) or networking channels (routers, firewalls, proxies, load balancers, etc.) and the diagram should illustrate which nodes host which processes from the process view. This allows us to start considering compute and network capacity, as well as latency and other performance considerations.</p><p>Deep dive into the Physical View: coming soon…</p><h3>Development View</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/0*05F-SKQpojhJahJT.jpg" /></figure><p>I often think about the development view as the “source code” view. As such, you can consider it as having two ‘sub-views’, or perspectives:</p><ul><li>Physical perspective, comprised of:</li><li>repositories</li><li>file systems</li><li>IDE projects/solutions &amp; structure (e.g. Visual Studio Solutions)</li></ul><p>The physical perspective helps you ‘find’ the code. There is a concept of ‘nearness’ which can be helpful when considering what code you want to keep ‘near’ what other code to enhance cohesion.</p><ul><li>Logical perspective, comprised of:</li><li>modules (e.g. assemblies, packages)</li><li>dependencies between modules</li><li>layering of modules</li></ul><p>The logical perspective helps you understand how the code modules work together. It allows you to understand static dependencies between the modules, as well as the flow of execution through the actual source code. This should help with understanding a run-time model — i.e. which modules will execute within which processes in the process view.</p><p>Deep dive into the Development View: coming soon…</p><p><strong>Scenario/Use Case View</strong></p><p>The scenario, or ‘use case’ view helps tie the architecture together. Different diagrams help to illustrate the flow of activity in a system and illustrate which logical, process, physical and development components are working together to facilitate the outcome.</p><p>Deep dive into the Scenario/Use Case View: coming soon…</p><h3>Why should I care?</h3><p>In this series of posts, I hope to demonstrate that many challenges facing teams today are a consequence of blending and ignoring the distinctions between the views — trying to solve problems in one view with design patterns in a different view, or by tightly aligning the design in each view. My experience is that if you allow yourself to evolve your solution in each view independently, many of these challenges become much easier to reason about.</p><p>This means you can plan ahead to scale appropriately, you can more easily trace performance or scalability issues back to the source, and you can understand why different teams (owning different components in the development view) have complex developer-time interactions affecting autonomy and progress.</p><p>After exploring each of the views in depth in the coming posts, we’ll return to this idea in more detail and explore how specific view alignment (or mis-alignment) patterns cause common risks and challenges.</p><p>References</p><p>Wikipedia :</p><p><a href="https://en.wikipedia.org/">Wikipedia, the free encyclopedia</a></p><p>D<a href="https://devcycles.io/">evcycles</a> :</p><p><a href="https://devcycles.io/">https://devcycles.io/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bfe0fb463e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of an Operating System ( 8-Page Frame Allocation)]]></title>
            <link>https://lahiruchathuranga-85477.medium.com/implementation-of-an-operating-system-8-page-frame-allocation-eeb90b39d87b?source=rss-a6ce32d56b94------2</link>
            <guid isPermaLink="false">https://medium.com/p/eeb90b39d87b</guid>
            <category><![CDATA[os]]></category>
            <category><![CDATA[page-mapping-in-os]]></category>
            <category><![CDATA[kernel]]></category>
            <category><![CDATA[implementation-os]]></category>
            <dc:creator><![CDATA[Lahiru Chathuranga]]></dc:creator>
            <pubDate>Fri, 10 Sep 2021 16:10:20 GMT</pubDate>
            <atom:updated>2021-09-27T04:37:39.065Z</atom:updated>
            <content:encoded><![CDATA[<p>This is my 8th article of my Implementation of an Operating System. So in this article I’m going to talk about Page Frame Allocation. But first I want to inform that you, If you are a new reader for my article series, I think you must go to begging and read begging. Because If you don’t do that you can’ understand what I am saying in this chapter. You can go to the begging in<strong> </strong><a href="https://lahiruchathuranga-85477.medium.com/implementing-a-simple-operating-system-booting-the-os-6fd45a30908b"><strong><em>this link.</em></strong></a></p><p>First we can see what is the mean of managing memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*DwPaq2YoZDiDttur" /></figure><h3>Managing Available Memory</h3><p>Memory Management is the process of controlling and coordinating computer memory, assigning portions known as blocks to various running programs to optimize the overall performance of the system.</p><p>It is the most important function of an operating system that manages primary memory. It helps processes to move back and forward between the main memory and execution disk. It helps OS to keep track of every memory location, irrespective of whether it is allocated to some process or it remains free.</p><p>First we need to know how much memory is available on the computer the OS is running on. The easiest way to do this is to read it from the multiboot structure [19] passed to us by GRUB. GRUB collects the information we need about the memory — what is reserved, I/O mapped, read-only etc. We must also make sure that we don’t mark the part of memory used by the kernel as free (since GRUB doesn’t mark this memory as reserved). One way to know how much memory the kernel uses is to export labels at the beginning and the end of the kernel binary from the linker script.</p><pre>ENTRY(loader)           /* the name of the entry symbol */</pre><pre>    . = 0xC0100000          /* the code should be relocated to 3 GB + 1 MB */</pre><pre>    /* these labels get exported to the code files */<br>    kernel_virtual_start = .;<br>    kernel_physical_start = . - 0xC0000000;</pre><pre>    /* align at 4 KB and load at 1 MB */<br>    .text ALIGN (0x1000) : AT(ADDR(.text)-0xC0000000)<br>    {<br>        *(.text)            /* all text sections from all files */<br>    }</pre><pre>    /* align at 4 KB and load at 1 MB + . */<br>    .rodata ALIGN (0x1000) : AT(ADDR(.rodata)-0xC0000000)<br>    {<br>        *(.rodata*)         /* all read-only data sections from all files */<br>    }</pre><pre>    /* align at 4 KB and load at 1 MB + . */<br>    .data ALIGN (0x1000) : AT(ADDR(.data)-0xC0000000)<br>    {<br>        *(.data)            /* all data sections from all files */<br>    }</pre><pre>    /* align at 4 KB and load at 1 MB + . */<br>    .bss ALIGN (0x1000) : AT(ADDR(.bss)-0xC0000000)<br>    {<br>        *(COMMON)           /* all COMMON sections from all files */<br>        *(.bss)             /* all bss sections from all files */<br>    }</pre><pre>    kernel_virtual_end = .;<br>    kernel_physical_end = . - 0xC0000000;</pre><p>These labels can directly be read from assembly code and pushed on the stack to make them available to C code:</p><pre>extern kernel_virtual_start<br>    extern kernel_virtual_end<br>    extern kernel_physical_start<br>    extern kernel_physical_end</pre><pre>    ; ...</pre><pre>    push kernel_physical_end<br>    push kernel_physical_start<br>    push kernel_virtual_end<br>    push kernel_virtual_start</pre><pre>    call kmain</pre><p>This way we get the labels as arguments to kmain. If you want to use C instead of assembly code, one way to do it is to declare the labels as functions and take the addresses of these functions:</p><pre>void kernel_virtual_start(void);</pre><pre>    /* ... */</pre><pre>    unsigned int vaddr = (unsigned int) &amp;kernel_virtual_start;</pre><p>If you use GRUB modules you need to make sure the memory they use is marked as reserved as well.</p><p>Note that the available memory does not need to be contiguous. In the first 1 MB there are several I/O-mapped memory sections, as well as memory used by GRUB and the BIOS. Other parts of the memory might be similarly unavailable.</p><p>It’s convenient to divide the memory sections into complete page frames, as we can’t map part of pages into memory.</p><p>Then we can see how Can We Access a Page Frame;</p><h3>How Can We Access a Page Frame</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/0*VuZpnifpCuaFUDc6.png" /></figure><p>A page, memory page, or virtual page is a fixed-length contiguous block of virtual memory, described by a single entry in the page table. It is the smallest unit of data for memory management in a virtual memory operating system. Similarly, a page frame is the smallest fixed-length contiguous block of physical memory into which memory pages are mapped by the operating system.</p><p>A transfer of pages between main memory and an auxiliary store, such as a hard disk drive, is referred to as paging or swapping.</p><p>We need to map the page frame into virtual memory, by updating the PDT and/or PT used by the kernel. What if all available page tables are full? Then we can’t map the page frame into memory, because we’d need a new page table — which takes up an entire page frame — and to write to this page frame we’d need to map its page frame… Somehow this circular dependency must be broken.</p><p>One solution is to reserve a part of the first page table used by the kernel (or some other higher-half page table) for temporarily mapping page frames to make them accessible. If the kernel is mapped at 0xC0000000 (page directory entry with index 768), and 4 KB page frames are used, then the kernel has at least one page table. If we assume - or limit us to - a kernel of size at most 4 MB minus 4 KB we can dedicate the last entry (entry 1023) of this page table for temporary mappings. The virtual address of pages mapped in using the last entry of the kernel’s PT will be:</p><pre>(768 &lt;&lt; 22) | (1023 &lt;&lt; 12) | 0x000 = 0xC03FF000</pre><p>After we’ve temporarily mapped the page frame we want to use as a page table, and set it up to map in our first page frame, we can add it to the paging directory, and remove the temporary mapping.</p><p>Next</p><h3>A Kernel Heap</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*EI23Li2Lonh1p7Ag" /></figure><p>A heap is a vital component of both application programs and the kernel. It is also generally superseded by a higher level of memory management that deals with larger chunks of memory. For most operating systems memory will be allocated based on pages or other large chunks. A page on the X86 and X64 architectures is generally 4KB, but can be larger. However, for smaller allocations the entire page would be wasted. For example if you only needed 24 bytes and you allocate an entire 4KB page you will have wasted a lot of memory. So most applications and kernels will implemented a second memory management scheme that uses memory allocated in 4KB chunks (or larger) and break these strips of pages or individual pages into smaller parts as they are requested.</p><p><strong>Standard Library, Applications, And Kernel</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bvvxEQ5zNmpoEWvg.jpeg" /></figure><p>Applications in most operating systems have their own heap implementation as a part of the standard library and do not use the implementation that the kernel uses. So therefore not only is the heap for the kernel separate from the heap of each application, but it may very well use a different heap implementation. Also, this allows each application to use it’s own implementation depending on which standard library is was built against or with. However, there is no reason why a kernel could not provide heap services directly to applications. It must be noted too that there is no way to enforce an application to use a specific heap or implementation because a clever programmer could simply use the memory allocated to supply it’s own implementation.</p><p>So far we’ve only been able to work with fixed-size data, or directly with raw memory. Now that we have a page frame allocator we can implement malloc and free to use in the kernel.</p><p>Kernighan and Ritchie [8] have an example implementation in their book that we can draw inspiration from. The only modification we need to do is to replace calls to sbrk/brk with calls to the page frame allocator when more memory is needed. We must also make sure to map the page frames returned by the page frame allocator to virtual addresses. A correct implementation should also return page frames to the page frame allocator on call to free, whenever sufficiently large blocks of memory are freed.</p><p>Thank you!</p><p>References;</p><p>wikipedia.com</p><p>littleosbook</p><p>You can refer this book : <a href="https://littleosbook.github.io/">https://littleosbook.github.io/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eeb90b39d87b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of an Operating System( 7-Virtual Memory and Paging)]]></title>
            <link>https://lahiruchathuranga-85477.medium.com/implementation-of-an-operating-system-7-virtual-memory-and-paging-4ab5558e22a3?source=rss-a6ce32d56b94------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ab5558e22a3</guid>
            <dc:creator><![CDATA[Lahiru Chathuranga]]></dc:creator>
            <pubDate>Mon, 06 Sep 2021 08:40:17 GMT</pubDate>
            <atom:updated>2021-09-06T08:41:29.560Z</atom:updated>
            <content:encoded><![CDATA[<p>This is my 7th article of my Implementation of an Operating System. So in this article I’m going to talk about what is the Virtual Memory and what is Paging. But first I want to inform that you, If you are a new reader for my article series, I think you must go to begging and read begging. Because If you don’t do that you can’ understand what I am saying in this chapter. You can go to the begging in<strong> </strong><a href="https://lahiruchathuranga-85477.medium.com/implementing-a-simple-operating-system-booting-the-os-6fd45a30908b"><strong><em>this link.</em></strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6h6z7NlccsTrAEzQ.jpg" /></figure><p>First we can sea what is the,</p><h3>Virtual Memory</h3><p><em>Virtual memory</em> is an abstraction of physical memory. The purpose of virtual memory is generally to simplify application development and to let processes address more memory than what is actually physically present in the machine. We also don’t want applications messing with the kernel or other applications’ memory due to security.</p><p><a href="http://www.cirosantilli.com/x86-paging">Version of this answer with a nice TOC and more content</a>.</p><p>I will correct any error reported. If you want to make large modifications or add a missing aspect, make them on your own answers to get well deserved rep. Minor edits can be merged directly in.</p><h3>Sample code</h3><p>Minimal example: <a href="https://github.com/cirosantilli/x86-bare-metal-examples/blob/5c672f73884a487414b3e21bd9e579c67cd77621/paging.S">https://github.com/cirosantilli/x86-bare-metal-examples/blob/5c672f73884a487414b3e21bd9e579c67cd77621/paging.S</a></p><p>Like everything else in programming, the only way to really understand this is to play with minimal examples.</p><p>What makes this a “hard” subject is that the minimal example is large because you need to make your own small OS.</p><h3>Intel manual</h3><p>Although it is impossible to understand without examples in mind, try to get familiar with the manuals as soon as possible.</p><p>Intel describes paging in the <a href="https://web.archive.org/web/20151025081259/http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-system-programming-manual-325384.pdf">Intel Manual Volume 3 System Programming Guide — 325384–056US September 2015</a> Chapter 4 “Paging”.</p><p>Specially interesting is Figure 4–4 “Formats of CR3 and Paging-Structure Entries with 32-Bit Paging”, which gives the key data structures.</p><h3>MMU</h3><p>Paging is done by the <a href="https://en.wikipedia.org/wiki/Memory_management_unit">Memory Management Unit</a> (MMU) part of the CPU. Like many others (e.g. <a href="https://en.wikipedia.org/wiki/X87">x87 co-processor</a>, <a href="https://en.wikipedia.org/wiki/Advanced_Programmable_Interrupt_Controller">APIC</a>), this used to be by separate chip on early days, which was later integrated into the CPU. But the term is still used.</p><h3>General facts</h3><p>Logical addresses are the memory addresses used in “regular” user-land code (e.g. the contents of rsi in mov eax, [rsi]).</p><p>First segmentation translates them into linear addresses, and then paging then translates linear addresses into physical addresses.</p><pre>(logical) ------------------&gt; (linear) ------------&gt; (physical)<br>             segmentation                 paging</pre><p>Most of the time, we can think of physical addresses as indexing actual RAM hardware memory cells, but this is not 100% true because of:</p><ul><li><a href="https://en.wikipedia.org/wiki/Memory-mapped_I/O">memory-mapped I/O regions</a></li><li><a href="https://en.wikipedia.org/wiki/Multi-channel_memory_architecture">multi channel memory</a></li></ul><p>Paging is only available in protected mode. The use of paging in protected mode is optional. Paging is on iff the PG bit of the cr0 register is set.</p><h3>Paging vs segmentation</h3><p>One major difference between paging and segmentation is that:</p><ul><li>paging splits RAM into equal sized chunks called pages</li><li>segmentation splits memory into chunks of arbitrary sizes</li></ul><p>This is the main advantage of paging, since equal sized chunks make things more manageable.</p><p>Paging has become so much more popular that support for segmentation was dropped in x86–64 in 64-bit mode, the main mode of operation for new software, where it only exists in compatibility mode, which emulates IA32.</p><p>Then what is,</p><h3>Paging</h3><p>Segmentation translates a logical address into a linear address. <em>Paging</em> translates these linear addresses onto the physical address space, and determines access rights and how the memory should be cached.</p><h3>Paging in x86</h3><p>Paging is a system which allows each process to see a full virtual address space, without actually requiring the full amount of physical memory to be available or present. 32-bit x86 processors support 32-bit virtual addresses and 4-GiB virtual address spaces, and current 64-bit processors support 48-bit virtual addressing and 256-TiB virtual address spaces. Intel has released <a href="https://en.wikipedia.org/wiki/Intel_5-level_paging">documentation</a> for a extension to 57-bit virtual addressing and 128-PiB virtual address spaces. Currently, implementations of x86–64 have a limit of between 4 GiB and 256 TiB of physical address space (and an architectural limit of 4 PiB of physical address space).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*3_38wGbF_rBHoUQA.gif" /></figure><p>In addition to this, paging introduces the benefit of page-level protection. In this system, user processes can only see and modify data which is paged in on their own address space, providing hardware-based isolation. System pages are also protected from user processes. On the x86–64 architecture, page-level protection now completely supersedes <a href="https://wiki.osdev.org/Segmentation">Segmentation</a> as the memory protection mechanism. On the IA-32 architecture, both paging and segmentation exist, but segmentation is now considered ‘legacy’.</p><p>Once an Operating System has paging, it can also make use of other benefits and workarounds, such as linear framebuffer simulation for memory-mapped IO and paging out to disk, where disk storage space is used to free up physical RAM. Then we can move to Identity Paging.</p><h3>Identity Paging</h3><p>Identity Paging, Identity Mapped Paging and 1:1 Paging are terms often used on the forum to describe a design choice where a portion of virtual addresses are mapped to physical addresses that have the same value. This means that if paging is enabled with identity paging, 0xb8000 <strong>is</strong> 0xb8000, as long as that area is identity mapped.</p><p><strong>Advantages</strong></p><p>When switching to paged protected mode, your 1:1 mapping region doesn’t care of whether paging is enabled or disabled. Placing your switching code and important data such as the core page directory and a few system page tables in this region gives you an easier way to set up paging without headaches.</p><p>For example you can refer below scenario.</p><p><strong>Example</strong></p><p>Let’s say you decide to use Identity Paging in the lowest 1MB. In this case vaddr 00000000..00000fff are mapped to frame #00000, vaddr 00001000..00001fff are mapped to frame #00001, and so on. (vaddr 000ff000..000fffff are mapped to frame #000ff)</p><p>You can easily do this with a loop filling the page table:</p><pre>void idpaging(uint32_t *first_pte, vaddr from, int size) {<br>    from = from &amp; 0xfffff000; <em>// discard bits we don&#39;t want</em><br>    for(; size&gt;0; from += 4096, size -= 4096, first_pte++){<br>       *first_pte = from | 1;     <em>// mark page present.</em><br>    }<br> }</pre><p>Now the most important thing comes. It is how to enabling paging.</p><h3>Enabling paging</h3><p>Paging is enabled by first writing the address of a page directory to cr3 and then setting bit 31 (the PG “paging-enable” bit) of cr0 to 1. To use 4 MB pages, set the PSE bit (Page Size Extensions, bit 4) of cr4. The following assembly code shows an example:</p><pre>; eax has the address of the page directory<br>    mov cr3, eax</pre><pre>    mov ebx, cr4        ; read current cr4<br>    or  ebx, 0x00000010 ; set PSE<br>    mov cr4, ebx        ; update cr4</pre><pre>    mov ebx, cr0        ; read current cr0<br>    or  ebx, 0x80000000 ; set PG<br>    mov cr0, ebx        ; update cr0</pre><pre>    ; now paging is enabled</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/0*0rA6fUZq2pJl8XHP.jpg" /></figure><h3>Another Few Details about paging</h3><p>It is important to note that all addresses within the page directory, page tables and in cr3 need to be physical addresses to the structures, never virtual. This will be more relevant in later sections where we dynamically update the paging structures (see the chapter <a href="https://littleosbook.github.io/#user-mode">“User Mode”</a>).</p><p>An instruction that is useful when an updating a PDT or PT is invlpg. It invalidates the <em>Translation Lookaside Buffer</em> (TLB) entry for a virtual address. The TLB is a cache for translated addresses, mapping physical addresses corresponding to virtual addresses. This is only required when changing a PDE or PTE that was previously mapped to something else. If the PDE or PTE had previously been marked as not present (bit 0 was set to 0), executing invlpg is unnecessary. Changing the value of cr3 will cause all entries in the TLB to be invalidated.</p><p>An example of invalidating a TLB entry is shown below:</p><pre>; invalidate any TLB references to virtual address 0<br>    invlpg [0]</pre><h3>Paging and Kernel</h3><p>In below sections I will try to explain about paging and the kernel.</p><h3>Reasons to Not Identity Map the Kernel</h3><p>If the kernel is positioned at the beginning of the virtual deal with space — this is, the digital cope with area (0x00000000, “size of kernel”) maps to the vicinity of the kernel in memory — there can be issues while linking the user mode process code. Normally, at some point of linking, the linker assumes that the code may be loaded into the memory position 0x00000000. Therefore, whilst resolving absolute references, 0x00000000 could be the base deal with for calculating the precise position. But if the kernel is mapped onto the digital deal with space (0x00000000, “length of kernel”), the person mode technique can’t be loaded at digital cope with 0x00000000 — it must be placed elsewhere. Therefore, the idea from the linker that the consumer mode procedure is loaded into memory at function 0x00000000 is incorrect. This may be corrected by using the use of a linker script which tells the linker to assume a special starting deal with, however that may be a very cumbersome answer for the users of the operating gadget.<br>This also assumes that we need the kernel to be part of the person mode system’ cope with area. As we can see later, this is a nice feature, considering the fact that for the duration of system calls we do not have to alternate any paging structures to get access to the kernel’s code and information. The kernel pages will of route require privilege level zero for get admission to, to save you a person process from reading or writing kernel memory.</p><h3>The Virtual Address for the KernelIn the Linux kernel it is possible to map a kernel address space to a user address space. This eliminates the overhead of copying user space information into the kernel space and vice versa. This can be done through a device driver and the user space device interface (/dev).</h3><p>This feature can be used by implementing the <strong>mmap()</strong> operation in the device driver&#39;s <strong>struct file_operations</strong> and using the <strong>mmap()</strong> system call in user space.</p><p>The basic unit for virtual memory management is a page, which size is usually 4K, but it can be up to 64K on some platforms. Whenever we work with virtual memory we work with two types of addresses: virtual address and physical address. All CPU access (including from kernel space) uses virtual addresses that are translated by the MMU into physical addresses with the help of page tables.</p><p>A physical page of memory is identified by the Page Frame Number (PFN). The PFN can be easily computed from the physical address by dividing it with the size of the page (or by shifting the physical address with PAGE_SHIFT bits to the right).</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>For efficiency reasons, the virtual address space is divided into user space and kernel space. For the same reason, the kernel space contains a memory mapped zone, called <strong>lowmem</strong>, which is contiguously mapped in physical memory, starting from the lowest possible physical address (usually 0). The virtual address where lowmem is mapped is defined by <strong>PAGE_OFFSET</strong>.</p><p>On a 32bit system, not all available memory can be mapped in lowmem and because of that there is a separate zone in kernel space called <strong>highmem</strong> which can be used to arbitrarily map physical memory.</p><p>Memory allocated by <strong>kmalloc()</strong> resides in lowmem and it is physically contiguous. Memory allocated by <strong>vmalloc()</strong> is not contiguous and does not reside in lowmem (it has a dedicated zone in highmem).</p><h3>Placing the Kernel at 0xC0000000</h3><p>To start with, it is better to place the kernel at 0xC0100000 than 0xC0000000, since this makes it possible to map (0x00000000, 0x00100000) to (0xC0000000, 0xC0100000). This way, the entire range (0x00000000, &quot;size of kernel&quot;) of memory is mapped to the range (0xC0000000, 0xC0000000 + &quot;size of kernel&quot;).</p><p>Placing the kernel at 0xC0100000 isn’t hard, but it does require some thought. This is once again a linking problem. When the linker resolves all absolute references in the kernel, it will assume that our kernel is loaded at physical memory location 0x00100000, not 0x00000000, since relocation is used in the linker script (see the section <a href="https://littleosbook.github.io/#linking-the-kernel">“Linking the kernel”</a>). However, we want the jumps to be resolved using 0xC0100000 as base address, since otherwise a kernel jump will jump straight into the user mode process code (remember that the user mode process is loaded at virtual memory 0x00000000).</p><p>However, we can’t simply tell the linker to assume that the kernel starts (is loaded) at 0xC01000000, since we want it to be loaded at the physical address 0x00100000. The reason for having the kernel loaded at 1 MB is because it can’t be loaded at 0x00000000, since there is BIOS and GRUB code loaded below 1 MB. Furthermore, we cannot assume that we can load the kernel at 0xC0100000, since the machine might not have 3 GB of physical memory.</p><p>This can be solved by using both relocation (.=0xC0100000) and the AT instruction in the linker script. Relocation specifies that non-relative memory-references should should use the relocation address as base in address calculations. AT specifies where the kernel should be loaded into memory. Relocation is done at link time by GNU ld , the load address specified by AT is handled by GRUB when loading the kernel, and is part of the ELF format.</p><h3>Higher-half Linker Script</h3><p>We can modify the <a href="https://littleosbook.github.io/#linking-the-kernel">first linker script</a> to implement this:</p><pre>ENTRY(loader)           /* the name of the entry symbol */</pre><pre>    . = 0xC0100000          /* the code should be relocated to 3GB + 1MB */</pre><pre>    /* align at 4 KB and load at 1 MB */<br>    .text ALIGN (0x1000) : AT(ADDR(.text)-0xC0000000)<br>    {<br>        *(.text)            /* all text sections from all files */<br>    }</pre><pre>    /* align at 4 KB and load at 1 MB + . */<br>    .rodata ALIGN (0x1000) : AT(ADDR(.text)-0xC0000000)<br>    {<br>        *(.rodata*)         /* all read-only data sections from all files */<br>    }</pre><pre>    /* align at 4 KB and load at 1 MB + . */<br>    .data ALIGN (0x1000) : AT(ADDR(.text)-0xC0000000)<br>    {<br>        *(.data)            /* all data sections from all files */<br>    }</pre><pre>    /* align at 4 KB and load at 1 MB + . */<br>    .bss ALIGN (0x1000) : AT(ADDR(.text)-0xC0000000)<br>    {<br>        *(COMMON)           /* all COMMON sections from all files */<br>        *(.bss)             /* all bss sections from all files */</pre><h3>Higher half Kernel</h3><p>It is traditional and generally good to have your kernel mapped in every user process. Linux and many other Unices, for instance, reside at virtual addresses <em>0xC0000000–0xFFFFFFFF</em> of every address space, leaving the range <em>0x00000000–0xBFFFFFFF</em> for user code, data, stacks, libraries, etc. Kernels that have such design are said to be “in the higher half” by opposition to kernels that use lowest virtual addresses for themselves, and leave higher addresses for the applications.</p><p>In addition, there is some non-x86 ISA (the <a href="https://wiki.osdev.org/MIPS_Overview">MIPS</a> <a href="https://wiki.osdev.org/User:Schol-r-lea/Understanding_RISC_vs_CISC">RISC architecture</a> and <a href="https://wiki.osdev.org/AArch64">ARM</a>) which partly forces the issue. On MIPS and ARM systems, addresses using the high bit (either bit 31 or bit 63, depending on the system word width) are reserved for use in Supervisor mode, and are exception trapped when in User mode.</p><p>Advantages of a higher half kernel are:</p><ul><li>It’s easier to set up <a href="https://wiki.osdev.org/Virtual_8086_Mode">VM86</a> processes since the region below 1 MB is userspace.</li><li>More generally, user applications are not dependent on how much memory is kernel space (your application can be linked to 0x400000 regardless of whether kernel is at <em>0xC0000000</em>, <em>0x80000000</em> or <em>0xE0000000</em> …), which makes the ABI nicer.</li><li>If your OS is 64-bit, then 32-bit applications will be able to use the full 32-bit address space.</li><li>‘Mnemonic’ invalid pointers such as <em>0xCAFEBABE</em>, <em>0xDEADBEEF</em>, <em>0xDEADC0DE</em>, etc. can be used.</li></ul><p>Now we know what is the higher half kernel and it advantages. Now we can look how entering the higher half.</p><h3>Entering Higher Half</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yybglpc1KB5doez2Il8_OQ.png" /></figure><p>When GRUB jumps to the kernel code, there is no paging table. Therefore, all references to 0xC0100000 + X won’t be mapped to the correct physical address, and will therefore cause a general protection exception (GPE) at the very best, otherwise (if the computer has more than 3 GB of memory) the computer will just crash.</p><p>Therefore, assembly code that doesn’t use relative jumps or relative memory addressing must be used to do the following:</p><ul><li>Set up a page table.</li><li>Add identity mapping for the first 4 MB of the virtual address space.</li><li>Add an entry for 0xC0100000 that maps to 0x0010000</li></ul><p>If we skip the identity mapping for the first 4 MB, the CPU would generate a page fault immediately after paging was enabled when trying to fetch the next instruction from memory. After the table has been created, an jump can be done to a label to make eip point to a virtual address in the higher half:</p><pre>; assembly code executing at around 0x00100000<br>    ; enable paging for both actual location of kernel<br>    ; and its higher-half virtual location</pre><pre>    lea ebx, [higher_half] ; load the address of the label in ebx<br>    jmp ebx                ; jump to the label</pre><pre>    higher_half:<br>        ; code here executes in the higher half kernel<br>        ; eip is larger than 0xC0000000<br>        ; can continue kernel initialisation, calling C code, etc.</pre><p>The register eip will now point to a memory location somewhere right after 0xC0100000 - all the code can now execute as if it were located at 0xC0100000, the higher-half. The entry mapping of the first 4 MB of virtual memory to the first 4 MB of physical memory can now be removed from the page table and its corresponding entry in the TLB invalidated with invlpg [0].</p><h3>Virtual Memory Through Paging</h3><p>Paging enables two things that are good for virtual memory. First, it allows for fine-grained access control to memory. You can mark pages as read-only, read-write, only for PL0 etc. Second, it creates the illusion of contiguous memory. User mode processes, and the kernel, can access memory as if it were contiguous, and the contiguous memory can be extended without the need to move data around in memory. We can also allow the user mode programs access to all memory below 3 GB, but unless they actually use it, we don’t have to assign page frames to the pages. This allows processes to have code located near 0x00000000 and the stack at just below 0xC0000000, and still not require more than two actual pages.</p><p>This is the end of my 7th chapter of my article series.</p><p>Thank you</p><p>references;</p><p><a href="https://stackoverflow.com/">Newest Questions</a></p><p>wikipedia.com</p><p>littleosbook</p><p>You can refer this book : <a href="https://littleosbook.github.io/">https://littleosbook.github.io/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ab5558e22a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software license..]]></title>
            <link>https://lahiruchathuranga-85477.medium.com/what-does-mean-by-software-license-8e544d2f56d7?source=rss-a6ce32d56b94------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e544d2f56d7</guid>
            <dc:creator><![CDATA[Lahiru Chathuranga]]></dc:creator>
            <pubDate>Fri, 27 Aug 2021 19:23:43 GMT</pubDate>
            <atom:updated>2021-08-27T19:24:14.542Z</atom:updated>
            <content:encoded><![CDATA[<h3>What does mean by software license.</h3><p>A software license is <strong>a document that provides legally binding guidelines for the use and distribution of software</strong>. Software licenses typically provide end users with the right to one or more copies of the software without violating copyrights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*-l8olTfUkafsKze_.jpg" /></figure><p>Most open source licenses include the following statements:</p><ol><li>Software can be modified, used commercially, and distributed.</li><li>Software can be modified and used in private.</li><li>A license and copyright notice must be included in the software.</li><li>Software authors provide no warranty with the software and are not liable for anything.</li></ol><h3><strong>different types of software licenses</strong></h3><p>There are many different types of software licenses, and the penalties for license noncompliance can be harsh. If you reuse a component without following the obligations of its license, the licensor might sue, and you might be forced to publish your own source code. To protect your code and your organization, you need to understand these software licenses before using any code, including libraries and frameworks, you didn’t write yourself. See our list of the top open source licenses and their potential legal risks.</p><p>Here are five types of common software license models,</p><ol><li><strong>Public domain.</strong></li><li><strong>LGPL.</strong></li><li><strong>Permissive.</strong></li><li><strong>Copyleft.</strong></li><li><strong>Copyleft.</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/0*tvzW7MZJQzm14_M-.png" /></figure><p>Now we can see some deep in that types.</p><ol><li><strong>Public domain</strong>.</li></ol><p>This is the most permissive type of software license. When software is in the public domain, anyone can modify and use the software without any restrictions. But you should always make sure it’s secure before adding it to your own codebase. Warning: Code that doesn’t have an explicit license is NOT automatically in the public domain. This includes code snippets you find on the internet.</p><p><strong>2. LGPL.</strong></p><p>The GNU Lesser General Public License allows you to link to open source libraries in your software. If you simply compile or link an LGPL-licensed library with your own code, you can release your application under any license you want, even a proprietary license. But if you modify the library or copy parts of it into your code, you’ll have to release your application under similar terms as the LGPL.</p><p><strong>3. Permissive.</strong></p><p>Permissive licenses are also known as “Apache style” or “BSD style.” They contain minimal requirements about how the software can be modified or redistributed. This type of software license is perhaps the most popular license used with free and open source software. Aside from the Apache License and the BSD License, another common variant is the MIT License.</p><p><strong>4. Copyleft.</strong></p><p>Copyleft licenses are also known as reciprocal licenses or restrictive licenses. The most well-known example of a copyleft or reciprocal license is the GPL. These licenses allow you to modify the licensed code and distribute new works based on it, <em>as long as</em> you distribute any new works or adaptations under the same software license. For example, a component’s license might say the work is free to use and distribute for personal use only. So any derivative you create would also be limited to personal use only. (A derivative is any new software you develop that contains the component.)</p><p>The catch here is that the users of your software would also have the right to modify the code. Therefore, you’d have to make your own source code available. But of course, exposing your source code may not be in your best interests.</p><p><strong>5. Proprietary.</strong></p><p>Of all types of software licenses, this is the most restrictive. The idea behind it is that all rights are reserved. It’s generally used for proprietary software where the work may not be modified or redistributed.</p><p>We will go through the most popular licenses, in order from the most restrictive to the most permissive (from a user’s perspective).</p><h4>GNU General Public License, version 3 (GPLv3)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*ic-xw8N9x4lsLnnZ.jpg" /></figure><p><a href="https://www.gnu.org/licenses/gpl-3.0.html">GPLv3</a> is one of the most restrictive licenses. It offers high protection for the author of the software.</p><ul><li>The source code must be made <strong>public</strong> whenever a distribution of the software is made.</li><li>Modifications of the software must be released under the <strong>same license</strong>.</li><li>Changes made to the source code <strong>must be documented</strong>.</li><li>If patented material was used in the creation of the software, it grants the right for users to use it. If the user sues anyone over the use of the patented material, they lose the right to use the software.</li></ul><p><strong>GPLv2</strong> is also very popular. The main difference from GPLv3 is the clause on patent grants.</p><p>That clause was added in version 3 to prevent companies from charging users for the use of their patents.</p><p>Popular projects using GPLv3 are <strong>Bash</strong> and <strong>GIMP</strong>. <strong>Linux</strong> uses GPLv2.</p><p>Ezequiel Foncubierta pointed something important for GPL licenses:</p><blockquote><em>The license of your source code must be compatible with the license of the open source code you are linking to. For instance, if your code is proprietary, you won’t be allowed to use a library under the GPL license. This is where people tends to make more mistakes.</em></blockquote><h4>Apache License 2.0</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/0*SsqkRxvs4trSLlSQ.png" /></figure><p>Apache License 2.0 offers more flexibility to the users.</p><ul><li>The source code <strong>doesn’t need to be public</strong> when a distribution of the software is made.</li><li>Modifications to the software can be release under <strong>any license</strong>.</li><li>Changes made to the source code <strong>must </strong>be documented.</li><li>It offers the same patent usage protection as GPLv3.</li><li>It explicitly prohibits the use of trademarked names found in the project.</li></ul><p>Popular projects using Apache License 2.0 are <strong>Android</strong>, <strong>Apache</strong>, and <strong>Swift</strong>.</p><h4>Berkeley Software Distribution (BSD)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nC-q059PrV1N1o_Z.jpg" /></figure><p>BSD has two main versions: 2-clause and 3-clause. They both offer more flexibility to the users than the Apache License 2.0.</p><ul><li>The source code <strong>doesn’t need to be public</strong> when a distribution of the software is made.</li><li>Modifications to the software can be release under <strong>any license</strong>.</li><li>Changes made to the source code <strong>may</strong> <strong>not</strong> be documented.</li><li>It offers no explicit position on patent usage.</li><li>The license and copyright notice must be included in the documentation of the <strong>compiled version</strong> of the source code (as opposed to only in the source code).</li><li>The BSD 3-clause states that the names of the author and contributors can’t be used to promote products derived from the software without permission.</li></ul><p>Popular projects using BSD license are <strong>Go</strong> (3-clause), <strong>Pure.css</strong> (3-clause), and <strong>Sentry</strong> (3-clause).</p><h4>MIT License</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Nu6fYBCeDpOdwXjh.png" /></figure><p>MIT is one of the most permissive licenses. It is also the most popular one. It offers very low protection for the author of the software.</p><ul><li>The source code <strong>doesn’t need to be public</strong> when a distribution of the software is made.</li><li>Modifications to the software can be release under <strong>any license</strong>.</li><li>Changes made to the source code <strong>may</strong> <strong>not</strong> be documented.</li><li>It offers no explicit position on patent usage.</li></ul><p>Popular projects using MIT are <strong>Angular.js</strong>, <strong>jQuery</strong>, <strong>Rails</strong>, <strong>Bootstrap</strong>, and many more.</p><p>Facebook’s <strong>React.js</strong> had a BSD-3+patents license up until September 25th. It combined the BSD-3 license with an extra clause on patents usage.</p><p>In a nutshell, if you sue Facebook or any of its subsidiaries, you lose the right to use React (or any other software under the same license).</p><p>React is now MIT licensed. You are now able to sue Facebook and still use React. What a relief!</p><h3>Applying a license to your open source projects</h3><p>Licensing your projects is easy. You need to add a license, license.txt or license.md in the root directory of your repository.</p><p>GitHub makes it even easier:</p><ol><li>Open your GitHub repository in a browser.</li><li>In the root directory, click on create new file.</li><li>Name the file “LICENSE”.</li><li>Click on choose a license template.</li><li>Pick one of the licenses (all the ones mentioned in this article are there).</li><li>Once chosen, click on review and submit.</li><li>Commit the file.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e544d2f56d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of an Operating System( 6-The road to user mode)]]></title>
            <link>https://lahiruchathuranga-85477.medium.com/implementation-of-an-operating-system-6-the-road-to-user-mode-414a631893d0?source=rss-a6ce32d56b94------2</link>
            <guid isPermaLink="false">https://medium.com/p/414a631893d0</guid>
            <dc:creator><![CDATA[Lahiru Chathuranga]]></dc:creator>
            <pubDate>Fri, 27 Aug 2021 12:24:27 GMT</pubDate>
            <atom:updated>2021-08-27T12:24:27.520Z</atom:updated>
            <content:encoded><![CDATA[<p>This is my sixth article of my article series about Implementation of an operating system. And in this article I will talk about The road to user mode in an operating system.</p><p>If you new to my series fist you must read in in beginning. Because if you don’t read it in beginning then you couldn’t understand what am I say now, In <a href="https://lahiruchathuranga-85477.medium.com/implementing-a-simple-operating-system-booting-the-os-6fd45a30908b"><em>here</em></a> you can go to first one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C3SYp-kMw_fCxhKH.jpg" /></figure><p>What do we do now that the kernels boots, prints to screen and reads from keyboard? The application logic is usually left for applications. To make application development easier, the kernels creates proper abstractions for memory, files, devices, and performs tasks on behalf of applications.</p><p>The environment in which the user’s programs execute is called user mode. The environment is less privileged and will prevent user programs from messing with other programs. Badly written kernels can mess up what they want.</p><p>This chapter will show you how to execute a small program in kernels mode, even though the OS created in this book can only execute programs in user mode.</p><h3>Loading an External Program</h3><p>Where do we get the external program? We need to load the code we want to execute into memory. More feature-complete operating systems usually have drivers and file systems that allow them to load the software from a CD-ROM drive, a hard disk or other persistent media.</p><p>We will use a feature in GRUB called modules to load the program instead of creating all these drivers and file systems.</p><p>The next thing is to talk about GRUB Modules.</p><h3>GRUB Modules</h3><p>GRUB can load arbitrary files into memory from the ISO image, and these files are usually referred to as <em>modules</em>. To make GRUB load a module, edit the file iso/boot/grub/menu.lst and add the following line at the end of the file:</p><pre>module /modules/program</pre><p>Now create the folder iso/modules:</p><pre>mkdir -p iso/modules</pre><p>The application program will be created later in this chapter.</p><p>The code that calls kmain must be updated to pass information to kmain about where it can find the modules. We also want to tell GRUB that it should align all the modules on page boundaries when loading them (see the chapter <a href="https://littleosbook.github.io/#paging">“Paging”</a> for details about page alignment).</p><p>To instruct GRUB how to load our modules, the “multiboot header” — the first bytes of the kernel — must be updated as follows:</p><pre>; in file `loader.s`<br></pre><pre>    MAGIC_NUMBER    equ 0x1BADB002      ; define the magic number constant<br>    ALIGN_MODULES   equ 0x00000001      ; tell GRUB to align modules</pre><pre>    ; calculate the checksum (all options + checksum should equal 0)<br>    CHECKSUM        equ -(MAGIC_NUMBER + ALIGN_MODULES)</pre><pre>    section .text:                      ; start of the text (code) section<br>    align 4                             ; the code must be 4 byte aligned<br>        dd MAGIC_NUMBER                 ; write the magic number<br>        dd ALIGN_MODULES                ; write the align modules instruction<br>        dd CHECKSUM                     ; write the checksum</pre><p>GRUB will also store a pointer to a struct in the register ebx that, among other things, describes at which addresses the modules are loaded. Therefore, you probably want to push ebx on the stack before calling kmain to make it an argument for kmain.</p><p>Now we will be look at how to Executing a Program.</p><h3>Executing a Program</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/0*R4Nz3FNr9Y8DwRv8.png" /></figure><h3>A Very Simple Program</h3><p>A program written at this stage can only perform a few actions. Therefore, a very short program that writes a value to a register suffices as a test program. Halting Bochs after a while and then check that register contains the correct number by looking in the Bochs log will verify that the program has run. This is an example of such a short program:</p><pre>; set eax to some distinguishable number, to read from the log afterwards<br>    mov eax, 0xDEADBEEF</pre><pre>    ; enter infinite loop, nothing more to do<br>    ; $ means &quot;beginning of line&quot;, ie. the same instruction<br>    jmp $</pre><h3>Compiling</h3><p>Since our kernel cannot parse advanced executable formats we need to compile the code into a flat binary. NASM can do this with the flag -f:</p><pre>nasm -f bin program.s -o program</pre><p>This is all we need. You must now move the file program to the folder iso/modules.</p><h3>Finding the Program in Memory</h3><p>Before jumping to the program we must find where it resides in memory. Assuming that the contents of ebx is passed as an argument to kmain, we can do this entirely from C.</p><p>The pointer in ebx points to a <em>multiboot</em> structure. Download the multiboot.h file from <a href="http://www.gnu.org/software/grub/manual/multiboot/html_node/multiboot.h.html">http://www.gnu.org/software/grub/manual/multiboot/html_node/multiboot.h.html</a>, which describes the structure.</p><p>The pointer passed to kmain in the ebx register can be cast to a multiboot_info_t pointer. The address of the first module is in the field mods_addr. The following code shows an example:</p><pre>int kmain(/* additional arguments */ unsigned int ebx)<br>    {<br>        multiboot_info_t *mbinfo = (multiboot_info_t *) ebx;<br>        unsigned int address_of_module = mbinfo-&gt;mods_addr;<br>    }</pre><p>However, before just blindly following the pointer, you should check that the module got loaded correctly by GRUB. This can be done by checking the flags field of the multiboot_info_t structure. You should also check the field mods_count to make sure it is exactly 1. For more details about the multiboot structure, see the multiboot documentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*prbPQ3ng19JG9Y_U.jpg" /></figure><h3>Jumping to the Code</h3><p>The only thing left to do is to jump to the code loaded by GRUB. Since it is easier to parse the multiboot structure in C than assembly code, calling the code from C is more convenient (it can of course be done with jmp or call in assembly code as well). The C code could look like this:</p><pre>typedef void (*call_module_t)(void);<br>    /* ... */<br>    call_module_t start_program = (call_module_t) address_of_module;<br>    start_program();<br>    /* we&#39;ll never get here, unless the module code returns */</pre><p>If we start the kernel, wait until it has run and entered the infinite loop in the program, and then halt Bochs, we should see 0xDEADBEEF in the register eax via the Bochs log. We have successfully started a program in our OS!</p><p>In this chapter we can lastly see about the beginning of user mode.</p><h3>The Beginning of User Mode</h3><p>The program we’ve written now runs at the same privilege level as the kernel — we’ve just entered it in a somewhat peculiar way. To enable applications to execute at a different privilege level we’ll need to, beside segmentation, do paging and page frame allocation.</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=414a631893d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of an Operating System( 5-Interrupts and Inputs)]]></title>
            <link>https://lahiruchathuranga-85477.medium.com/implementation-of-an-operating-system-interrupts-and-inputs-b4e10d2e2d5?source=rss-a6ce32d56b94------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4e10d2e2d5</guid>
            <dc:creator><![CDATA[Lahiru Chathuranga]]></dc:creator>
            <pubDate>Fri, 20 Aug 2021 14:47:55 GMT</pubDate>
            <atom:updated>2021-08-27T12:04:15.262Z</atom:updated>
            <content:encoded><![CDATA[<p>This is my fifth article of my article series about Implementation of an operating system. And in this article I will talk about Interrupts and Inputs in an operating system.</p><p>If you new to my series fist you must read in in beginning. Because if you don’t read it in beginning then you couldn’t understand what am I say now, In <a href="https://lahiruchathuranga-85477.medium.com/implementing-a-simple-operating-system-booting-the-os-6fd45a30908b"><em>here</em></a> you can go to first one.</p><p>First I talk about Interrupts Handlers,</p><h3>Interrupts Handlers.</h3><p>Interrupts are handled via the <em>Interrupt Descriptor Table</em> (IDT). The IDT describes a handler for each interrupt. The interrupts are numbered (0–255) and the handler for interrupt <em>i</em> is defined at the <em>ith</em> position in the table. There are three different kinds of handlers for interrupts:</p><ul><li>Task handler</li><li>Interrupt handler</li><li>Trap handler</li></ul><p>The task handlers use functionality specific to the Intel version of x86, so they won’t be covered here (see the Intel manual [33], chapter 6, for more info). The only difference between an interrupt handler and a trap handler is that the interrupt handler disables interrupts, which means you cannot get an interrupt while at the same time handling an interrupt. In this book, we will use trap handlers and disable interrupts manually when we need to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tuqAdki07z0cTF85.png" /></figure><h3>Creating an Entry in the IDT</h3><p>An entry in the IDT for an interrupt handler consists of 64 bits. The highest 32 bits are shown in the figure below:</p><pre>Bit:     | 31              16 | 15 | 14 13 | 12 | 11 | 10 9 8 | 7 6 5 | 4 3 2 1 0 |<br>Content: | offset high        | P  | DPL   | 0  | D  | 1  1 0 | 0 0 0 | reserved  |</pre><p>The lowest 32 bits are presented in the following figure:</p><pre>Bit:     | 31              16 | 15              0 |<br>Content: | segment selector   | offset low        |</pre><p>A description for each name can be found in the table below:</p><p>NameDescriptionoffset highThe 16 highest bits of the 32 bit address in the segment.offset lowThe 16 lowest bits of the 32 bits address in the segment.pIf the handler is present in memory or not (1 = present, 0 = not present).DPLDescriptor Privilige Level, the privilege level the handler can be called from (0, 1, 2, 3).DSize of gate, (1 = 32 bits, 0 = 16 bits).segment selectorThe offset in the GDT.rReserved.</p><p>The offset is a pointer to code (preferably an assembly code label). For example, to create an entry for a handler whose code starts at 0xDEADBEEF and that runs in privilege level 0 (therefore using the same code segment selector as the kernel) the following two bytes would be used:</p><pre>0xDEAD8E00<br>    0x0008BEEF</pre><p>If the IDT is represented as an unsigned integer idt[512] then to register the above example as an handler for interrupt 0 (divide-by-zero), the following code would be used:</p><pre>idt[0] = 0xDEAD8E00<br>    idt[1] = 0x0008BEEF</pre><p>As written in the chapter <a href="https://littleosbook.github.io/#getting-to-c">“Getting to C”</a>, we recommend that you instead of using bytes (or unsigned integers) use packed structures to make the code more readable.</p><h3>Handling an Interrupt</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*i0BvE5-SylH7oLc-" /></figure><p>When an interrupt occurs the CPU will push some information about the interrupt onto the stack, then look up the appropriate interrupt hander in the IDT and jump to it. The stack at the time of the interrupt will look like the following:</p><pre>[esp + 12] eflags<br>    [esp + 8]  cs<br>    [esp + 4]  eip<br>    [esp]      error code?The C handler should get the state of the registers, the state of the stack and the number of the interrupt as arguments. The following definitions can for example be used:</pre><pre>struct cpu_state {<br>        unsigned int eax;<br>        unsigned int ebx;<br>        unsigned int ecx;<br>        .<br>        .<br>        .<br>        unsigned int esp;<br>    } __attribute__((packed));<br><br>    struct stack_state {<br>        unsigned int error_code;<br>        unsigned int eip;<br>        unsigned int cs;<br>        unsigned int eflags;<br>    } __attribute__((packed));<br><br>    void interrupt_handler(struct cpu_state cpu, struct stack_state stack, unsigned int interrupt);</pre><h3>Creating a Generic Interrupt Handler</h3><p>Since the CPU does not push the interrupt number on the stack it is a little tricky to write a generic interrupt handler. This section will use macros to show how it can be done. Writing one version for each interrupt is tedious — it is better to use the macro functionality of NASM [34]. And since not all interrupts produce an error code the value 0 will be added as the “error code” for interrupts without an error code. The following code shows an example of how this can be done:</p><pre>%macro no_error_code_interrupt_handler %1<br>    global interrupt_handler_%1<br>    interrupt_handler_%1:<br>        push    dword 0                     ; push 0 as error code<br>        push    dword %1                    ; push the interrupt number<br>        jmp     common_interrupt_handler    ; jump to the common handler<br>    %endmacro</pre><pre>    %macro error_code_interrupt_handler %1<br>    global interrupt_handler_%1<br>    interrupt_handler_%1:<br>        push    dword %1                    ; push the interrupt number<br>        jmp     common_interrupt_handler    ; jump to the common handler<br>    %endmacro</pre><pre>    common_interrupt_handler:               ; the common parts of the generic interrupt handler<br>        ; save the registers<br>        push    eax<br>        push    ebx<br>        .<br>        .<br>        .<br>        push    ebp</pre><pre>        ; call the C function<br>        call    interrupt_handler</pre><pre>        ; restore the registers<br>        pop     ebp<br>        .<br>        .<br>        .<br>        pop     ebx<br>        pop     eax</pre><pre>        ; restore the esp<br>        add     esp, 8</pre><pre>        ; return to the code that got interrupted<br>        iret</pre><pre>    no_error_code_interrupt_handler 0       ; create handler for interrupt 0<br>    no_error_code_interrupt_handler 1       ; create handler for interrupt 1<br>    .<br>    .<br>    .<br>    error_code_handler              7       ; create handler for interrupt 7<br>    .<br>    .<br>    .</pre><p>The common_interrupt_handler does the following:</p><ul><li>Push the registers on the stack.</li><li>Call the C function interrupt_handler.</li><li>Pop the registers from the stack.</li><li>Add 8 to esp (because of the error code and the interrupt number pushed earlier).</li><li>Execute iret to return to the interrupted code.</li></ul><p>Since the macros declare global labels the addresses of the interrupt handlers can be accessed from C or assembly code when creating the IDT.</p><h3>Loading the IDT</h3><p>The IDT is loaded with the lidt assembly code instruction which takes the address of the first element in the table. It is easiest to wrap this instruction and use it from C:</p><pre>global  load_idt</pre><pre>    ; load_idt - Loads the interrupt descriptor table (IDT).<br>    ; stack: [esp + 4] the address of the first entry in the IDT<br>    ;        [esp    ] the return address<br>    load_idt:<br>        mov     eax, [esp+4]    ; load the address of the IDT into register eax<br>        lidt    eax             ; load the IDT<br>        ret                     ; return to the calling function</pre><h3>Programmable Interrupt Controller (PIC)</h3><p>To start using hardware interrupts you must first configure the Programmable Interrupt Controller (PIC). The PIC makes it possible to map signals from the hardware to interrupts. The reasons for configuring the PIC are:</p><ul><li>Remap the interrupts. The PIC uses interrupts 0–15 for hardware interrupts by default, which conflicts with the CPU interrupts. Therefore the PIC interrupts must be remapped to another interval.</li><li>Select which interrupts to receive. You probably don’t want to receive interrupts from all devices since you don’t have code that handles these interrupts anyway.</li><li>Set up the correct mode for the PIC.</li></ul><p>In the beginning there was only one PIC (PIC 1) and eight interrupts. As more hardware were added, 8 interrupts were too few. The solution chosen was to chain on another PIC (PIC 2) on the first PIC (see interrupt 2 on PIC 1).</p><p>The hardware interrupts are shown in the table below:</p><p>PIC 1HardwarePIC 2Hardware0Timer8Real Time Clock1Keyboard9General I/O2PIC 210General I/O3COM 211General I/O4COM 112General I/O5LPT 213Coprocessor6Floppy disk14IDE Bus7LPT 115IDE Bus</p><p>A great tutorial for configuring the PIC can be found at the SigOPS website [35]. We won’t repeat that information here.</p><p>Every interrupt from the PIC has to be acknowledged — that is, sending a message to the PIC confirming that the interrupt has been handled. If this isn’t done the PIC won’t generate any more interrupts.</p><p>Acknowledging a PIC interrupt is done by sending the byte 0x20 to the PIC that raised the interrupt. Implementing a pic_acknowledge function can thus be done as follows:</p><pre>#include &quot;io.h&quot;</pre><pre>    #define PIC1_PORT_A 0x20<br>    #define PIC2_PORT_A 0xA0</pre><pre>    /* The PIC interrupts have been remapped */<br>    #define PIC1_START_INTERRUPT 0x20<br>    #define PIC2_START_INTERRUPT 0x28<br>    #define PIC2_END_INTERRUPT   PIC2_START_INTERRUPT + 7</pre><pre>    #define PIC_ACK     0x20</pre><pre>    /** pic_acknowledge:<br>     *  Acknowledges an interrupt from either PIC 1 or PIC 2.<br>     *<br>     *  @param num The number of the interrupt<br>     */<br>    void pic_acknowledge(unsigned integer interrupt)<br>    {<br>        if (interrupt &lt; PIC1_START_INTERRUPT || interrupt &gt; PIC2_END_INTERRUPT) {<br>          return;<br>        }</pre><pre>        if (interrupt &lt; PIC2_START_INTERRUPT) {<br>          outb(PIC1_PORT_A, PIC_ACK);<br>        } else {<br>          outb(PIC2_PORT_A, PIC_ACK);<br>        }<br>    }</pre><h3>Reading Input from the Keyboard</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/0*1ISwYpchjlhnF7DF.png" /></figure><p>The keyboard does not generate ASCII characters, it generates scan codes. A scan code represents a button — both presses and releases. The scan code representing the just pressed button can be read from the keyboard’s data I/O port which has address 0x60. How this can be done is shown in the following example:</p><pre>#include &quot;io.h&quot;</pre><pre>    #define KBD_DATA_PORT   0x60</pre><pre>    /** read_scan_code:<br>     *  Reads a scan code from the keyboard<br>     *<br>     *  @return The scan code (NOT an ASCII character!)<br>     */<br>    unsigned char read_scan_code(void)<br>    {<br>        return inb(KBD_DATA_PORT);<br>    }</pre><p>The next step is to write a function that translates a scan code to the corresponding ASCII character. If you want to map the scan codes to ASCII characters as is done on an American keyboard then Andries Brouwer has a great tutorial [36].</p><p>Remember, since the keyboard interrupt is raised by the PIC, you must call pic_acknowledge at the end of the keyboard interrupt handler. Also, the keyboard will not send you any more interrupts until you read the scan code from the keyboard.</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4e10d2e2d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of an Operating System(4-Segmentation)…]]></title>
            <link>https://lahiruchathuranga-85477.medium.com/implementation-of-an-operating-system-segmentation-99f6281bbf7a?source=rss-a6ce32d56b94------2</link>
            <guid isPermaLink="false">https://medium.com/p/99f6281bbf7a</guid>
            <dc:creator><![CDATA[Lahiru Chathuranga]]></dc:creator>
            <pubDate>Fri, 13 Aug 2021 13:59:54 GMT</pubDate>
            <atom:updated>2021-08-27T12:02:38.963Z</atom:updated>
            <content:encoded><![CDATA[<p>If you new to my series fist you must read in in beginning. Because if you don’t read it in beginning then you couldn’t understand what am I say now, In <a href="https://lahiruchathuranga-85477.medium.com/implementing-a-simple-operating-system-booting-the-os-6fd45a30908b"><em>here</em></a> you can go to first one.</p><p>This chapter I will explain how to Segmentation in x86. Segmentation in x86 means accessing the memory through segments. In Operating Systems, Segmentation is a memory management technique in which the memory is divided into the variable size parts. Each part is known as a segment which can be allocated to a process. The details about each segment are stored in a table called a segment table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*NOs8_tHBxmR8ej8w.png" /></figure><p>To enable segmentation you need to set up a table that describes each segment. There are two types of descriptor tables,</p><ol><li>The <em>Global Descriptor Table</em> (GDT).</li><li><em>Local Descriptor Tables</em> (LDT).</li></ol><p>An LDT is set up and managed by user-space processes, and all processes have their own LDT.</p><h3>Accessing Memory</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/0*GCj6GTb3hOULHfuP.jpg" /></figure><p>Most of the time when accessing memory there is no need to explicitly specify the segment to use. The processor has six 16-bit segment registers: cs, ss, ds, es, gs and fs. The register cs is the code segment register and specifies the segment to use when fetching instructions. The register ss is used whenever accessing the stack (through the stack pointer esp), and ds is used for other data accesses. The OS is free to use the registers es, gs and fs however it want.</p><p>Below is an example showing implicit use of the segment registers:</p><pre>func:<br>        <strong>mov</strong> <strong>eax</strong>, [<strong>esp</strong>+4]<br>        <strong>mov</strong> <strong>ebx</strong>, [<strong>eax</strong>]<br>        <strong>add</strong> <strong>ebx</strong>, 8<br>        <strong>mov</strong> [<strong>eax</strong>], <strong>ebx</strong><br>        <strong>ret</strong></pre><p>The above example can be compared with the following one that makes explicit use of the segment registers:</p><pre>func:<br>        <strong>mov</strong> <strong>eax</strong>, [<strong>ss</strong>:<strong>esp</strong>+4]<br>        <strong>mov</strong> <strong>ebx</strong>, [<strong>ds</strong>:<strong>eax</strong>]<br>        <strong>add</strong> <strong>ebx</strong>, 8<br>        <strong>mov</strong> [<strong>ds</strong>:<strong>eax</strong>], <strong>ebx</strong><br>        <strong>ret</strong></pre><p>You don’t need to use ss for storing the stack segment selector, or ds for the data segment selector. You could store the stack segment selector in ds and vice versa. However, in order to use the implicit style shown above, you must store the segment selectors in their indented registers.</p><h3>The Global Descriptor Table (GDT)</h3><p>The GDT can hold things other than segment descriptors as well. Every 8-byte entry in the GDT is a descriptor, but these descriptors can be references not only to memory segments but also to Task State Segment (TSS), Local Descriptor Table (LDT), or Call Gate structures in memory. The last ones, Call Gates, are particularly important for transferring control between x86 privilege levels although this mechanism is not used on most modern operating systems.</p><p>There is also a Local Descriptor Table (LDT). Multiple LDTs can be defined in the GDT, but only one is current at any one time: usually associated with the current Task. While the LDT contains memory segments which are private to a specific program, the GDT contains global segments. The x86 processors have facilities for automatically switching the current LDT on specific machine events, but no facilities for automatically switching the GDT.</p><p>Every memory access which a program can perform always goes through a segment. On the 80386 processor and later, because of 32-bit segment offsets and limits, it is possible to make segments cover the entire addressable memory, which makes segment-relative addressing transparent to the user.</p><p>In order to reference a segment, a program must use its index inside the GDT or the LDT. Such an index is called a segment selector (or selector). The selector must generally be loaded into a segment register to be used. Apart from the machine instructions which allow one to set/get the position of the GDT, and of the Interrupt Descriptor Table (IDT), in memory, every machine instruction referencing memory has an implicit Segment Register, occasionally two. Most of the time this Segment Register can be overridden by adding a Segment Prefix before the instruction.</p><p>Loading a selector into a segment register automatically reads the GDT or the LDT and stores the properties of the segment inside the processor itself. Subsequent modifications to the GDT or LDT will not be effective unless the segment register is reloaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/0*rUtwKIv0h_-qhFu0.png" /></figure><p>Now we can see how to loading the GDT.</p><h3>Loading the GDT</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EaKw8MCsHbB2RumS.jpg" /></figure><p>Loading the GDT into the processor is done with the lgdt assembly code instruction, which takes the address of a struct that specifies the start and size of the GDT. It is easiest to encode this information using a <a href="https://littleosbook.github.io/#packing-structs">“packed struct”</a> as shown in the following example:</p><pre><strong>struct</strong> gdt {<br>        unsigned int address;<br>        unsigned short size;<br>    } __attribute__((packed));</pre><p>If the content of the eax register is the address to such a struct, then the GDT can be loaded with the assembly code shown below:</p><pre><strong>lgdt</strong> [<strong>eax</strong>]</pre><p>It might be easier if you make this instruction available from C, the same way as was done with the assembly code instructions in and out.</p><p>After the GDT has been loaded the segment registers needs to be loaded with their corresponding segment selectors. The content of a segment selector is described in the figure and table below:</p><pre>Bit:     | 15                                3 | 2  | 1 0 |<br>Content: | offset (index)                      | ti | rpl |</pre><p>The layout of segment selectors.NameDescriptionrplRequested Privilege Level — we want to execute in PL0 for now.tiTable Indicator. 0 means that this specifies a GDT segment, 1 means an LDT Segment.offset (index)Offset within descriptor table.</p><p>The offset of the segment selector is added to the start of the GDT to get the address of the segment descriptor: 0x08 for the first descriptor and 0x10 for the second, since each descriptor is 8 bytes. The Requested Privilege Level (RPL) should be 0 since the kernel of the OS should execute in privilege level 0.</p><p>Loading the segment selector registers is easy for the data registers — just copy the correct offsets to the registers:</p><pre><strong>mov</strong> <strong>ds</strong>, 0x10<br>    <strong>mov</strong> <strong>ss</strong>, 0x10<br>    <strong>mov</strong> <strong>es</strong>, 0x10<br>    .<br>    .<br>    .</pre><p>To load cs we have to do a “far jump”:</p><pre><em>; code here uses the previous cs</em><br>    <strong>jmp</strong> 0x08:flush_cs   <em>; specify cs when jumping to flush_cs</em></pre><pre>    flush_cs:<br>        <em>; now we&#39;ve changed cs to 0x08</em></pre><p>A far jump is a jump where we explicitly specify the full 48-bit logical address: the segment selector to use and the absolute address to jump to. It will first set cs to 0x08 and then jump to flush_cs using its absolute address.</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99f6281bbf7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of an Operating System(3-Play with Outputs)]]></title>
            <link>https://lahiruchathuranga-85477.medium.com/kk-d12638cbac7c?source=rss-a6ce32d56b94------2</link>
            <guid isPermaLink="false">https://medium.com/p/d12638cbac7c</guid>
            <dc:creator><![CDATA[Lahiru Chathuranga]]></dc:creator>
            <pubDate>Fri, 06 Aug 2021 16:26:05 GMT</pubDate>
            <atom:updated>2021-08-27T12:00:07.442Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/710/0*j4H5Rn3JGJjjuQyA.jpg" /></figure><p>In this chapter I will write about “how we can get a output to display”.</p><p>If you new to my series fist you must read in in beginning. Because if you don’t read it in beginning then you couldn’t understand what am I say now, In <a href="https://lahiruchathuranga-85477.medium.com/implementing-a-simple-operating-system-booting-the-os-6fd45a30908b"><em>here</em></a> you can go to first one.</p><h3>Interacting with the Hardware</h3><p>There are usually two different ways to interact with the hardware, <em>memory-mapped I/O</em> and <em>I/O ports</em>.</p><p>If the hardware uses memory-mapped I/O then you can write to a specific memory address and the hardware will be updated with the new data. One example of this is the framebuffer, which will be discussed in more detail later. For example, if you write the value 0x410F to address 0x000B8000, you will see the letter A in white color on a black background.</p><h3>The Framebuffer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/0*43Y4GAFwhxcsXm1i.gif" /></figure><p>The framebuffer is a hardware device that is capable of displaying a buffer of memory on the screen [26]. The framebuffer has 80 columns and 25 rows, and the row and column indices start at 0 (so rows are labelled 0–24).</p><h3>Writing Text</h3><p>Writing text to the console via the framebuffer is done with memory-mapped I/O. The starting address of the memory-mapped I/O for the framebuffer is 0x000B8000 [27]. The memory is divided into 16 bit cells, where the 16 bits determine both the character, the foreground color and the background color. The highest eight bits is the ASCII [28] value of the character, bit 7 - 4 the background and bit 3 - 0 the foreground, as can be seen in the following figure:</p><pre>Bit:     | 15 14 13 12 11 10 9 8 | 7 6 5 4 | 3 2 1 0 |<br>Content: | ASCII                 | FG      | BG      |</pre><p>The following code shows how this can be wrapped into a function in kmain.c file:</p><pre><em>/** fb_write_cell:</em><br><em>     *  Writes a character with the given foreground and background to position i</em><br><em>     *  in the framebuffer.</em><br><em>     *</em><br><em>     *  </em><strong>@param</strong><em> </em><strong>i</strong><em>  The location in the framebuffer</em><br><em>     *  </em><strong>@param</strong><em> </em><strong>c</strong><em>  The character</em><br><em>     *  </em><strong>@param</strong><em> </em><strong>fg</strong><em> The foreground color</em><br><em>     *  </em><strong>@param</strong><em> </em><strong>bg</strong><em> The background color</em><br><em>     */</em><br>    void fb_write_cell(unsigned int i, char c, unsigned char fg, unsigned char bg)<br>    {<br>        fb[i] = c;<br>        fb[i + 1] = ((fg &amp; 0x0F) &lt;&lt; 4) | (bg &amp; 0x0F)<br>    }</pre><p>The function can then be used as follows in function called kmain:</p><pre>int kmain(){</pre><pre>    #define FB_GREEN     2<br>    #define FB_DARK_GREY 8</pre><pre>fb_write_cell(0, &#39;A&#39;, FB_GREEN, FB_DARK_GREY);<br>return 0;</pre><pre>}</pre><h3>Moving the Cursor</h3><pre><strong>global</strong> outb             <em>; make the label outb visible outside this file</em><br><br>    <em>; outb - send a byte to an I/O port</em><br>    <em>; stack: [esp + 8] the data byte</em><br>    <em>;        [esp + 4] the I/O port</em><br>    <em>;        [esp    ] return address</em><br>    outb:<br>        <strong>mov</strong> <strong>al</strong>, [<strong>esp</strong> + 8]    <em>; move the data to be sent into the al register</em><br>        <strong>mov</strong> <strong>dx</strong>, [<strong>esp</strong> + 4]    <em>; move the address of the I/O port into the dx register</em><br>        <strong>out</strong> <strong>dx</strong>, <strong>al</strong>           <em>; send the data to the I/O port</em><br>        <strong>ret</strong>                  <em>; return to the calling function</em></pre><p>First we should save the above data in io.s file and below data in io.h file.</p><pre>#ifndef INCLUDE_IO_H<br>    #define INCLUDE_IO_H<br><br>    <em>/** outb:</em><br><em>     *  Sends the given data to the given I/O port. Defined in io.s</em><br><em>     *</em><br><em>     *  </em><strong>@param</strong><em> </em><strong>port</strong><em> The I/O port to send the data to</em><br><em>     *  </em><strong>@param</strong><em> </em><strong>data</strong><em> The data to send to the I/O port</em><br><em>     */</em><br>    void outb(unsigned short port, unsigned char data);<br><br>    #endif <em>/* INCLUDE_IO_H */</em></pre><p>Then the kmain.c file should update with below data.</p><pre>#include &quot;io.h&quot;<br><br>    <em>/* The I/O ports */</em><br>    #define FB_COMMAND_PORT         0x3D4<br>    #define FB_DATA_PORT            0x3D5<br><br>    <em>/* The I/O port commands */</em><br>    #define FB_HIGH_BYTE_COMMAND    14<br>    #define FB_LOW_BYTE_COMMAND     15<br><br>    <em>/** fb_move_cursor:</em><br><em>     *  Moves the cursor of the framebuffer to the given position</em><br><em>     *</em><br><em>     *  </em><strong>@param</strong><em> </em><strong>pos</strong><em> The new position of the cursor</em><br><em>     */</em><br>    void fb_move_cursor(unsigned short pos)<br>    {<br>        outb(FB_COMMAND_PORT, FB_HIGH_BYTE_COMMAND);<br>        outb(FB_DATA_PORT,    ((pos &gt;&gt; 8) &amp; 0x00FF));<br>        outb(FB_COMMAND_PORT, FB_LOW_BYTE_COMMAND);<br>        outb(FB_DATA_PORT,    pos &amp; 0x00FF);<br>    }</pre><h3>The Driver</h3><p>The driver should provide an interface that the rest of the code in the OS will use for interacting with the framebuffer. There is no right or wrong in what functionality the interface should provide, but a suggestion is to have a write function with the following declaration:</p><pre>int write(char *buf, unsigned int len);</pre><p>The write function writes the contents of the buffer buf of length len to the screen. The write function should automatically advance the cursor after a character has been written and scroll the screen if necessary.</p><h3>The Serial Ports</h3><p>The serial port [30] is an interface for communicating between hardware devices and although it is available on almost all motherboards, it is seldom exposed to the user in the form of a DE-9 connector nowadays. The serial port is easy to use, and, more importantly, it can be used as a logging utility in Bochs. If a computer has support for a serial port, then it usually has support for multiple serial ports, but we will only make use of one of the ports. This is because we will only use the serial ports for logging. Furthermore, we will only use the serial ports for output, not input. The serial ports are completely controlled via I/O ports.</p><h3>4.3.1 Configuring the Serial Port</h3><p>The first data that need to be sent to the serial port is configuration data. In order for two hardware devices to be able to talk to each other they must agree upon a couple of things. These things include:</p><ul><li>The speed used for sending data (bit or baud rate)</li><li>If any error checking should be used for the data (parity bit, stop bits)</li><li>The number of bits that represent a unit of data (data bits).</li></ul><h3>Configuring the Line</h3><p>Configuring the line means to configure how data is being sent over the line. The serial port has an I/O port, the <em>line command port</em>, that is used for configuration.</p><p>Now we can save this data in kmain.c file</p><pre>#include &quot;io.h&quot; <em>/* io.h is implement in the section &quot;Moving the cursor&quot; */</em><br><br>    <em>/* The I/O ports */</em><br><br>    <em>/* All the I/O ports are calculated relative to the data port. This is because</em><br><em>     * all serial ports (COM1, COM2, COM3, COM4) have their ports in the same</em><br><em>     * order, but they start at different values.</em><br><em>     */</em><br><br>    #define SERIAL_COM1_BASE                0x3F8      <em>/* COM1 base port */</em><br><br>    #define SERIAL_DATA_PORT(base)          (base)<br>    #define SERIAL_FIFO_COMMAND_PORT(base)  (base + 2)<br>    #define SERIAL_LINE_COMMAND_PORT(base)  (base + 3)<br>    #define SERIAL_MODEM_COMMAND_PORT(base) (base + 4)<br>    #define SERIAL_LINE_STATUS_PORT(base)   (base + 5)<br><br>    <em>/* The I/O port commands */</em><br><br>    <em>/* SERIAL_LINE_ENABLE_DLAB:</em><br><em>     * Tells the serial port to expect first the highest 8 bits on the data port,</em><br><em>     * then the lowest 8 bits will follow</em><br><em>     */</em><br>    #define SERIAL_LINE_ENABLE_DLAB         0x80<br><br>    <em>/** serial_configure_baud_rate:</em><br><em>     *  Sets the speed of the data being sent. The default speed of a serial</em><br><em>     *  port is 115200 bits/s. The argument is a divisor of that number, hence</em><br><em>     *  the resulting speed becomes (115200 / divisor) bits/s.</em><br><em>     *</em><br><em>     *  </em><strong>@param</strong><em> </em><strong>com</strong><em>      The COM port to configure</em><br><em>     *  </em><strong>@param</strong><em> </em><strong>divisor</strong><em>  The divisor</em><br><em>     */</em><br>    void serial_configure_baud_rate(unsigned short com, unsigned short divisor)<br>    {<br>        outb(SERIAL_LINE_COMMAND_PORT(com),<br>             SERIAL_LINE_ENABLE_DLAB);<br>        outb(SERIAL_DATA_PORT(com),<br>             (divisor &gt;&gt; 8) &amp; 0x00FF);<br>        outb(SERIAL_DATA_PORT(com),<br>             divisor &amp; 0x00FF);<br>    }</pre><p>Then this data must save in the kmain.c file.</p><pre><em>/** serial_configure_line:</em><br><em>     *  Configures the line of the given serial port. The port is set to have a</em><br><em>     *  data length of 8 bits, no parity bits, one stop bit and break control</em><br><em>     *  disabled.</em><br><em>     *</em><br><em>     *  </em><strong>@param</strong><em> </em><strong>com</strong><em>  The serial port to configure</em><br><em>     */</em><br>    void serial_configure_line(unsigned short com)<br>    {<br>        <em>/* Bit:     | 7 | 6 | 5 4 3 | 2 | 1 0 |</em><br><em>         * Content: | d | b | prty  | s | dl  |</em><br><em>         * Value:   | 0 | 0 | 0 0 0 | 0 | 1 1 | = 0x03</em><br><em>         */</em><br>        outb(SERIAL_LINE_COMMAND_PORT(com), 0x03);<br>    }</pre><h3>Configuring the Buffers</h3><p>When data is transmitted via the serial port it is placed in buffers, both when receiving and sending data. This way, if you send data to the serial port faster than it can send it over the wire, it will be buffered. However, if you send too much data too fast the buffer will be full and data will be lost. In other words, the buffers are FIFO queues.</p><h3>Configuring the Modem</h3><p>The modem control register is used for very simple hardware flow control via the Ready To Transmit (RTS) and Data Terminal Ready (DTR) pins. When configuring the serial port we want RTS and DTR to be 1, which means that we are ready to send data.</p><h3>Writing Data to the Serial Port</h3><p>Writing data to the serial port is done via the data I/O port. However, before writing, the transmit FIFO queue has to be empty (all previous writes must have finished). The transmit FIFO queue is empty if bit 5 of the line status I/O port is equal to one.</p><p>Reading the contents of an I/O port is done via the in assembly code instruction. There is no way to use the in assembly code instruction from C, therefore it has to be wrapped (the same way as the out assembly code instruction):</p><pre><strong>global</strong> inb</pre><pre>    <em>; inb - returns a byte from the given I/O port</em><br>    <em>; stack: [esp + 4] The address of the I/O port</em><br>    <em>;        [esp    ] The return address</em><br>    inb:<br>        <strong>mov</strong> <strong>dx</strong>, [<strong>esp</strong> + 4]       <em>; move the address of the I/O port to the dx register</em><br>        <strong>in</strong>  <strong>al</strong>, <strong>dx</strong>              <em>; read a byte from the I/O port and store it in the al register</em><br>        <strong>ret</strong>                     <em>; return the read byte</em></pre><pre><em>/* in file io.h */</em></pre><pre>    <em>/** inb:</em><br><em>     *  Read a byte from an I/O port.</em><br><em>     *</em><br><em>     *  </em><strong>@param</strong><em>  </em><strong>port</strong><em> The address of the I/O port</em><br><em>     *  </em><strong>@return</strong><em>      The read byte</em><br><em>     */</em><br>    unsigned char inb(unsigned short port);</pre><p>Checking if the transmit FIFO is empty can then be done from C:</p><pre>#include &quot;io.h&quot;</pre><pre>    <em>/** serial_is_transmit_fifo_empty:</em><br><em>     *  Checks whether the transmit FIFO queue is empty or not for the given COM</em><br><em>     *  port.</em><br><em>     *</em><br><em>     *  </em><strong>@param</strong><em>  </em><strong>com</strong><em> The COM port</em><br><em>     *  </em><strong>@return</strong><em> 0 if the transmit FIFO queue is not empty</em><br><em>     *          1 if the transmit FIFO queue is empty</em><br><em>     */</em><br>    int serial_is_transmit_fifo_empty(unsigned int com)<br>    {<br>        <em>/* 0x20 = 0010 0000 */</em><br>        <strong>return</strong> inb(SERIAL_LINE_STATUS_PORT(com)) &amp; 0x20;<br>    }</pre><p>Writing to a serial port means spinning as long as the transmit FIFO queue isn’t empty, and then writing the data to the data I/O port.</p><h3>Configuring Bochs</h3><p>To save the output from the first serial serial port the Bochs configuration file bochsrc.txt must be updated. The com1 configuration instructs Bochs how to handle first serial port.</p><h3>The Driver</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/0*czAngSEnt6NWx3Cr.jpg" /></figure><p>We recommend that you implement a write function for the serial port similar to the write function in the driver for the framebuffer. To avoid name clashes with the write function for the framebuffer it is a good idea to name the functions fb_write and serial_write to distinguish them.</p><p>Thank you!</p><p>References :</p><h3>The little book about OS development</h3><h3>Erik Helin, Adam Renberg;</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d12638cbac7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>