<?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 Nethmini Devyanjalee on Medium]]></title>
        <description><![CDATA[Stories by Nethmini Devyanjalee on Medium]]></description>
        <link>https://medium.com/@nethminid1999?source=rss-6b0a279af35d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zzxs5R21JjfGNMhVXptKBA.png</url>
            <title>Stories by Nethmini Devyanjalee on Medium</title>
            <link>https://medium.com/@nethminid1999?source=rss-6b0a279af35d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:34:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nethminid1999/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[Structures, Classes, and Protocols in Swift]]></title>
            <link>https://medium.com/@nethminid1999/structures-classes-and-protocols-in-swift-19947fd26ee9?source=rss-6b0a279af35d------2</link>
            <guid isPermaLink="false">https://medium.com/p/19947fd26ee9</guid>
            <category><![CDATA[swift-class]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift-protocol]]></category>
            <category><![CDATA[swift-struct]]></category>
            <dc:creator><![CDATA[Nethmini Devyanjalee]]></dc:creator>
            <pubDate>Wed, 25 May 2022 21:07:46 GMT</pubDate>
            <atom:updated>2022-05-25T21:07:46.496Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vRij9Hfzux7tRD0CdR96Ag.jpeg" /></figure><p>Swift is an open-source multi-paradigm programming language for iPadOS, macOS, tvOS, watchOS, and iOS development. Apple established it in 2014 to provide developers with a strong language for creating iOS apps. Swift.org claims that the language was created to be safe, quick, and expressive. It’s designed to take the place of C-based languages. The Swift programming language is constantly evolving, and the Swift community is growing. The Swift source code is available on GitHub, making it accessible.</p><p>Class and structure are the roots of your iOS development. So let’s explore those two first.</p><h3>Swift Structures</h3><p>Swift structures are the flexible basic building blocks of the programs. We can extend the functionality of structures by defining the different types of properties and methods. The struct keyword is used to define structures.</p><p>A structure is used to store variables of different data types. They are used to encapsulate simple data values and to copy the encapsulated data and its associated properties by ‘values’ rather than by ‘references’.This means each instance of a struct will have an independent copy of data.</p><p>Syntax:</p><pre>struct StructureName {<br>  // structure definition <br>}</pre><h3>Swift Classes</h3><p>Classes in Swift are similar to Structures in Swift. A class is considered a blueprint of objects. We can define classes using classkeyword and define the properties, and methods in classes same as constants, variables, and functions.</p><p>Class is the concept of object-oriented programming. So, it provides some OOP features like Inheritance where we can derive a new class from the existing class. Classes are of reference type. This means each instance of a class shares the same copy of data. It offers you Type casting which you can use to check in runtime. Deinitializers in classes will take care of memory management by releasing unused resources. Reference counting allows the class instance to have more than one reference.</p><p>Syntax:</p><pre>class ClassName {<br>  // class definition <br>}</pre><h3>Swift Protocols</h3><p>In Swift, a protocol defines a blueprint of methods or properties that can then be adopted by classes. It is just described as a methods or properties skeleton instead of implementation. Also, it is used to specify whether the property is ‘gettable’ or ‘settable’. Methods and properties implementation can further be done by defining classes, functions, and enumerations. Any type that satisfies the requirements of a protocol is said to <em>conform</em> to that protocol. We use the protocol keyword to define a protocol.</p><p>Similar to classes, protocols can inherit other protocols. You can write extensions on your protocols that provide default implementations of the methods. Protocols formalize the connection between different parts of your code, without providing implementations. This allows you to build rigid structures in your code, without tightly coupling your code’s components.</p><p>Syntax:</p><pre>protocol SomeProtocol {<br>// protocol definition<br>}</pre><p>This is the end of this article, Hope you liked this!</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19947fd26ee9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make your own Operating System#9]]></title>
            <link>https://medium.com/@nethminid1999/make-your-own-operating-system-9-1b731fdd7597?source=rss-6b0a279af35d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b731fdd7597</guid>
            <category><![CDATA[user-mode]]></category>
            <category><![CDATA[operating-systems]]></category>
            <dc:creator><![CDATA[Nethmini Devyanjalee]]></dc:creator>
            <pubDate>Mon, 27 Sep 2021 17:26:13 GMT</pubDate>
            <atom:updated>2021-11-10T18:08:44.171Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CBw3uNxNJqtdBs5YdkGzkA.jpeg" /></figure><p><em>Hello everyone!</em></p><p>This is the 9th article of my ‘Make you own Operating System” article series. In this article, I will talk about how to run a simple program in user mode.</p><h3>User Mode</h3><p>User mode is now almost within our reach, there are just a few more steps required to get there.</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.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/0*5jSgtnJ1Sys2Fq4X.png" /><figcaption>The segment descriptors needed for user mode</figcaption></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><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 grown and shrunk 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><h3>Entering User Mode</h3><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 <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</pre><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 set up for the user-mode process.</p><p>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 the 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. 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 be 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.</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. 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.</p><h3>Using C for User Mode Programs</h3><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 as the file format for the kernel executable is that 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.</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, mainmight 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 shows an example of a linker script that places these instructions first in executable.</p><pre>OUTPUT_FORMAT(&quot;binary&quot;)    /* output flat binary */<br><br>SECTIONS<br>{<br>  . = 0;                 /* relocate to address 0 */<br><br>  .text ALIGN(4):<br>  {<br>    start.o(.text)     /* include the .text section of start.o */<br>    *(.text)           /* include all other .text sections */<br>  }<br><br>  .data ALIGN(4):<br>  {<br>    *(.data)<br>  }<br><br>  .rodata ALIGN(4):<br>  {<br>    *(.rodata*)<br>  }<br> }</pre><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.</p><p>When we compile user programs we want the following GCC flags:</p><pre>-m32 -nostdlib -nostdinc -fno-builtin -fno-stack-protector -nostartfiles -nodefaultlibs</pre><p>For linking, the followings flags should be used:</p><pre>-T link.ld -melf_i386  # emulate32bitsELF,thebinaryoutputisspecified<br>                       # in the linker script</pre><p>The option -T instructs the linker to use the linker script link.ld.</p><p>— Create new files as ‘start_user_program.s’, ‘link_user_program.ld’, ‘hardware_interrupt_enabler.h’, ‘hardware_interrupt_enabler.s’, ‘user_program.c’, ‘ user_mode.h’, ‘user_mode.c’, and ‘user_mode.s’.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88febd58ff55e460ba57330bf695296d/href">https://medium.com/media/88febd58ff55e460ba57330bf695296d/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/427b62794e260c35da474fed688014c6/href">https://medium.com/media/427b62794e260c35da474fed688014c6/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3134de16629ddfda651abb08a4cffcf0/href">https://medium.com/media/3134de16629ddfda651abb08a4cffcf0/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5bbf6501eae702aac30519fc2be2358/href">https://medium.com/media/d5bbf6501eae702aac30519fc2be2358/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af31b359aad0ecde814e065ad71abf63/href">https://medium.com/media/af31b359aad0ecde814e065ad71abf63/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2687dd45475dc152655261c3d5cc3062/href">https://medium.com/media/2687dd45475dc152655261c3d5cc3062/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40263f00457a3b3b63ae82fe9dfb5b63/href">https://medium.com/media/40263f00457a3b3b63ae82fe9dfb5b63/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/daf6b13f3ddb762611487c4eabfe5462/href">https://medium.com/media/daf6b13f3ddb762611487c4eabfe5462/href</a></iframe><p>— Updated ‘kmain.c’ file and ‘memory_segments.c’ file should look like,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddac78cdb33655b0c16a8c64ccdb2e6f/href">https://medium.com/media/ddac78cdb33655b0c16a8c64ccdb2e6f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b19a6da6c4557de65392a6f5210a0c3b/href">https://medium.com/media/b19a6da6c4557de65392a6f5210a0c3b/href</a></iframe><p>If everything has been set upright, we should now have a kernel that can enter user mode.</p><p>You can refer to my Github for further clarification.</p><p><a href="https://github.com/NethminiDevyanjalee/myFirstOS/tree/user_modes">GitHub - NethminiDevyanjalee/myFirstOS at user_modes</a></p><p>We will see about <em>File Systems</em> in the next article “Make your own Operating System#10”.</p><p>Hope to see you in the next article as well!</p><p>Reference: <a href="https://littleosbook.github.io/">The Little OS Book</a></p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b731fdd7597" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make your own Operating System#8]]></title>
            <link>https://medium.com/@nethminid1999/make-your-own-operating-system-8-efb78a3a00ac?source=rss-6b0a279af35d------2</link>
            <guid isPermaLink="false">https://medium.com/p/efb78a3a00ac</guid>
            <category><![CDATA[kernel]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Nethmini Devyanjalee]]></dc:creator>
            <pubDate>Fri, 10 Sep 2021 18:15:56 GMT</pubDate>
            <atom:updated>2021-11-10T16:31:11.151Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*9KQBcW8jubnC1avr99sang.jpeg" /></figure><p><em>Hello everyone!</em></p><p>This is the 8th article of my ‘Make you own Operating System” article series. In this article, I will talk about page frame allocation.</p><h3>Page Frame Allocation</h3><p>When using virtual memory, how does the OS know which parts of memory are free to use? That is the role of the page frame allocator.</p><h3>Managing Available Memory</h3><h4><strong>How Much Memory is There?</strong></h4><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 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 the 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 */<br><br>. = 0xC0100000     /* the code should be relocated to 3 GB + 1 MB */<br><br>/* these labels get exported to the code files */<br>kernel_virtual_start = .;<br>kernel_physical_start = . - 0xC0000000;<br><br>/* 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>}<br><br>/* 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>}<br><br>/* 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>}<br><br>/* 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>}<br><br>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<br><br>; ...<br><br>push kernel_physical_end<br>push kernel_physical_start<br>push kernel_virtual_end<br>push kernel_virtual_start<br><br>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);<br><br>/* ... */</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><h4>Managing Available Memory</h4><p>How do we know which page frames are in use? The page frame allocator needs to keep track of which are free and which aren’t. There are several ways to do this: bitmaps, linked lists, trees, the Buddy System, etc.</p><p>Bitmaps are quite easy to implement. One bit is used for each page frame and one (or more) page frames are dedicated to storing the bitmap.</p><h3>How Can We Access a Page Frame?</h3><p>The page frame allocator returns the physical start address of the page frame. This page frame is not mapped in — no page table points to this page frame. How can we read and write data to the frame?</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 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><h3>A Kernel Heap</h3><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>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>— Now your ‘paging.c’ file should update like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95699a9cfdaf9648d5f656cd68ffad2c/href">https://medium.com/media/95699a9cfdaf9648d5f656cd68ffad2c/href</a></iframe><p>— Now you can run the command make run. You won’t see any visible changes on the screen: this is an internal change.</p><p>If everything is okay. Well done!</p><p>You can refer to my Github for further clarification.</p><p><a href="https://github.com/NethminiDevyanjalee/myFirstOS/tree/page_frame_allocation">GitHub - NethminiDevyanjalee/myFirstOS at page_frame_allocation</a></p><p>We will see about <em>User Mode</em> in the next article “Make your own Operating System#9”.</p><p>Hope to see you in the next article as well!</p><p>Reference: <a href="https://littleosbook.github.io/">The Little OS Book</a></p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efb78a3a00ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make your own Operating System#7]]></title>
            <link>https://medium.com/@nethminid1999/make-your-own-operating-system-7-2b7d093004de?source=rss-6b0a279af35d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b7d093004de</guid>
            <category><![CDATA[paging]]></category>
            <category><![CDATA[virtual-memory]]></category>
            <category><![CDATA[operating-systems]]></category>
            <dc:creator><![CDATA[Nethmini Devyanjalee]]></dc:creator>
            <pubDate>Mon, 06 Sep 2021 17:15:02 GMT</pubDate>
            <atom:updated>2021-09-07T19:16:37.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EQ3DwSHTen41mlekoZ2zFw.png" /></figure><p><em>Hello everyone!</em></p><p>This is the 7th article of my ‘Make you own Operating System” article series. In this article, I will talk about how to enable virtual memory through paging.</p><h4>What is Virtual Memory?</h4><p>Virtual memory 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 physically present in the machine. We also don’t want applications messing with the kernel or other applications’ memory due to security.</p><p>In the x86 architecture, virtual memory can be accomplished in two ways:</p><ul><li>segmentation</li><li>paging</li></ul><h4>Virtual Memory Through Segmentation?</h4><p>Each user-mode process would get its segment, with the base address and limit properly set up. This way no process can see the memory of another process. A problem with this is that the physical memory for a process needs to be contiguous. Either we need to know in advance how much memory the program will require or we can move the memory segments to places where they can grow when the limit is reached. Paging solves both these problems.</p><h4>Virtual Memory Through Paging</h4><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 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><h3>Paging</h3><p>Segmentation translates a logical address into a linear address. Paging translates these linear addresses onto the physical address space and determines access rights and how the memory should be cached.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HgB5NvZTiZtysWIHc-cfxw.jpeg" /></figure><p>Virtual memory through paging means that each process will get the impression that the available memory range is 0x00000000–0xFFFFFFFF even though the actual size of the memory might be much less. It also means that when a process addresses a byte of memory it will use a virtual (linear) address instead of the physical one. The code in the user process won’t notice any difference. The linear address gets translated to a physical address by the MMU and the page table. If the virtual address isn’t mapped to a physical address, the CPU will raise a page fault interrupt.</p><p>Paging is optional, and some operating systems do not make use of it. But if we want to mark certain areas of memory accessible only to code running at a certain privilege level, paging is the neatest way to do it.</p><h3>Paging in x86</h3><p>Paging in x86 consists of a page directory (PDT) that can contain references to 1024 page tables (PT), each of which can point to 1024 sections of physical memory called page frames (PF). Each page frame is 4096 bytes large.</p><p>In a virtual (linear) address, the highest 10 bits specifies the offset of a page directory entry (PDE) in the current PDT, the next 10 bits the offset of a page table entry (PTE) within the page table pointed to by that PDE. The lowest 12 bits in the address is the offset within the page frame to be addressed.</p><p>All page directories, page tables, and page frames need to be aligned on 4096-byte addresses. This makes it possible to address a PDT, PT, or PF with just the highest 20 bits of a 32-bit address since the lowest 12 need to be zero.</p><p>The PDE and PTE structure is very similar to each other: 32 bits (4 bytes), where the highest 20 bits point to a PTE or PF, and the lowest 12 bits control access rights and other configurations. 4 bytes times 1024 equals 4096 bytes, so a page directory and page table both fit in a page frame themselves.</p><p>The translation of linear addresses to physical addresses is described in the figure below.</p><p>While pages are normally 4096 bytes, it is also possible to use 4 MB pages. A PDE then points directly to a 4 MB page frame, which needs to be aligned on a 4 MB address boundary. The address translation is almost the same as in the figure, with just the page table step removed. It is possible to mix 4 MB and 4 KB pages.</p><p>The 20 bits pointing to the current PDT are stored in the register cr3. The lower 12 bits of cr3 are used for configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*soZe3Z_1pJVIbAF9KVAkng.png" /></figure><h3>Identity Paging</h3><p>The simplest kind of paging is when we map each virtual address onto the same physical address, called identity paging. This can be done at compile time by creating a page directory where each entry points to its corresponding 4 MB frame. In NASM this can be done with macros and commands (%rep, times, and dd). It can of course also be done at run-time by using ordinary assembly code instructions.</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<br><br>mov ebx, cr4        ; read current cr4<br>or  ebx, 0x00000010 ; set PSE<br>mov cr4, ebx        ; update cr4<br><br>mov ebx, cr0        ; read current cr0<br>or  ebx, 0x80000000 ; set PG<br>mov cr0, ebx        ; update cr0<br><br>; now paging is enabled</pre><p>— Create a file named ‘paging_enable.s’, and your file should look like,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1d6729cbe927e4c7785ebdc952bee5e/href">https://medium.com/media/f1d6729cbe927e4c7785ebdc952bee5e/href</a></iframe><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.</p><p>An instruction that is useful when updating a PDT or PT is <em>invlpg</em>. It invalidates the Translation Lookaside Buffer (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 <em>invlpg</em> 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><p>— Now run your OS using identity paging before trying to implement a more advanced paging setup, since it can be hard to debug a malfunctioning page table that is set up via assembly code.</p><h3>Paging and the Kernel</h3><p>This section will describe how paging affects the OS kernel.</p><h4>Reasons to Not Identity Map the Kernel</h4><p>If the kernel is placed at the beginning of the virtual address space — that is, the virtual address space (0x00000000, “size of kernel”) maps to the location of the kernel in memory — there will be issues when linking the user-mode process code. Normally, during linking, the linker assumes that the code will be loaded into the memory position 0x00000000. Therefore, when resolving absolute references, 0x00000000 will be the base address for calculating the exact position. But if the kernel is mapped onto the virtual address space (0x00000000, “size of kernel”), the user-mode process cannot be loaded at virtual address 0x00000000 — it must be placed somewhere else. Therefore, the assumption from the linker that the user-mode process is loaded into memory at position 0x00000000 is wrong. This can be corrected by using a linker script that tells the linker to assume a different starting address.</p><p>This also assumes that we want the kernel to be part of the user-mode process’ address space. This is a nice feature since during system calls we don’t have to change any paging structures to get access to the kernel’s code and data.</p><h4>The Virtual Address for the Kernel</h4><p>Preferably, the kernel should be placed at a very high virtual memory address, for example, 0xC0000000 (3 GB). The user-mode process is not likely to be 3 GB large, which is now the only way that it can conflict with the kernel. When the kernel uses virtual addresses at 3 GB and above it is called a higher-half kernel. 0xC0000000 is just an example, the kernel can be placed at any address higher than 0 to get the same benefits. Choosing the correct address depends on how much virtual memory should be available for the kernel (it is easiest if all memory above the kernel virtual address should belong to the kernel) and how much virtual memory should be available for the process.</p><p>If the user-mode process is larger than 3 GB, some pages will need to be swapped out by the kernel.</p><h4>Placing the Kernel at 0xC0000000</h4><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, “size of kernel”) of memory is mapped to the range (0xC0000000, 0xC0000000 + “size of kernel”).</p><p>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. However, we want the jumps to be resolved using 0xC0100000 as the base address since otherwise, a kernel jump will jump straight into the user-mode process code.</p><p>However, we can’t simply tell the linker to assume that the kernel 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 use the relocation address as the 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><h4>Higher-half Linker Script</h4><p>We can modify the first linker script to implement this.</p><p>— Now your updated ‘link.ld’ file should look like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c6ebe03331eb10cabe90afd6cc62c97/href">https://medium.com/media/9c6ebe03331eb10cabe90afd6cc62c97/href</a></iframe><h4>Entering the Higher Half</h4><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.</p><p>— Create two new files named ‘paging.h’ and ‘paging.c’.</p><p>‘paging.h’ file should look like,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/603135c2988a4bfbfd0815e2f190487b/href">https://medium.com/media/603135c2988a4bfbfd0815e2f190487b/href</a></iframe><p>‘paging.c’ file should look like,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e4593d35937f2589b368dc2ab0d2ff5/href">https://medium.com/media/5e4593d35937f2589b368dc2ab0d2ff5/href</a></iframe><p>After the table has been created, a jump can be done to a label to make <em>eip</em> point to a virtual address in the higher half using assembly code:</p><pre>; assembly code executing at around 0x00100000<br>; enable paging for both actual location of kernel<br>; and its higher-half virtual location<br><br>lea ebx, [higher_half] ; load the address of the label in ebx<br>jmp ebx                ; jump to the label<br><br>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 <em>eip </em>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 is invalidated with<em> invlpg [0].</em></p><h4>Running in the Higher Half</h4><p>There are a few more details we must deal with when using a higher-half kernel. We must be careful when using memory-mapped I/O that uses specific memory locations. For example, the frame buffer is located at 0x000B8000, but since there is no entry in the page table for the address 0x000B8000 any longer, the address 0xC00B8000 must be used, since the virtual address 0xC0000000 maps to the physical address 0x00000000.</p><p>Any explicit references to addresses within the multiboot structure need to be changed to reflect the new virtual addresses as well.</p><p>Mapping 4 MB pages for the kernel is simple but wastes memory unless you have a really big kernel. Creating a higher-half kernel mapped in as 4 KB pages save memory but are harder to set up. Memory for the page directory and one-page table can be reserved in the .data section, but one needs to configure the mappings from virtual to physical addresses at run-time. The size of the kernel can be determined by exporting labels from the linker script.</p><p>— Now we have to create four new files named ‘kheap.h’, ‘kheap.c’, ‘common.h’ and ‘common.c’.</p><p>‘kheap.h’ file should look like,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce271b38bd4161beae4105b11f2b4fdc/href">https://medium.com/media/ce271b38bd4161beae4105b11f2b4fdc/href</a></iframe><p>‘kheap.c’ file should look like,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5a6a250dd31e05e5f92015caa8672c7/href">https://medium.com/media/a5a6a250dd31e05e5f92015caa8672c7/href</a></iframe><p>‘common.h’ file should look like,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/729fa9d6aac14c64c7a09f0fd193c32a/href">https://medium.com/media/729fa9d6aac14c64c7a09f0fd193c32a/href</a></iframe><p>‘common.c’ file should look like,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36116848ff40b26d1dc0194dd59fba8f/href">https://medium.com/media/36116848ff40b26d1dc0194dd59fba8f/href</a></iframe><p>— lastly, your updated ‘kmain.c’ file should look like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/222f58949c4f15ab61c7db779c18ddf4/href">https://medium.com/media/222f58949c4f15ab61c7db779c18ddf4/href</a></iframe><p>— Now you can run the command make run. You won’t see any visible changes on the screen: this is an internal change.</p><p>If everything is okay. Well done!</p><p>You can refer to my Github for further clarification.</p><p><a href="https://github.com/NethminiDevyanjalee/myFirstOS/tree/virtual_memory_paging">GitHub - NethminiDevyanjalee/myFirstOS at virtual_memory_paging</a></p><p>We will see about <em>Page Frame Allocation</em> in the next article <strong>“Make your own Operating System#8”</strong>.</p><p>Hope to see you in the next article as well!</p><p>Reference: <a href="https://littleosbook.github.io/">The Little OS Book</a></p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b7d093004de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make your own Operating System#6]]></title>
            <link>https://medium.com/@nethminid1999/make-your-own-operating-system-6-370629baa13c?source=rss-6b0a279af35d------2</link>
            <guid isPermaLink="false">https://medium.com/p/370629baa13c</guid>
            <category><![CDATA[modules]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[user-mode]]></category>
            <dc:creator><![CDATA[Nethmini Devyanjalee]]></dc:creator>
            <pubDate>Fri, 27 Aug 2021 15:03:37 GMT</pubDate>
            <atom:updated>2021-09-06T18:18:22.453Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4e3MkrPa9Gu2jXsRO68-qg.jpeg" /></figure><p><em>Hello everyone!</em></p><p>Now that the kernel boots, prints to screen, and reads from the keyboard. what else we can do from our OS?</p><p>This article will show how to easily execute a small program in kernel mode.</p><h4>Kernel mode</h4><p>Usually, a kernel is not supposed to do the application logic itself, but leave that for applications. The kernel creates the proper abstractions to make application development easier, performs tasks on behalf of applications, and schedules processes.</p><h4>User mode</h4><p>User mode, in contrast with kernel mode, is the environment in which the user’s programs execute. This environment is less privileged than the kernel and will prevent user programs from messing with other programs or the kernel. Badly written kernels are free to mess up what they want.</p><h3>Loading an External Program</h3><p>Where do we get the external program from? Somehow we need to load the code we want to execute into memory. More feature-complete operating systems usually have drivers and file systems that enable them to load the software from a CD-ROM drive, a hard disk, or other persistent media.</p><p>Instead of creating all these drivers and file systems, we will use a feature in GRUB called modules to load the program.</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>.</p><p>— 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 your updated ‘menu.lst’ file should look like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d978b5ebea50cd43cd98e1ba6b903ba/href">https://medium.com/media/2d978b5ebea50cd43cd98e1ba6b903ba/href</a></iframe><p>— Create the folder iso/modules by running the below command in the terminal.</p><pre>mkdir -p iso/modules</pre><p>Now your ‘iso’ folder should look like this with the new modules folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*FqyQw2yoacQX5X8Mg9kr9g.png" /></figure><p>The code that calls kmain must be updated to pass information to kmain 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.</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`</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><pre>; in file `loader.s`</pre><pre>push ebx         ; multiboot info in ebx</pre><p>Now your updated ‘loader.s’ file should look like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/711c1bcc5acf454ffb2d534e4f6c2fcc/href">https://medium.com/media/711c1bcc5acf454ffb2d534e4f6c2fcc/href</a></iframe><h3>Executing a Program</h3><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><p>— Create a new file as ‘program.s’ and your file should look like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ddae3696b45ffac9ce4bbee8d458381/href">https://medium.com/media/7ddae3696b45ffac9ce4bbee8d458381/href</a></iframe><p>You must now move the file program to the folder iso/modules.</p><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><p>— Run the below code in the terminal for that.</p><pre>nasm -f bin program.s -o program</pre><p>Now you can see a binary file named ‘program’ in the ‘modules’ folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*-9026lzZSjyW0O6_g4EOrw.png" /></figure><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.</p><p>— Download the multiboot.h file, which describes the structure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47edaed3b9fa0c26b70d9bb4ec9dd27e/href">https://medium.com/media/47edaed3b9fa0c26b70d9bb4ec9dd27e/href</a></iframe><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.</p><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>Now your updated ‘kmain’ file should look like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/219d986c7ecd637fc98f949761e7ac09/href">https://medium.com/media/219d986c7ecd637fc98f949761e7ac09/href</a></iframe><p>If we start the kernel, wait until it has run and entered the infinite loop in the program, and then halt Bochs.</p><p>we should see 0xDEADBEEF in the register eax via the Bochs log.</p><p>— Run the command ‘cat bochslog.txt’ in the terminal. Now you should be able to see 0xDEADBEEF in the register eax. See the below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*kCz0kFLYUb-T62HJSjSqFA.png" /></figure><p>Well done, We have successfully started a program in our OS!</p><p>You can refer to my Github for further clarification.</p><p><a href="https://github.com/NethminiDevyanjalee/myFirstOS/tree/integrate_user_modes">GitHub - NethminiDevyanjalee/myFirstOS at integrate_user_modes</a></p><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, besides <em>segmentation</em>, do <em>paging</em> and <em>page frame allocation</em>.</p><p>We will see about Virtual Memory and Paging in the next article “Make your own Operating System#7”.</p><p>Hope to see you in the next article as well!</p><p>Reference: <a href="https://littleosbook.github.io/">The Little OS Book</a></p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=370629baa13c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make your own Operating System#5]]></title>
            <link>https://medium.com/@nethminid1999/make-your-own-operating-system-5-e325d42ba329?source=rss-6b0a279af35d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e325d42ba329</guid>
            <category><![CDATA[input-output]]></category>
            <category><![CDATA[interrupt]]></category>
            <dc:creator><![CDATA[Nethmini Devyanjalee]]></dc:creator>
            <pubDate>Fri, 20 Aug 2021 15:32:13 GMT</pubDate>
            <atom:updated>2021-08-24T16:12:45.385Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*qH5qT8r9Du3KbEC01QaAaA.jpeg" /></figure><p><em>Hello everyone!</em></p><p>Now our primitive OS can produce output. So it would be nice if it also could get some input.</p><p>The operating system must be able to handle interrupts to read information from the keyboard. An interrupt occurs when a hardware device, such as the keyboard, the serial port, or the timer, signals the CPU that the state of the device has changed. The CPU itself can also send interrupts due to program errors, for example when a program references memory it doesn’t have access to, or when a program divides a number by zero. Finally, there is also software interrupts, which are caused by the int assembly code instruction and are often used for system calls.</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. 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 our OS, we will use trap handlers and disable interrupts manually when we need to.</p><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><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*Cs0zO59Eu4MI5DOXUEDovQ.png" /></figure><p>The lowest 32 bits are presented in the following figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*qd_p8AkNZJlPoNywk1ojdA.png" /></figure><p>A description for each name can be found in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*_Mozj6uZej8sEwublds5PA.png" /></figure><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 a handler for interrupt 0 (divide-by-zero), the following code would be used:</p><pre>idt[0] = 0xDEAD8E00<br>idt[1] = 0x0008BEEF</pre><p>we recommend that you use packed structures instead of using bytes (or unsigned integers) to make the code more readable.</p><h3>Handling an Interrupt</h3><p>When an interrupt occurs the CPU will push some information about the interrupt onto the stack, then look up the appropriate interrupt handler 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?</pre><p>The reason for the question mark behind the error code is that not all interrupts create an <em>error code</em>. The specific CPU interrupts that put an error code on the stack are 8, 10, 11, 12, 13, 14, and 17. The error code can be used by the interrupt handler to get more information on what has happened. Also, note that the interrupt <em>number</em> is <em>not</em> pushed onto the stack. We can only determine what interrupt has occurred by knowing what code is executing — if the handler registered for interrupt 17 is executing, then interrupt 17 has occurred.</p><p>Once the interrupt handler is done, it uses the iret instruction to return. The instruction iret expects the stack to be the same as at the time of the interrupt. Therefore, any values pushed onto the stack by the interrupt handler must be popped. Before returning, iret restores eflags by popping the value from the stack and then finally jumps to cs:eip as specified by the values on the stack.</p><p>The interrupt handler has to be written in assembly code since all registers that the interrupt handlers used must be preserved by pushing them onto the stack. This is because the code that was interrupted doesn’t know about the interrupt and will therefore expect that its registers stay the same. Writing all the logic of the interrupt handler in assembly code will be tiresome. Creating a handler in assembly code that saves the registers, calls a C function, restores the registers, and finally executes iret is a good idea!</p><p>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:</p><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));</pre><pre>    struct stack_state {<br>        unsigned int error_code;<br>        unsigned int eip;<br>        unsigned int cs;<br>        unsigned int eflags;<br>    } __attribute__((packed));</pre><pre>    void interrupt_handler(struct cpu_state cpu, struct stack_state stack, unsigned int interrupt);</pre><p>— Create two new files, as ‘interrupts.h’ and ‘interrupts.c’.</p><p>Your ‘interrupts.h’ file should look like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b877c3b77157b46663883e3b55bc31e5/href">https://medium.com/media/b877c3b77157b46663883e3b55bc31e5/href</a></iframe><p>Your ‘interrupts.c’ file should look like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a924ce836e6acc39d88e78e20c6a7883/href">https://medium.com/media/a924ce836e6acc39d88e78e20c6a7883/href</a></iframe><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. 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<br><br>    %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<br><br>    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<br><br>        ; call the C function<br>        call    interrupt_handler<br><br>        ; restore the registers<br>        pop     ebp<br>        .<br>        .<br>        .<br>        pop     ebx<br>        pop     eax<br><br>        ; restore the esp<br>        add     esp, 8<br><br>        ; return to the code that got interrupted<br>        iret<br><br>    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><p>— Create a new file as ‘interrupt_handlers.s’ and your file should look like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc28f49fc9acd32a885ea016f7dbf990/href">https://medium.com/media/dc28f49fc9acd32a885ea016f7dbf990/href</a></iframe><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<br><br>    ; 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><p>— Create a new file as ‘idt.s’ and your file should look like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5cf401236739263844a9510e89c903b/href">https://medium.com/media/b5cf401236739263844a9510e89c903b/href</a></iframe><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 was 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><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*_q_S_gZPemjOnN4Eb5SSYA.png" /></figure><p>Every interrupts 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;<br><br>    #define PIC1_PORT_A 0x20<br>    #define PIC2_PORT_A 0xA0<br><br>    /* 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<br><br>    #define PIC_ACK     0x20<br><br>    /** 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>        }<br><br>        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><p>— Create two new files, as ‘pic.h’ and ‘pic.c’.</p><p>Your ‘pic.h’ file should look like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccabbb4f35b6333db534eb19000f6198/href">https://medium.com/media/ccabbb4f35b6333db534eb19000f6198/href</a></iframe><p>Your ‘pic.c’ file should look like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f97393c48e035472f3029699f6f6654e/href">https://medium.com/media/f97393c48e035472f3029699f6f6654e/href</a></iframe><h3>Reading Input from the Keyboard</h3><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 an address 0x60. How this can be done is shown in the following example:</p><pre>#include &quot;io.h&quot;<br><br>    #define KBD_DATA_PORT   0x60<br><br>    /** 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.</p><p>— Create two new files, as ‘keyboard.h’ and ‘keyboard.c.</p><p>Your ‘keyboard.h’ file should look like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33213d4ae83a75b037af40464e6cb212/href">https://medium.com/media/33213d4ae83a75b037af40464e6cb212/href</a></iframe><p>Your ‘keyboard.c’ file should look like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/985ef08024da68e5c0f9a45182cde8d9/href">https://medium.com/media/985ef08024da68e5c0f9a45182cde8d9/href</a></iframe><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>— Lastly, update the file kmain.c</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d34dcad939f5331276901d0d6cceb14d/href">https://medium.com/media/d34dcad939f5331276901d0d6cceb14d/href</a></iframe><p>— Now you can run the command make run</p><p>You will see bochs Emulator running. After typing ‘c‘ in the terminal. You should get the below screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*UpL5w6dgfOCg-DDW.png" /></figure><p>Then you can type the word ‘inputs’ in bochs Emulator but it won’t be visible on the screen. Open the file called com1.out in your working directory.</p><p>Your file com1.out should look like the below image including the word ‘inputs’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*cu6ZcaTS82mAN-l8d4YWEA.png" /></figure><p>If everything is good, Well done!</p><p>Now our primitive OS can get inputs by handling interrupts. You can refer to my Github for further clarification.</p><p><a href="https://github.com/NethminiDevyanjalee/myFirstOS/tree/interupt_and_inputs">GitHub - NethminiDevyanjalee/myFirstOS at interupt_and_inputs</a></p><p>Hope to see you in the next article as well!</p><p>We will see about User Modes in the next article “Make your own Operating System#6”.</p><p>Reference: <a href="https://littleosbook.github.io/">The Little OS Book</a></p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e325d42ba329" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make your own Operating System#4]]></title>
            <link>https://medium.com/@nethminid1999/make-your-own-operating-system-4-601f99d90f00?source=rss-6b0a279af35d------2</link>
            <guid isPermaLink="false">https://medium.com/p/601f99d90f00</guid>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[segmentation]]></category>
            <dc:creator><![CDATA[Nethmini Devyanjalee]]></dc:creator>
            <pubDate>Fri, 13 Aug 2021 16:24:21 GMT</pubDate>
            <atom:updated>2021-08-13T17:10:44.479Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nfUDlH_od48phjeXl_pBNg.png" /></figure><p><em>Hello everyone!</em></p><p>In this article, I will talk about integrate segmentation. Segmentation is a Memory Management technique in which memory is divided into variable-sized chunks allocated to processes. Each chunk is called a segment. A table stores the information about all such segments. To address a byte in segmented memory you use a 48-bit <em>logical address</em>: 16 bits that specify the segment and 32-bits that specify what offset within that segment you want. The offset is added to the base address of the segment, and the resulting linear address is checked against the segment’s limit. If everything works out fine the result is a <em>linear address</em>. When paging is disabled, then the linear address space is mapped 1:1 onto the <em>physical address</em> space, and the physical memory can be accessed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*tT5q2KoHwy6HSPWcy4I4EA.png" /></figure><p>To enable segmentation you need to set up a table that describes each segment — a <em>segment descriptor table</em>. In x86, there are two types of descriptor tables: the <em>Global Descriptor Table</em> (GDT) and <em>Local Descriptor Tables</em> (LDT). An LDT is set up and managed by user-space processes, and all processes have their own LDT. LDTs can be used if a more complex segmentation model is desired — we won’t use it. The GDT is shared by everyone — it’s global.</p><h3>Accessing Memory</h3><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 cs register is also known as the Code Segment. The Code Segment tells the processor which offset into the GDT that it will find the access privileges in which to execute the current code. The register ss is used whenever accessing the stack. The ds register is the same idea, but it’s not for code, it’s the Data segment and defines the access privileges for the current data. es, fs, and gs are simply alternate ds registers and are not important to us.</p><p>Below is an example showing implicit use of the segment registers:</p><pre>func:<br>        mov eax, [esp+4]<br>        mov ebx, [eax]<br>        add ebx, 8<br>        mov [eax], ebx<br>        ret</pre><p>The above example can be compared with the following one that makes explicit use of the segment registers:</p><pre>func:<br>        mov eax, [ss:esp+4]<br>        mov ebx, [ds:eax]<br>        add ebx, 8<br>        mov [ds:eax], ebx<br>        ret</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, you must store the segment selectors in their indented registers to use the implicit style shown above.</p><h3>The Global Descriptor Table (GDT)</h3><p>The GDT<strong> </strong>defines base access privileges for certain parts of memory. We can use an entry in the GDT to generate segment violation exceptions that allow the kernel to end a process that is doing something it shouldn’t. Most modern operating systems use a mode of memory called “Paging” to do this: It is a lot more versatile and allows for higher flexibility. The GDT can also define if a section in memory is executable or if it is in fact, data. The GDT is also capable of defining what is called Task State Segments (TSS).</p><p>Note that GRUB already installs a <em>GDT</em> for you, but if we overwrite the area of memory that <em>GRUB</em> was loaded to, we will trash the GDT and this will cause what is called a ‘triple fault’. In short, it’ll reset the machine. What we should do to prevent that problem is to set up our own GDT in a place in memory that we know and can access. This involves building our own GDT, telling the processor where it is, and finally loading the processor’s cs, ss, ds, es, gs and fs registers with our new entries.</p><p>A GDT is an array of 8-byte segment descriptors. These entries define where in memory that the allowed region will start, as well as the limit of this region, and the access privileges associated with this entry. The first descriptor in the GDT is always a null descriptor and can never be used to access memory. No segment register should be set to 0, otherwise, this will cause a General Protection fault, and is a protection feature of the processor. At least two segment descriptors (plus the null descriptor) are needed for the GDT because the descriptor contains more information than just the base and limit fields. The two most relevant fields for us are the <em>Type</em> field and the <em>Descriptor Privilege Level</em> (DPL) field.</p><p>Type field can’t be both writable <em>and</em> executable at the same time. Therefore, two segments are needed: one segment for executing code to put in cs (Type is Execute-only or Execute-Read) and one segment for reading and writing data (Type is Read/Write) to put in the other segment registers.</p><p>The DPL specifies the <em>privilege levels</em> required to use the segment. x86 allows for four privilege levels (PL), 0 to 3, where PL0 is the most privileged. In most operating systems, only PL0 and PL3 are used. The kernel should be able to do anything, therefore it uses segments with DPL set to 0 (also called kernel mode). The current privilege level (CPL) is determined by the segment selector in cs.</p><p>The segments needed are described in the table below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*5maQbqqBl-T3uuqN8EQ9cg.png" /></figure><p>Note that the segments overlap they both encompass the entire linear address space. In our minimal setup, we’ll only use segmentation to get privilege levels.</p><h3>Loading the GDT</h3><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>struct 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>lgdt [eax]</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 need to be loaded with their corresponding segment selectors. The content of a segment selector is described in the figure and table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDJ6AGSf_rxXK7fiEjNG4Q.png" /></figure><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>mov ds, 0x10<br>    mov ss, 0x10<br>    mov es, 0x10<br>    .<br>    .<br>    .</pre><p>To load cs we have to do a “far jump”:</p><pre>; code here uses the previous cs<br>    jmp 0x08:flush_cs   ; specify cs when jumping to flush_cs</pre><pre>    flush_cs:<br>        ; now we&#39;ve changed cs to 0x08</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>Steps:</p><p>— Create two new files, as ‘memory_segments.h’ and ‘memory_segments.c’.</p><p>Your ‘memory_segments.h’ file should look like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c24a6e7a0e61af4e4048ae2d55cbeea4/href">https://medium.com/media/c24a6e7a0e61af4e4048ae2d55cbeea4/href</a></iframe><p>Your ‘memory_segments.c’ file should look like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49b28c0bbd4e2c02871c01ec9103749b/href">https://medium.com/media/49b28c0bbd4e2c02871c01ec9103749b/href</a></iframe><p>— Get gcc to compile your ‘memory_segments.c’ by adding ‘memory_segments.o’ to the list of files in ‘Makefile’.</p><p>— Create a new file, ‘gdt.s’. Then your file should look like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c32ccb54f5eca75eb9cdd119790e7672/href">https://medium.com/media/c32ccb54f5eca75eb9cdd119790e7672/href</a></iframe><p>— Get gcc to compile your ‘memory_segments.c’ by adding ‘gdt.o’ to the list of files in ‘Makefile’.</p><p>Your make file should look like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fe6713aeb3d87d2c2afbe879868a3eb/href">https://medium.com/media/2fe6713aeb3d87d2c2afbe879868a3eb/href</a></iframe><p>Now that our GDT loading infrastructure is in place, and we compile and link it into our kernel,</p><p>— we need to call segments_install_gdt() in order to do our work! Open ‘kmain.c’ and add ‘segments_install_gdt();’ as the very first line in your kmain() function. The GDT needs to be one of the very first things that you initialize because as you learned from this article, it’s very important.</p><p>Your ‘kmain.c’ file should look like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e0e8362a731a5714db82eda7609663f/href">https://medium.com/media/2e0e8362a731a5714db82eda7609663f/href</a></iframe><p>Now, you can run the command ‘make run’. You won’t see any visible changes on the screen: this is an internal change.</p><p>If everything is good then, Good job!</p><p>You can refer to my GitHub for further clarification.</p><p><a href="https://github.com/NethminiDevyanjalee/myFirstOS/tree/integrate_segmentation">GitHub - NethminiDevyanjalee/myFirstOS at integrate_segmentation</a></p><p>Hope to see you in the next article as well!</p><p>We will see about the Interrupts and Input in the next article “Make your own Operating System#5”.</p><p>Reference: <a href="https://littleosbook.github.io/">The Little OS Book</a></p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=601f99d90f00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make your own Operating System#3]]></title>
            <link>https://medium.com/@nethminid1999/make-your-own-operating-system-3-758e808561e5?source=rss-6b0a279af35d------2</link>
            <guid isPermaLink="false">https://medium.com/p/758e808561e5</guid>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[drive]]></category>
            <category><![CDATA[frame-buffer]]></category>
            <category><![CDATA[serial-port]]></category>
            <dc:creator><![CDATA[Nethmini Devyanjalee]]></dc:creator>
            <pubDate>Fri, 06 Aug 2021 17:15:50 GMT</pubDate>
            <atom:updated>2021-08-07T17:23:20.022Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*IRZaiCEMPtLtHzT1KeKDRg.png" /></figure><p><em>Hello everyone!</em></p><p>This article will explain the steps to display text on the console as well as writing data to the serial port. And also we’ll create our first driver; code that acts as a layer between the kernel and the hardware, providing a higher abstraction than communicating directly with the hardware.</p><h3>Interacting with the Hardware</h3><p>There are usually two alternative ways to interact with the hardware.</p><p><strong><em>Memory-mapped I/O</em></strong></p><p>If the hardware uses memory-mapped I/O, you’ll be able to write to a selected memory address and the hardware will be updated with the new data. One example of this is the framebuffer.</p><p><strong><em>I/O ports</em></strong></p><p>If the hardware uses I/O ports then the assembly code instructions <strong>out</strong> and <strong>in</strong> should be used to communicate with the hardware. The instruction <strong>out</strong> takes two parameters: the address of the I/O port and the data to send. The instruction <strong>in </strong>takes one parameter, the address of the I/O port, and returns data from the hardware. The cursor of the framebuffer is one example of hardware controlled via I/O ports on a computer.</p><p><strong>The first part of this article is about creating a driver for the framebuffer to be able to display text on the console.</strong></p><h3>The Framebuffer</h3><p>The framebuffer is a hardware device that’s capable of displaying a buffer of memory on the screen. The framebuffer has 80 columns and 25 rows, and the row and column indices start at 0 (so rows are labeled 0–24).</p><h4>Writing Text</h4><p>The starting address of the memory-mapped I/O for the framebuffer is 0x000B8000 .The memory is divided into 16-bit cells, where the 16 bits determine both the character, the foreground color, and the background color.</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>Using an ASCII table, one can see that A corresponds to 65 or 0x41. Therefore, to write the character A with a green foreground (2) and dark grey background (8) at the place (0,0), the following assembly code instruction is used:</p><pre>mov [0x000B8000], 0x4128</pre><p>The second cell then corresponds to row zero, column one and its address is, therefore:</p><pre>0x000B8000 + 16 = 0x000B8010</pre><p>Writing to the framebuffer can also be done in C by treating the address 0x000B8000 as a char pointer,</p><p>char *fb = (char *) 0x000B8000</p><p>Then, writing A at the place (0,0) with green foreground and dark grey background becomes:</p><pre>fb[0] = &#39;A&#39;;<br>fb[1] = 0x28;</pre><p>The following code shows how this can be wrapped into a function:</p><pre>/** fb_write_cell:<br>     *  Writes a character with the given foreground and background to position i<br>     *  in the framebuffer.<br>     *<br>     *  @param i  The location in the framebuffer<br>     *  @param c  The character<br>     *  @param fg The foreground color<br>     *  @param bg The background color<br>     */<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:</p><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);</pre><p>You can now create a header file as <strong>‘framebuffer.h’</strong> including the above codes.</p><h4>Moving the Cursor</h4><p>The cursor’s position is determined with a 16 bits integer: 0 means row zero, column zero; 1 means row zero, column one, and so on. Since the position is 16 bits large, and the out assembly code instruction argument is 8 bits, the position must be sent in two turns, first 8 bits then the next 8 bits. The framebuffer has two I/O ports, one for accepting the data, and one for describing the data being received. Port 0x3D4 [29] is the port that describes the data and port 0x3D5 [29] is for the data itself.</p><p>To set the cursor at row one, column zero (position 80 = 0x0050), one would use the following assembly code instructions:</p><pre>out 0x3D4, 14      ; 14 tells the framebuffer to expect the highest 8 bits of the position<br>out 0x3D5, 0x00    ; sending the highest 8 bits of 0x0050<br>out 0x3D4, 15      ; 15 tells the framebuffer to expect the lowest 8 bits of the position<br>out 0x3D5, 0x50    ; sending the lowest 8 bits of 0x0050</pre><p>The out assembly code instruction can’t be executed directly in C. Therefore it is a good idea to wrap out in a function in assembly code that can be accessed from C via the cdecl calling standard :</p><p>Store this function in a file called <strong>io.s</strong></p><pre>global outb             ; make the label outb visible outside this file</pre><pre>    ; outb - send a byte to an I/O port<br>    ; stack: [esp + 8] the data byte<br>    ;        [esp + 4] the I/O port<br>    ;        [esp    ] return address<br>    outb:<br>        mov al, [esp + 8]    ; move the data to be sent into the al register<br>        mov dx, [esp + 4]    ; move the address of the I/O port into the dx register<br>        out dx, al           ; send the data to the I/O port<br>        ret                  ; return to the calling function</pre><p>And also create a header file as <strong>io.h </strong>and include the below code.</p><p>Then the out assembly code instruction can be conveniently accessed from C:</p><pre>#ifndef INCLUDE_IO_H<br>#define INCLUDE_IO_H<br><br>/** outb:<br> *  Sends the given data to the given I/O port. Defined in io.s<br> *<br> *  @param port The I/O port to send the data to<br> *  @param data The data to send to the I/O port<br> */<br>void outb(unsigned short port, unsigned char data);</pre><pre>#endif /* INCLUDE_IO_H */</pre><p>Moving the cursor can now be wrapped in a C function:</p><p>Include the below code in the <strong>‘framebuffer.h’ </strong>header file.</p><pre>#include &quot;io.h&quot;<br><br>/* The I/O ports */<br>#define FB_COMMAND_PORT         0x3D4<br>#define FB_DATA_PORT            0x3D5<br><br>/* The I/O port commands */<br>#define FB_HIGH_BYTE_COMMAND    14<br>#define FB_LOW_BYTE_COMMAND     15<br><br>/** fb_move_cursor:<br> *  Moves the cursor of the framebuffer to the given position<br> *<br> *  @param pos The new position of the cursor<br> */<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><h4>The Driver</h4><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>Then the ‘ <strong>‘framebuffer.h’ </strong>header file should look like the below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*4tPGfKGaLA5XpE79MycNPQ.png" /></figure><p>You should update your file kmain.c as the below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*d_3kxfNvJSYGiGjoRZ2ShA.png" /></figure><p>Then 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><p>— Now, you can run the command make run</p><p>You will see bochs Emulator running. After typing ‘c‘ in the terminal. You should get the below screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*ZrtGF6qGsICWuP4_l6cbUA.png" /></figure><p><strong>As the second part of this article, this section will guide to create a driver for the serial port.</strong></p><h3>The Serial Ports</h3><p>The serial port is an interface for communicating between hardware devices. The serial port is easy to use, and, more importantly, it can be used as a logging utility in Bochs. The serial ports are completely controlled via I/O ports.</p><h4>Configuring the Serial Port</h4><p>The first data that need to be sent to the serial port is configuration data. 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><h4>Configuring the Line</h4><p>Configuring the line means configuring 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>First, the speed for sending data will be set. The serial port has an internal clock that runs at 115200 Hz. Setting the speed means sending a divisor to the serial port, for example sending 2 results in a speed of 115200 / 2 = 57600 Hz.</p><p>A divisor is a 16-bit number but we can only send 8 bits at a time. We must therefore send an instruction telling the serial port to first expect the highest 8 bits, then the lowest 8 bits. This is done by sending 0x80 to the line command port. An example is shown below:</p><p>You can now create a header file as <strong>‘serial.h’</strong> including the below codes.</p><pre>#include &quot;io.h&quot; /* io.h is implement in the section &quot;Moving the cursor&quot; */<br><br>    /* The I/O ports */<br><br>    /* All the I/O ports are calculated relative to the data port. This is because<br>     * all serial ports (COM1, COM2, COM3, COM4) have their ports in the same<br>     * order, but they start at different values.<br>     */<br><br>    #define SERIAL_COM1_BASE                0x3F8      /* COM1 base port */<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>    /* The I/O port commands */<br><br>    /* SERIAL_LINE_ENABLE_DLAB:<br>     * Tells the serial port to expect first the highest 8 bits on the data port,<br>     * then the lowest 8 bits will follow<br>     */<br>    #define SERIAL_LINE_ENABLE_DLAB         0x80<br><br>    /** serial_configure_baud_rate:<br>     *  Sets the speed of the data being sent. The default speed of a serial<br>     *  port is 115200 bits/s. The argument is a divisor of that number, hence<br>     *  the resulting speed becomes (115200 / divisor) bits/s.<br>     *<br>     *  @param com      The COM port to configure<br>     *  @param divisor  The divisor<br>     */<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>The way that data should be sent must be configured. This is also done via the line command port by sending a byte. The layout of the 8 bits looks like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*pe1tsmbhenO2ziC-_PZZ0w.png" /></figure><p>We will use the mostly standard value 0x03 , meaning a length of 8 bits, no parity bit, one stop bit, and break control disabled. This is sent to the line command port, as seen in the following example:</p><pre>/** serial_configure_line:<br>     *  Configures the line of the given serial port. The port is set to have a<br>     *  data length of 8 bits, no parity bits, one stop bit and break control<br>     *  disabled.<br>     *<br>     *  @param com  The serial port to configure<br>     */<br>    void serial_configure_line(unsigned short com)<br>    {<br>        /* Bit:     | 7 | 6 | 5 4 3 | 2 | 1 0 |<br>         * Content: | d | b | prty  | s | dl  |<br>         * Value:   | 0 | 0 | 0 0 0 | 0 | 1 1 | = 0x03<br>         */<br>        outb(SERIAL_LINE_COMMAND_PORT(com), 0x03);<br>    }</pre><h4>Configuring the Buffers</h4><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. The FIFO queue configuration byte looks like the following figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*y7BUqdW-x3JwKNXriLzRTg.png" /></figure><p>We use the value 0xC7 = 11000111 that:</p><ul><li>Enables FIFO</li><li>Clear both receiver and transmission FIFO queues</li><li>Use 14 bytes as the size of the queue</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*vMet_CksaM0JGlay62kuuQ.png" /></figure><h4>Configuring the Modem</h4><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. The modem configuration byte is shown in the following figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*YrwDg0fk6SGdYf0geQVcjg.png" /></figure><p>We don’t need to enable interrupts, because we won’t handle any received data. Therefore we use the configuration value 0x03 = 00000011 (RTS = 1 and DTS = 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*iuYZnlkv1dEgT-y2pbY-RA.png" /></figure><h4>Writing Data to the Serial Port</h4><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><p>Include the below codes in the <strong>io.s</strong> file.</p><pre>global inb<br><br>    ; inb - returns a byte from the given I/O port<br>    ; stack: [esp + 4] The address of the I/O port<br>    ;        [esp    ] The return address<br>    inb:<br>        mov dx, [esp + 4]       ; move the address of the I/O port to the dx register<br>        in  al, dx              ; read a byte from the I/O port and store it in the al register<br>        ret                     ; return the read byte</pre><p>Include the below codes in the <strong>io.h</strong> file.</p><pre>/** inb:<br>     *  Read a byte from an I/O port.<br>     *<br>     *  @param  port The address of the I/O port<br>     *  @return      The read byte<br>     */<br>    unsigned char inb(unsigned short port);</pre><p>Checking if the transmit FIFO is empty can then be done from C:</p><p>Update the file ‘serial.h’ using the below codes.</p><pre>   /** serial_is_transmit_fifo_empty:<br>     *  Checks whether the transmit FIFO queue is empty or not for the given COM<br>     *  port.<br>     *<br>     *  @param  com The COM port<br>     *  @return 0 if the transmit FIFO queue is not empty<br>     *          1 if the transmit FIFO queue is empty<br>     */<br>    int serial_is_transmit_fifo_empty(unsigned int com)<br>    {<br>        /* 0x20 = 0010 0000 */<br>        return 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><h4>Configuring Bochs</h4><p>To save the output from the first serial port the Bochs configuration file bochsrc.txt must be updated. The com1 configuration instructs Bochs how to handle the first serial port:</p><pre>com1: enabled=1, mode=file, dev=com1.out</pre><p>The output from serial port one will now be stored in the file com1.out.</p><h4>The Driver</h4><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>An example for serial_write function:</p><pre>/* Divisor for different baud rates */<br>enum BaudRate { Baud_115200 = 1, Baud_57600, Baud_19200, Baud_9600 };<br>enum BaudRate divisor = Baud_115200;</pre><pre>void serial_write_byte(unsigned short port, char byteData) {<br>  outb(port, byteData);<br>}</pre><pre>void serial_configure(unsigned short port, unsigned short baudRate) {<br>  serial_configure_baud_rate(port, baudRate);<br>  serial_configure_line(port);<br>  serial_configure_fifo_buffer(port);<br>  serial_configure_modem(port);<br>}</pre><pre>int serial_write(unsigned short com, char *buf, unsigned int len) {<br>  serial_configure(com , divisor);<br>  unsigned int indexToBuffer = 0;<br>  while (indexToBuffer &lt; len) {<br>    if (serial_is_transmit_fifo_empty(com)) {<br>      serial_write_byte(com, buf[indexToBuffer]);<br>      indexToBuffer++;<br>    }<br>  }<br>  return 0;<br>}</pre><p>Now your ‘serial.h’ file should look like the below image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*vfVmlh37oW4tdQaHRuvE4g.png" /></figure><p>Lastly, update the file kmain.c</p><pre>#include &quot;serial.h&quot;</pre><pre>int kmain()<br>    {<br>     char msg[] = &quot;Welcome to myFirstOS&quot;;<br>     unsigned int len = sizeof(msg) / sizeof(msg[0]);<br> <br>     //serial writing<br>     serial_write(0x3F8, msg, len);<br>     <br>     return 0;<br>    }</pre><p>— Now you can run the command make run</p><p>Then you will see a file called com1.out in your working directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*9SqQSOoTL_naR_g_sx_d3Q.png" /></figure><p>When you open the file com1.out using a text editor your file should look like the above image.</p><p>If everything is good then, <strong>Good job!</strong></p><p>You can refer to my <a href="https://github.com/NethminiDevyanjalee/myFirstOS/tree/integrate_outputs">Github</a> for further clarification.</p><p>Hope to see you in the next article as well!</p><p>We will see about Segmentation in the next article “Make your own Operating System#4”.</p><p>Reference: <a href="https://littleosbook.github.io/">The Little OS Book</a></p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=758e808561e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Licenses]]></title>
            <link>https://medium.com/@nethminid1999/software-licenses-38437f7e5e13?source=rss-6b0a279af35d------2</link>
            <guid isPermaLink="false">https://medium.com/p/38437f7e5e13</guid>
            <category><![CDATA[software-license]]></category>
            <dc:creator><![CDATA[Nethmini Devyanjalee]]></dc:creator>
            <pubDate>Wed, 04 Aug 2021 10:28:04 GMT</pubDate>
            <atom:updated>2021-08-04T10:34:21.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*q8sSKPcq_wvM_BojpN7lZQ.jpeg" /></figure><p>A software license is a legal document that governs how the software can be used and distributed. Under copyright laws, all software is protected. A typical license grants a user permission to use one or more copies of the software without infringement of copyright.</p><p>Software license falls into two broad categories: open-source software license types and proprietary software license types.</p><h3><strong>1. Open-source software license </strong>types</h3><p>Open-source software licenses grant other users the permission and rights to use or repurpose the code for new applications or to include the code in other projects under defined terms and conditions.</p><p>Open-source licenses are commonly classified into two categories:</p><h4>a. Permissive License</h4><p>A permissive license guarantees the freedom to use, modify, and redistribute, while also permitting proprietary derivative works. It is also called a BSD-like or BSD-style license.</p><p>Examples — GNU All-permissive License, MIT License, BSD licenses, Apple Public Source License, Apache license, etc.</p><h4><strong>b. Copyleft License</strong></h4><p>Copyleft licenses allow you to modify the licensed code and distribute new works based on it, require that any derivative work of the copyleft-licensed software be released under the same license as the original software.</p><p>Example — GPL, Mozilla Public License, Eclipse Public License, Microsoft Reciprocal License, etc.</p><h3>2. Proprietary Software License Types</h3><p>Proprietary software consists of software that is licensed by the copyright holder under very specific conditions. In general, you can use the software, but you are not allowed to modify the software or distribute it to others.</p><p>Examples — Microsoft Windows, Adobe Flash Player, PS3 OS, iTunes, Adobe Photoshop, Google Earth, macOS, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*edujKAc4V-KYEbsC9dDjlg.png" /></figure><h3>The most common types of software licensing models</h3><p><strong>Perpetual License — </strong>A perpetual software license grants users permission to use the software forever, for a single one-time cost.</p><p><strong>Floating License — </strong>A license where many machines may have the software installed, but only a specific number of machines may run it at a time.</p><p><strong>Subscription License — </strong>Purchased on a monthly or annual basis and grant the user rights to operate the software only during the specified subscription period.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*mgLZ-2HOA6-VV9eozg2fSw.jpeg" /></figure><h3>Copyright Law</h3><p>Copyright law refers to the legal right of the owner of intellectual property. In simpler terms, copyright is the right to copy. This means that the original creators of products and anyone they give authorization to are the only ones with the exclusive right to reproduce the work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*R_Yag0rf7kfYrgyHuzhM9g.png" /></figure><h3>Ownership vs. licensing</h3><p><strong>Ownership: </strong>full rights to do whatever you want with the software &amp; code. The original creator has transferred full rights to you.</p><p><strong>licensing: </strong>permission by the owner of the software to do certain things with the software, as detailed in the license agreement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hXMdOwKLiIwud4MmWUqDHA.png" /></figure><h3>Why You Should Use Licensed Software</h3><ul><li>Using Unlicensed Software Is Against the Law</li><li>Licensed Software Offers Better Protection from Cybersecurity Threats</li><li>The Right Software License Can Save You Money</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RkY-v1Lx_RWwJYVM5AxF5A.jpeg" /></figure><h3>How to Select the Correct Software License</h3><p>Before downloading software it is important to understand what you will need it for, how you will use it, and how many computers it will be used on.</p><p>When purchasing software, try to go through official channels and websites. Most legitimate software companies have customer service lines or trialware that you can use first. Don’t immediately trust an offer or a website because the price is lower. If the price seems too good to be true then it probably is.</p><p>Take the time to read the software licensing and fully understand the terms and conditions. Watch out for unusual restrictions or obligations. Remember, even free and open-source software can include obligations for reuse.</p><p><em>Being smart about software licensing can put you in a position to be successful and can save you a lot of headaches in the long run.</em></p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38437f7e5e13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EVALUATION: INSPECTIONS, ANALYTICS, AND MODELS]]></title>
            <link>https://medium.com/@nethminid1999/evaluation-inspections-analytics-and-models-c922175f3389?source=rss-6b0a279af35d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c922175f3389</guid>
            <category><![CDATA[heuristic-evaluation]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[predictive-model]]></category>
            <category><![CDATA[interactive-walkthroughs]]></category>
            <category><![CDATA[web-analytics]]></category>
            <dc:creator><![CDATA[Nethmini Devyanjalee]]></dc:creator>
            <pubDate>Tue, 03 Aug 2021 10:21:12 GMT</pubDate>
            <atom:updated>2021-08-03T10:21:12.634Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*2akPiXeHS9OXglIIv6eAuA.png" /></figure><p>Imagine that you designed an app for youngsters to make videos. You prototyped your initial design and implemented the core functionality. how would you find out whether it would appeal to them and whether they will use it? you would need to evaluate it — but how? This chapter presents an introduction to the main types of evaluation and the methods that you can use to evaluate design prototypes and design concepts.</p><p>Evaluation provides a systematic method to study a program, practice, intervention, or initiative to understand how well it achieves its goals. Evaluations help determine what works well and what could be improved in a program or initiative.</p><h3>Inspections</h3><p>Evaluation performed by the usability expert without directly involving the user. Inspection methods for interaction design include heuristic evaluations and walk-throughs.</p><h4>Heuristic Evaluation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gmx8t_gZH36-Vtc6jNXlZA.png" /></figure><p>A heuristic evaluation can be outlined as a review of your user interface, looking closely at user experience aspects. It helps to spot several types of user experience issues and is conducted against a set of design principles — also known as heuristics.</p><p>Many people use a set of ten common heuristics from Jakob Neilsen’s 10 Usability Heuristics for User Interface Design:</p><ol><li><strong>Visibility of system status</strong></li></ol><p>The system should always keep users informed about what is going on, through appropriate feedback within a reasonable time.</p><p>Example — Gmail application- iPhone</p><p>Here you can easily see the series of feedback designed for the user to show the status. It is divided into 3 parts,</p><p>-Sending(uploading the files)</p><p>-Finishing(completing the upload procedure)</p><p>- Done(files have been successfully uploaded)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tYCECz6AtVa4U_2C5rd3HA.jpeg" /></figure><p><strong>2. Match between system and the real world</strong></p><p>The system should speak the user’s language, with words, phrases, and concepts familiar to the user, rather than system-oriented terms. Follow real-world conventions, making information appear in a natural and logical order.</p><p>Example — We are very familiar with our daily trash bins. So, whenever we see a similar recycle or trash bin icon in a system, we can easily understand that we can drag a file/folder to delete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/1*zzRIrVA2xM-ewfkS1bG4Tg.jpeg" /></figure><p><strong>3. User control and freedom</strong></p><p>Users often choose system functions by mistake and will need a marked “emergency exit” to leave the unwanted state without having to go through an extended dialogue. Support undo and redo.</p><p>Example — When you send an email from your Gmail account, you immediately have the option to ‘undo’ and the system will recall the message. They’ve put this option front and center for a reason.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*LFf9Hi-0lJ6Xs8GlFaq0XA.png" /></figure><p><strong>4. Consistency and standards</strong></p><p>Users should not have to wonder whether different words, situations, or actions mean the same thing. Follow platform conventions.</p><p>Example — In web design, headers of websites usually include the same elements: Logo, menu, and call-to-action buttons such as “Sign In” or “Get started”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4T-k5EAX_HXvwIaKpsqhVA.png" /></figure><p><strong>5. Error prevention</strong></p><p>Even better than good error messages is a careful design that prevents a problem from occurring in the first place. Either eliminate error-prone conditions or check for them and present users with a confirmation option before they commit to the action.</p><p>Example — Microsoft Recycle Bin- Windows OS</p><p>If the user deleted one of the important files in a hurry while deleting the unimportant files, Microsoft gives the ability to restore or recover the deleted file from the recycle bin at ease. But it’s only possible if you have simply deleted and not the shift + delete (permanently deleted).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*TijY9zz8KxtpBCceb88G3g.jpeg" /></figure><p><strong>6. Recognition rather than recall</strong></p><p>Minimize the user’s memory load by making objects, actions, and options visible. The user should not have to remember information from one part of the dialogue to another. Instructions for use of the system should be visible or easily retrievable whenever appropriate.</p><p>Example — When you google, it gives you a list of suggestions as you type in based on your previous searches and related most searches. It also lists your matching bookmarks as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*hr0eA8BOvjtSSVT9II7Zrg.png" /></figure><p><strong>7. Flexibility and efficiency of use</strong></p><p>Accelerators — unseen by the novice user — may often speed up the interaction for the expert user such that the system can cater to both inexperienced and experienced users. Allow users to tailor frequent actions.</p><p>Example — Adobe Photoshop- Windows Software</p><p>Adobe allows the user to be enough flexible to edit and make their series of shortcuts. This flexibility is for the advanced set of users. Users can change and create shortcuts according to the area of their profession.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c5cI_1GHCMj6Kg37PkNkHw.jpeg" /></figure><p><strong>8. Aesthetic and minimalist design</strong></p><p>Dialogues should not contain information that is irrelevant or rarely needed. Every extra unit of information in a dialogue competes with the relevant units of information and diminishes their relative visibility.</p><p>Example — the Google homepage, where mainly we have only the search bar and really few more possible interactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*oWngs4czzGCI1nhgtiyDSA.png" /></figure><p><strong>9. Help users recognize, diagnose, and recover from errors</strong></p><p>Error messages should be expressed in plain language (no codes), precisely indicate the problem, and constructively suggest a solution.</p><p>Example — YouTube Tells that they are offline but can still watch the downloaded videos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*jlvfjhze-WiprzFn14IGHg.png" /></figure><p><strong>10. Help and documentation</strong></p><p>Even though it is better if the system can be used without documentation, it may be necessary to provide help and documentation. Any such information should be easy to search, focused on the user’s task, list concrete steps to be carried out, and not be too large.</p><p>Example — Canva’s Help Center</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5_d8JM_csmLv_lt8nIyXQ.png" /></figure><h4>walk-throughs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*jSJ20o9e4BB65s5rZTacow.png" /></figure><p>walk-throughs involve walking through a task with the product and noting problematic usability features. In this section, we consider cognitive and pluralistic walk-throughs.</p><p><strong><em>Cognitive Walk-Throughs</em></strong></p><p>Cognitive walkthroughs are designed to see whether a new user can easily carry out tasks within a given system. It is a task-specific approach to usability in contrast to heuristic evaluation which is a more holistic usability inspection.</p><p>The main steps involved in cognitive walk-throughs are as follows:</p><ol><li>The characteristics of typical users are identified and documented, and sample tasks have been developed that focus on the aspects of the design to be evaluated. A description, mock-up, or prototype of the interface to be developed is also produced, along with a clear sequence of the actions needed for the users to complete the task.</li><li>A designer and one or more UX researchers come together to do the analysis.</li><li>The UX researchers walk through the action sequences for each task, placing it within the context of a typical scenario. As they do this, they try to answer the following questions:</li></ol><ul><li>Will the correct action be sufficiently evident to the user?</li><li>Will the user notice that the correct action is available?</li><li>Will the user associate and interpret the response from the action correctly?</li></ul><p>4. As the walk-through is being done, a record of critical information is compiled.</p><p>5. The design is then revised to fix the problems presented. Before making the fix, insights derived from the walk-through are often checked by testing them with real users.</p><p><strong><em>Pluralistic Walk-Throughs</em></strong></p><p>The pluralistic walkthrough involves both users and members of the product team. In this method, a facilitator presents participants with an image of the interface for each step in a task and asks them to write down what they would do at each step to get to the next step in a task. After the participants have written their answers for each step, the facilitator reveals the “correct answer” and invites discussion.</p><p><em>Benefits:</em></p><ul><li>Include a strong focus on users’ tasks at a detailed level</li><li>The researchers bring a variety of expertise and opinions for interpreting each stage of the interaction.</li><li>“Design, Prototyping, and Construction,” by involving a multidisciplinary team in which users play a key role.</li></ul><p><em>Limitations:</em></p><ul><li>Only a limited number of scenarios, and hence paths through the interface, can usually be explored because of time constraints.</li><li>The limitations with this approach include having to get the researchers together at one time and then proceed at the rate of the slowest.</li></ul><h3>Analytics</h3><h4>Web analytics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*l-_wYJJf8CuiSIlIZhSsJA.jpeg" /></figure><p>Web analytics groups together the measurement, collection, analysis, and presentation of data from the Internet to understand and optimize how websites are used. Web analytics lets you precisely study user behavior on your websites (and mobile sites, and mobile applications, which is more largely called digital analytics).</p><p><strong><em>Web Analytics Process</em></strong></p><ul><li>Collection of data - Exactly what it says, collection of the basic, elementary data. Typically, this data is the count of things.</li><li>Processing of data into information - At this stage, you typically take counts and make them ratios, although there are still some counts. You are taking your data and making it into information, specifically metrics.</li><li>Developing KPI - At this stage, you focus on those ratios (and counts) which are infused with business strategies. These are referred to as Key Performance Indicators (KPI). Many times, KPIs deal with conversion aspects, but not always.</li><li>Formulating online strategy - These are the online goals, objectives, and standards for your organization or business. Usually, these strategies are related to making money, saving money, or increasing market share.</li></ul><p><strong><em>Types of Web Analytics</em></strong></p><p><em>1.On-site</em></p><p>It measures the users’ behavior once it is on the website. For example, measurement of your website performance.</p><p><em>2.Off-site</em></p><p>It is the measurement and analysis irrespective of whether you own or maintain a website. For example, measurement of visibility, comments, potential audience, etc.</p><p><strong><em>Web analytics tools</em></strong></p><ul><li>Google Analytics - traffic analytics tool from Google</li><li>Adobe Analytics - traffic analytics and multichannel data collection tool from Adobe</li><li>Mixpanel - advanced product and business analytics platform</li><li>Matomo - free and open-source traffic analytics</li><li>Statcounter - web traffic analytics</li><li>Yandex Metrica - free all-in-one website analytics from Russian search engine Yandex</li><li>Amplitude - product intelligence</li></ul><h4>A/B testing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*MjwIa-1mrYnZU_iUaI0sfA.jpeg" /></figure><p>A/B testing, otherwise known as split testing, is the process of testing two different versions of a web page or a product feature to optimize conversion rate or improve upon a certain business metric. The two versions can be very similar, with only a change in button color, or very different, with a total change in the way a feature behaves.</p><p><strong><em>Why should you consider A/B testing?</em></strong></p><ul><li>Solve visitor pain points</li><li>Get better ROI from existing traffic</li><li>Reduce bounce rate</li><li>Make low-risk modifications</li><li>Achieve statistically significant improvements</li><li>Redesign website to increase future business gains</li></ul><p><strong>How To Conduct Efficient A/B testing</strong></p><p><em>Step 1:</em> Pick one variable to test.</p><p><em>Step 2:</em> Split your sample groups equally and randomly.</p><p><em>Step 3:</em> Test both variations simultaneously.</p><p><em>Step 4:</em> Give the A/B test enough time to produce useful data.</p><p><em>Step 5:</em> Measure the significance of your results using our A/B testing calculator.</p><p><em>Step 6:</em> Take action based on your results.</p><p><strong><em>Example</em></strong></p><p>Changing copy of Facebook Ad increases Facebook likes from 0 to 70!</p><p>Wanted to increase the number of likes on their Facebook page. They ran two Facebook ads to see which one would result in a higher number of likes.</p><p>Hypothesis: Keeping everything else the same they just changed the copy on their ads (see below.)</p><p>Result: Version A “LIKE us for pro tips on how to improve your Facebook ad campaigns today!” resulted in 70 Facebook likes. Version B didn’t even get 1 like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*dqSczudx3ZERNaP1jwccIw.png" /></figure><h3>MODELS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ihW4IoD9VGqtvciADfmA5Q.png" /></figure><h4>Predictive Models</h4><p>predictive models can be used to evaluate a product without users being present. Rather than user researchers being involved in role-playing during inspections, or tracking their behavior using analytics, predictive models use formulas to derive various measures of user performance. Predictive modeling provides estimates of the efficiency of different systems for various kinds of tasks.</p><p><strong><em>Fitts’ Law</em></strong></p><p>One kind of predictive model that has been influential in HCI and interaction design over the years is Fitts’ law.</p><p>This scientific law predicts that the time required to rapidly move to a target area is a function of the ratio between the distance to the target and the width of the target. Fitts’s law is used to model the act of pointing, either by physically touching an object with a hand or finger, or virtually, by pointing to an object on a computer monitor using a pointing device.</p><p><em>Fitts’ law states that:</em></p><p>T = klog2(D/S +1 .0)</p><p>where,</p><p>T = time to move the pointer to a target</p><p>D = distance between the pointer and the target</p><p>S = size of the target</p><p>k is a constant of approximately 200 ms/bit.</p><p><em>Fitts’ Law Applications</em></p><ul><li>Usually, the cursor automatically stops at the edges of the screen. Put UI elements in the corners of the screen, and they will be easier to click on.</li></ul><p>Example — Windows 10 Home (update 2020), menu and app icons in the bottom left corner, other icons in the bottom right corner. Moreover, the Windows menu is square to shorten the time to reach menu items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*jQiTL72g7t-McdtALxU4cQ.png" /></figure><ul><li>Larger targets are easier to click on. Clickable areas should be as large, as possible.</li></ul><p>Example — facebook.com, Big Log In button right under the form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*btp2c9oSP2rLZBuhSdmLKw.png" /></figure><p>“We have to stop optimizing for programmers and start optimizing for users”</p><p>References:</p><p>Helen Sharp, Jenny Preece, Yvonne Rogers — Interaction Design_ Beyond Human-Computer Interaction-Wiley (2019)</p><p><a href="https://en.wikipedia.org/wiki/Main_Page">Wikipedia</a></p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c922175f3389" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>