<?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 Pubudu Wickramathunge on Medium]]></title>
        <description><![CDATA[Stories by Pubudu Wickramathunge on Medium]]></description>
        <link>https://medium.com/@pwickramathunge?source=rss-21dcb68bd36e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ejJwzDYyisnw856fdivQpA.jpeg</url>
            <title>Stories by Pubudu Wickramathunge on Medium</title>
            <link>https://medium.com/@pwickramathunge?source=rss-21dcb68bd36e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 16:52:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pwickramathunge/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[Difference Between Struct, Protocol, and Class in Swift]]></title>
            <link>https://pwickramathunge.medium.com/difference-between-struct-protocol-and-class-in-swift-6da9d5419edf?source=rss-21dcb68bd36e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6da9d5419edf</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Pubudu Wickramathunge]]></dc:creator>
            <pubDate>Tue, 16 Aug 2022 10:29:40 GMT</pubDate>
            <atom:updated>2022-08-16T10:29:40.427Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a3XvFFFZ2lpMu1fvSt91mQ.jpeg" /></figure><p>Swift is an open-source, general-purpose programming language developed by Apple Inc. The language is safe, fast, and expressive and It’s intended to be a replacement for C-based languages including Objective-C. Swift is mainly used for native iOS, iPadOS, macOS, tvOS, and watchOS development. In late 2015, the Swift language became open-sourced under the Apache license and Swift.org was created to host the project. Because of that, the Swift source code can be found on GitHub, making it easy for anyone to access the code and contribute to the development. Since Swift language is open-sourced and backed by Apple it is constantly evolving, and the community continues to grow. Swift is a great language to learn If you’re interested in iOS development.</p><p>In this article, I&#39;m hoping to give you a clear idea about what is Structure, protocol, and class, and how those differ from each other.</p><p><strong>What is a Structure?</strong></p><p>Swift provides a flexible building block for making use of constructs as Structures. By making use of these structures one can define the construct&#39;s methods and properties. Unlike Objective C Structure need not require implementation files and interface. It allows the developer to create a single file and extend its interface automatically to other blocks. In Structure, the variable values are copied and passed in subsequent codes by returning a copy of the old values so that the values cannot be altered.</p><p>Structures use to,</p><p>· Encapsulate simple data values.</p><p>· Copy the encapsulated data and its associated properties by ‘values’ rather than by ‘references’.</p><p><strong>What is a Class?</strong></p><p>Classes in Swift are building blocks of flexible constructs. Similar to constants, variables, and functions the user can define class properties and methods. Swift language provides developers the functionality that while declaring classes the users need not create interfaces or implementation files. Once the classes are initialized Swift allows developers to create classes as a single file and the external interfaces will be created by default.</p><p>Classes use to,</p><ul><li>Inheritance acquires the properties of one class to another class</li><li>Type casting enables the user to check the class type at run time</li><li>Deinitializers take care of releasing memory resources</li><li>Reference counting allows the class instance to have more than one reference</li></ul><p><strong>What is a Protocol?</strong></p><p>Protocols provide a blueprint for Methods, properties, and other requirements functionality. A protocol is just described as a methods or properties skeleton instead of implementation. Methods and properties implementation can further be done by defining classes, functions, and enumerations.</p><h4>Struct vs Class</h4><p><strong>Similarities</strong></p><p><em>Classes</em> and <em>Structs</em> in Swift have many similar things such as:</p><ul><li>Allow defining properties to store values, define methods to provide functionality, and define subscripts to provide access to their values using subscript syntax.</li><li>Allow defining initializers to set up their initial state.</li><li>Allow expanding their functionality beyond a default implementation.</li><li>Allow conforming to protocols to provide standard functionality of a certain kind.</li></ul><p><strong>differences</strong></p><p>Struct and Classes are pretty similar in Swift. Still, there are quite a lot of important differences to be aware of.</p><ul><li>One of the most important differences is that a struct is a value type while a class is a reference type.</li></ul><p>Struct is the value type object, it is the member-wise initializer. It is called a value type because it passes the value to the function. When you use the struct whole thing is duplicated. It points to the value of the object and then shows the value.</p><p>Class is the reference type of object. It passes the reference data to the function. When class is used each object points to the same original object if the developer change one they all will change. It shows the reference to the real object.</p><ul><li>Structs are allocated in Stack memory.</li><li>Reference of the class object can be created on the Stack but the properties of the class object are stored in the heap.</li><li>A class can inherit the property or characteristics of another class. But in struct, it is not possible.</li><li>Deinitializers are only available on class types. We can de-initialize the class resource at any instant.</li></ul><h4>Protocol vs Class/ struct</h4><p>In their basic form, a protocol describes what an unknown type of object can do. It might have two or three properties of various types, and methods. But it never includes anything <em>inside</em> the methods or provides actual storage for the properties.</p><p>In comparison, classes are concrete things. While they might adopt protocols. You can create objects from classes, whereas protocols are just type definitions. Think of protocols as being abstract definitions, whereas classes and structs are real things you can create.</p><h4>Conclusion</h4><p>Protocols are effectively like interfaces. Classes are classes, like in Java/Android, and pretty much any other language. Structs are like classes, but they are passed by-value. Swift is encouraging users to use struct. So it is better to get used to that concept but in the end, it&#39;s all up to you whether to use struct or class.</p><p>Hope you find this article helpful. Until we meet with another article, stay safe!</p><p>Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6da9d5419edf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluation techniques for interactive systems]]></title>
            <link>https://pwickramathunge.medium.com/evaluation-techniques-for-interactive-systems-63a34081872d?source=rss-21dcb68bd36e------2</link>
            <guid isPermaLink="false">https://medium.com/p/63a34081872d</guid>
            <category><![CDATA[hci]]></category>
            <dc:creator><![CDATA[Pubudu Wickramathunge]]></dc:creator>
            <pubDate>Sat, 30 Apr 2022 21:11:52 GMT</pubDate>
            <atom:updated>2022-04-30T21:11:52.753Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U59DFfC0IpQypQxoPNoOLA.jpeg" /></figure><p>Software engineering is the look at designing, developing, and renovating software. It comes in touch with HCI to make the person and device interplay greater colorful and interactive.</p><p>Evaluation is a manner that seriously examines a program. It includes gathering and studying statistics about a program’s activities, characteristics, and outcomes.</p><p>The assessment itself can contain many unique human beings from designers and evaluators to real customers of the system.</p><p>Evaluation has 3 major goals:</p><p><strong>· Assess the quantity and accessibility of the system’s functionality.</strong></p><p>The system’s functionality is vital in that it needs to accord with the user’s requirements. Evaluation at this level may also measure the user’s overall performance with the system to evaluate the effectiveness of the system in helping the task.</p><p><strong>· Assess customers’ experience of the interaction. </strong><br> It is important to evaluate the user’s experience of the interaction and its effect on the user. And consists of thinking about factors such as how easy the system is to learn, its usability, and the user’s satisfaction with it. It may additionally consist of his entertainment and emotional response, especially in the case of structures that are aimed at enjoyment or entertainment.</p><p><strong>· Identify any specific problems with the system. </strong><br> These can be elements of the design that, when used in their supposed context, cause unexpected results, or confusion among users. And it is associated with each the functionality and usability of the design.</p><p>The very last purpose of assessment is to discover specific problems with the design. These can be elements of the layout that, while the use of their supposed context, cause unexpected results, or confusion among customers.</p><h4>Evaluation through expert analysis</h4><p>The evaluation of a system needs to ideally take place earlier than any implementation work begins. If the design itself may be evaluated, expensive errors may be prevented because the design can be modified earlier than any large resource commitments are made. A variety of techniques for evaluating interactive structures and the use of expert evaluation were developed. These techniques are flexible evaluation methods because they’ll be applied at any point of the development process, from design specifications through storyboards and prototypes to full implementations.</p><p>There are a few expert-based assessment approaches.</p><ul><li><strong>Cognitive Walkthrough</strong></li></ul><p>This is one of the most efficient and extremely cost-effective ways of increasing the usability of the system. Most users prefer to do things to learn a product rather than to study a guide or follow a set of instructions. So with this evaluation, it is confident that the design is easy to pick up through a beginner and takes much less time to turn out to be professional in using the design.</p><p>The expert must have a specification or prototype of the system, a description of duties, and an additionally written list of the actions needed to complete the task with the proposed system to do this walkthrough.</p><ul><li><strong>Heuristic Evaluation</strong></li></ul><p>In a heuristic evaluation, a small number of usability evaluators systematically inspect a user interface and make decisions based on a predetermined set of usability principles known as heuristics. Heuristics are general rules that describe common properties of usable user interfaces.</p><ul><li><strong>Model-based evaluation</strong></li></ul><p>Model-based evaluation is the use of a model of how a human could use a proposed system to achieve predicted usability measures through calculation or simulation. These predictions can replace or supplement empirical measurements received through user testing. Model-based evaluation is combining cognitive and design models for the evaluation process.</p><h4>Evaluation through user participation</h4><p>User participation in evaluation tends to arise in the later stages of development while there’s at least a working prototype of the system in place. This may range from a simulation of the system’s interactive capabilities, without its underlying functionality.</p><p><strong>Styles of evaluation</strong></p><p>Laboratory studies:</p><p>Users are taken out of their ordinary work environment to participate in controlled tests, often in a specialist usability laboratory.</p><p>Field studies :</p><p>This type of evaluation takes the designer or evaluator out into the user’s work environment to observe the system in action.</p><h4>Empirical methods: experimental evaluation</h4><p>This presents empirical proof to support a specific claim or hypothesis. The evaluator chooses a hypothesis to test. Any modifications in the behavioral measures are attributed to the specific conditions.</p><h4>Observational Techniques</h4><ol><li><strong>Think aloud</strong></li></ol><p>In this technique, the user is requested to talk through what he’s doing as he’s being observed.</p><p><strong>2. Cooperative evaluation</strong></p><p>A variation on think-aloud is referred to as cooperative evaluation. In this approach, the user is recommended to look at himself as a collaborator in the evaluation and not actually as an experimental participant.</p><p><strong>3. Automated Analysis</strong></p><p>Analyzing protocols, whether or not video, audio or system logs, is time-consuming and tedious by hand. It is tough if there may be multiple stream of information to synchronize. So, automatic analysis gives tools like EVA ( Experimental Video Annotator ) that’s a system that runs on a multimedia workstation with an immediate link to a video recorder to support the task.</p><p>4. <strong>Post-task walkthrough</strong></p><p>the participants have to perform tasks in a recorded session and are then later asked by a moderator to reflect on their actions. But the disadvantage of this method is loss of freshness.</p><p><strong>5. Protocol Analysis</strong></p><h4>Query Techniques</h4><ol><li><strong>Interviews</strong></li></ol><p>Interviewing users about their experience with an interactive system provides a direct way of gathering information.</p><p>2. <strong>Questionnaires</strong></p><p>Users are given a set of fixed questions about what they prefer and what they think about the design. This gives the chance to reach a group of people. But this is less flexible.</p><h4>Evaluation through monitoring physiological responses</h4><p>This will allow seeing more clearly what users do when they interact with computers and how they feel.</p><p><strong>Physiological Measurements</strong></p><p>Measuring physiological responses like heart rate, breathing, and skin secretions may use in determining a user’s emotional response to an interface.</p><p>Hope you found this article helpful!</p><p>See you in another article.</p><p>Thank you!</p><p><em>Reference</em>: <em>Alan Dix, Janet Finlay, Gregory Abowd, and Russell Beale. 2003. Human–Computer Interaction(3rd Edition). New York: Prentice-Hall</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63a34081872d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Build An Operating System: User Mode - Part 09]]></title>
            <link>https://pwickramathunge.medium.com/how-to-build-an-operating-system-user-mode-part-09-747630f0afa8?source=rss-21dcb68bd36e------2</link>
            <guid isPermaLink="false">https://medium.com/p/747630f0afa8</guid>
            <category><![CDATA[user-mode]]></category>
            <category><![CDATA[operating-systems]]></category>
            <dc:creator><![CDATA[Pubudu Wickramathunge]]></dc:creator>
            <pubDate>Mon, 27 Sep 2021 16:52:53 GMT</pubDate>
            <atom:updated>2021-09-27T17:09:22.252Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone!. This is the 9th article of this building an own operating system article series. Please read the first seven articles in this article series if you didn’t read those. It will help you to understand this article more. Let&#39;s jump into today&#39;s chapter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6Nc3hK98loPXP_D5GVxlw.jpeg" /></figure><p>In this article, we are going to discuss user mode. We are only a few steps away from our destination but these steps are hard and tricky. So I hope you will follow these steps very carefully with me. We talked about user-mode briefly in previous articles. You can refer to that article <a href="https://pwickramathunge.medium.com/how-to-build-an-operating-system-user-modes-part-06-65d433cdd061">here</a>. Here we will discuss that more deeply.</p><p>To enable user mode, we should add two more segments to the GDT and they are very similar to the kernel segments we added in previous articles.</p><p>The segment descriptors needed for user mode as following:</p><pre>Index       Offset Name             Address range          type DPL<br>  3    0x18user code segment    0x00000000 - 0xFFFFFFFFRX     PL3<br>  4    0x20user data segment    0x00000000 - 0xFFFFFFFFRW     PL3</pre><p>DPL now allows code to execute in PL3. We need paging to protect the kernel because just using these segments won’t protect it.</p><h4>Setting Up For User Mode</h4><ul><li>Page frames for code, data, and stack. It suffices to allocate a one-page frame for the stack and enough page frames to fit the program’s code. Get basic implementation work first.</li><li>The binary from the GRUB module should be copied to the page frames used for the program&#39;s code.</li><li>Above mentioned page frames need to be mapped using a page dictionary and page tables. For that, we need at least two-page tables since code and data must be mapped in at 0x00000000 and increasing from there, and the stack should start from below the kernel, at 0xBFFFFFFB, growing towards lower addresses. <em>The U/S flag needs set to allow PL3 access.</em></li></ul><h4>Entering User Mode</h4><p>The only way to execute code with a lower privilege level than the current privilege level is executing an iret or lret instruction — interrupt return or long return.</p><p>After setting up the stack as if the processor had raised an inter-privilege level interrupt to enter user mode the stack should look like this:</p><pre>[esp + 16]  ss         ; the stack segment selector for user mode<br>[esp + 12]  esp        ; the user mode stack pointer<br>[esp +  8]  eflags     ; the control flags want to use in user mode<br>[esp +  4]  cs         ; the code segment selector<br>[esp +  0]  eip        ; instruction pointer of user mode to execute</pre><p>The instruction iret will read these values from the stack. And then it will fill in the corresponding registers. We need to change the page directory we set up for the user-mode process before we execute iret. You need to continue executing kernel code after switched PDT. And the kernel needs to be mapped in. To accomplish this we need to have a separate PDT for the kernel, which maps all data at 0xC0000000 and above and merges it with the user PDT which only maps below 0xC0000000 when performing the switch. The physical address of the PDT has to be used when setting the register cr3.</p><p>The <em>eflags</em> register contains a set of different flags. The interrupt enables (IF) flag is the most important for this. In privilege level 3, the assembly code instruction <em>sti</em> cannot be used to enable interrupts. Interrupts cannot be enabled once user mode is entered if interrupts are disabled before entering user mode. The assembly code instruction <em>iret</em> sets the register <em>eflags</em> to the matching value on the stack, setting the<em> IF flag</em> in the eflags register entry on the stack will enable interrupts during the user-mode. We should have interrupts disabled for now. It requires some work to get inter-privilege level interrupts to work correctly. The value eip on the stack should be pointing to the entry point for the user code - 0x00000000 . The value esp on the stack should be where the stack starts - 0xBFFFFFFB (0xC0000000 - 4).</p><p>Respectively the values cs and ss on the stack should be the segment selectors for the user code and user data segments. The lowest two bits of a segment selector is the Requested Privilege Level. The RPL of cs and ss should be 0x3when using iret to enter PL3.</p><p>Here is 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 other data segment registers, and the register ds should be set to the same segment selector as ss. With the mov assembly code instruction, they can be set the ordinary way. Now we can execute iret. Now the kernel should be able to enter user mode.</p><h4>Using C for User Mode Programs</h4><p>We write user-mode programs in C and compile them to flat binaries. In this way, the generated code is more unpredictable. And the entry point, main, may not be at offset 0 in the binary. Adding few assembly code lines placed at offset 0 which calls mainwill solve this as below.</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>save this code in a file called start.s.Here is an example for linker script that places these instructions first in executable:</p><pre>OUTPUT_FORMAT(&quot;binary&quot;)   /* output flat binary */</pre><pre>SECTIONS<br>{<br>     = 0;                 /* relocate to address 0 */</pre><pre>     .text ALIGN(4):<br>     {<br>         start.o(.text)   /* include the.text section of start.o */<br>         *(.text)         /* include all other .text sections */<br>     }</pre><pre>     .data ALIGN(4):<br>     {<br>         *(.data)<br>     }</pre><pre>     .rodata ALIGN(4):<br>     {<br>         *(.rodata*)<br>     }<br>}</pre><p>Now we can write programs in C or assembler or any other language that compiles to object files linkable with ld. As well as it is easy to load and map for the kernel.</p><p>We want the following GCC flags when we compiling user programs:</p><pre>-m32 -nostdlib -nostdinc -fno-builtin -fno-stack-protector -     nostartfiles</pre><pre>-nodefaultlibs</pre><p>The followings flags should be used for linking:</p><pre>-T link.ld -melf_i386  # emulate 32 bits ELF, the binary output is specified<br>                       <br>                       # in the linker script</pre><p>The option -T instructs the linker to use the linker script link.ld.</p><p>This is all for this article. Hope you get the idea and see you with the next article and there, we will be discussing File Systems as the next part.</p><p>Thanks for reading!.</p><p>References,</p><p><a href="https://littleosbook.github.io/">The little book about OS development</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=747630f0afa8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4+1 Architectural View Model]]></title>
            <link>https://pwickramathunge.medium.com/4-1-architectural-view-model-52887d8cafa?source=rss-21dcb68bd36e------2</link>
            <guid isPermaLink="false">https://medium.com/p/52887d8cafa</guid>
            <dc:creator><![CDATA[Pubudu Wickramathunge]]></dc:creator>
            <pubDate>Fri, 17 Sep 2021 17:23:27 GMT</pubDate>
            <atom:updated>2021-09-17T18:20:04.928Z</atom:updated>
            <content:encoded><![CDATA[<p>Software architecture is a key factor in the process of turning requirements into a system. It is the process of designing, building, and delivering software that meets all software requirements in a defensible and reusable manner. The architectural view model is a key component in understanding the architecture perspective of a system. A model is used to represent an architectural perspective or view on a wide variety of architectural topics. This paper provides an overview of the 4+1 architectural view model’s history, evolution, modeling description, and current usage, etc.</p><h4><strong>History of the 4+1 architectural view model</strong></h4><p>In 1995 Philippe Kruchten was working at Rational Software Corp as a Software Engineer. With years of experience designing large-scale complex software systems, Kruchten had observed that the software architecture diagrams are failed to provide clarity as to the actual system. It was frequently confusing, and stakeholders struggled to discover the information they needed.</p><p>As the solution, he published the “Architectural Blueprints-The 4+1 View Model of Software Architecture” paper that year. It organizes the description of a software architecture using a set of concurrent called views. Each view addresses specific concerns, for specific stakeholders.</p><h4><strong>View models</strong></h4><p>The 4+1 View Model provides four essential views</p><p>• The logical view describes the object model of the design. The logical view describes the structures of the software that solve the functional requirements. It is a subset of all the classes of the system. It is strictly a structural view of the software, including the important classes and class relationships in the architecture.</p><p>• The process view describes the activities of the system, captures the synchronization aspects and concurrency of the design. The process view, or process architecture, describes the view of the architecture that includes running processes and instantiated objects that exist in the system.</p><p>• The physical view describes the machines run the software and how components and objects are deploy to the machines and their configurations.</p><p>• The development view describes the static organization or structure of the software in its development of environment. It focuses on the module organization of the software. This view shows how classes are organized into packages, and it outlines the dependencies between packages of software. Development view is the view of the design that shows the layered structures of the software and what the responsibilities of each layer in the system are.</p><p>This model extends by adding one more view called the use case(scenario) view. The requirement that the system must satisfy represents by scenarios. The scenarios that are chosen are those that are the most important to solve because they are either the most frequently executed or they pose some technical risk or unknown that must be proven out by the architecture baseline. This view has a special significance as it details the high-level requirement of a system. All other four views would not be possible without it. Because of that specialty, this method is called the 4+1 view model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*eavT2F3ehhR6fiFbMEqHnw.png" /><figcaption>view models in 4+1 architectural view model</figcaption></figure><h4><strong>Evolution 4+1 architectural view model</strong></h4><p>The 4+1 view model has been widely imported from the software engineering community. The original paper “The 4+1 View Model of Software Architecture” was hosted on NASA’s Web site, and later in 1998, it was superseded by a paper published by NASA. In that year NASA re-hosted its 1998 paper on their website. A copy of this paper is included with this report for reference purposes only.</p><p>The following decade marked the beginning of the 4+1 architectural view method. First of all, the 4+1 architectural view model was extended by Chuck McMullan in 2001 (Logical View). Then in 2004, Bob Bishop published an article about using this model to analyze designs for twenty or so years. The paper was titled “Software Architecture on the Road to Abstraction”. The 4+1 View Model is used in Software Architecture Document (SAD) and has been further extended into a 5+1 view model, which also includes a deployment view. Although these are some important extensions, they are not yet considered as “the” 4+1 architectural view model.</p><h4><strong>Current usage of 4+1 architectural view model</strong></h4><p>This model is used throughout the industry for describing system architectures. As a result of its use, the 4+1 view is gaining more and more popularity as a method for describing software architecture. This paper also shows the 4+1 view model is a powerful and flexible model. It provides great value to both experts and novices while modeling an architecture. It can be used to record both static and dynamic aspects of the design.</p><p>The 4+1 view model is used because it delivers clarity and reduces confusion in understanding the requirements and the design. The use of this model allows an agile team to understand better and fit into a development environment that satisfies their desired practices and goals. However, there can be many variations on the 4+1 architectural view model. The usage of this model in most industrial organizations with practices like RUP, TOGAF, Zachman Framework, etc.</p><h4><strong>Limitations</strong></h4><p>The style used to present the model has not been given a good solution by its creators and instead it is still in need. The current version of this method has not been reviewed and so it suffers from the same problems as other architectural models.</p><p>conclusion of this is that the 4+1 model is a good starting point for logical and process-oriented analysis of an organization and it is a good starting point. The model has been used in various organizations and is currently in use in some groups that have been more successful than others.</p><p>Thanks for reading!.</p><p>References</p><p>1. P. Kruchten <a href="https://www.cs.ubc.ca/~gregor/teaching/papers/4+1view-architecture.pdf">Architectural Blueprints — The “4+1” View Model of Software Architecture</a>.</p><p>2. <a href="https://en.wikipedia.org/wiki/4%2B1_architectural_view_model">4+1 architectural_view_model wikipedia.org</a></p><p>3. <a href="https://devcycles.io/2019/02/27/4-1-architectural-view-model-introduction/">4+1-architectural-view-model-introduction devcycles.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52887d8cafa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Build An Operating System: Page Frame Allocation- Part 08]]></title>
            <link>https://pwickramathunge.medium.com/how-to-build-an-operating-system-page-frame-allocation-part-08-e2a8cff8f44d?source=rss-21dcb68bd36e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2a8cff8f44d</guid>
            <category><![CDATA[operating-systems]]></category>
            <dc:creator><![CDATA[Pubudu Wickramathunge]]></dc:creator>
            <pubDate>Fri, 10 Sep 2021 15:43:55 GMT</pubDate>
            <atom:updated>2021-09-10T22:24:38.070Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the 8th article of this <a href="https://pwickramathunge.medium.com/list/how-to-build-an-operating-system-1ad3f9cd2417">building an own operating system article series</a>. If you didn’t read the first seven articles in this series, I recommend you to read those articles first.</p><p>We talked about virtual memory and paging in the last article. In this article, we will discuss page frame allocation. It uses to decide how many frames allocate to each process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*r2e_pYHYFZpX3viAys2qew.jpeg" /></figure><h3>Managing available memory</h3><p>To manage the memory we need to know how much memory is left in the computer. We can read that from the multiboot structure passed by the GRUB. GRUB collects the information about the memory like I/O mapped, what it reserved so on. GRUB doesn’t mark the memory as reserved by the kernel, we should also make sure that we don’t mark that part of the memory used by the kernel as free. We can know how much memory uses by the kernel, is to export labels from the linker script at the beginning and the end of the kernel binary as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c67cd3dc921d0757eb24ed4ad25e1edb/href">https://medium.com/media/c67cd3dc921d0757eb24ed4ad25e1edb/href</a></iframe><p>These labels can be read directly from the assembly code. It will 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>Using these we get the labels as arguments to kmain. You can declare the labels as functions and take the addresses of those functions if you want to use C language instead of assembly language.</p><pre>    void kernel_virtual_start(void);<br><br>    /* ... */<br><br>    unsigned int vaddr = (unsigned int) &amp;kernel_virtual_start;</pre><p>And also if you are using GRUB modules, you should make sure that the memory they use is marked as reserved. The available memory doesn’t need to be contiguous. Because we can’t map part of pages into memory it is convenient to divide the memory sections into complete page frames.</p><p>The page frame allocator needs to keep track of which page frames are free and which are in use. There are several ways to track that. Some of them are bitmaps, linked lists, trees, the Buddy System, etc. Here we are going to use bitmaps because it is easy to implement compared to other methods. In bitmaps, One bit is used for each page frame, and one or more page frames are dedicated to storing the bitmap.</p><h3>Accessing a Page Frame</h3><p>By updating the PDT and/or PT used by the kernel we should map the page frame into virtual memory. We can’t map the page frame into memory if all available page tables are full, because we would need a new page table that takes up an entire page frame, and to write to this page frame we would need to map its page frame. So this circular dependency must be broken. A solution is to reserve a part of the first-page table used by the kernel for temporarily mapping page frames to make them accessible. If the kernel is mapped at 0xC0000000, and the 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 of this page table for temporary mappings.</p><p>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 adding the page frame, we want to use as a page table and set it up to map in the first-page frame, we can add it to the paging directory, and remove the temporary mapping.</p><p>To this point, we have only been able to work directly with raw memory, or with fixed-size data. Now we have a page frame allocator and now we can implement malloc and free to use in the kernel.</p><p>So this is all for this week. See you next week.</p><p>Thanks for reading!.</p><p>References,</p><p><a href="https://littleosbook.github.io/">The little book about OS development</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2a8cff8f44d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Build An Operating System: Virtual Memory and Paging- Part 07]]></title>
            <link>https://pwickramathunge.medium.com/how-to-build-an-operating-system-virtual-memory-and-paging-part-07-c69587d08df4?source=rss-21dcb68bd36e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c69587d08df4</guid>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[paging]]></category>
            <category><![CDATA[virtual-memory]]></category>
            <dc:creator><![CDATA[Pubudu Wickramathunge]]></dc:creator>
            <pubDate>Mon, 06 Sep 2021 17:38:54 GMT</pubDate>
            <atom:updated>2021-09-07T08:25:44.843Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the seventh article of this building an own operating system article series. If you didn’t read the first six articles in this series, I recommend you to read those articles first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o5tP2oXQ6hvkJHIdE_4IZg.jpeg" /></figure><h3>Virtual Memory</h3><p>Virtual Memory is a storage scheme that provides users the illusion of having a very big main memory. This is done by treating a part of secondary memory as the main memory. In this technique, the user can load the bigger size processes than the available main memory by having the illusion that the memory is available to load the process. Instead of loading one big process in the main memory, the OS loads the different parts of more than one process in the main memory. By doing this, the degree of multiprogramming will be increased and CPU utilization will be increased.</p><h4>Advantages of Virtual Memory</h4><ul><li>It allows users to run more applications at a time.</li><li>Users can run a large application with less RAM.</li><li>Users can fit many large programs into smaller programs.</li><li>A multiprogramming environment can be easily implemented.</li><li>Data should be read from the disk at the time when required.</li><li>Common data can be shared easily between memory.</li></ul><p>Paging is the most common method to accomplish virtual memory. Segmentation is also used in some scenarios. Paging and page frame allocation deals with memory management in an operating system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*wteLp4ygSVJ11Ba2vaKZBA.png" /></figure><h3>Paging</h3><p>Paging is a memory management technique in which the memory is divided into fixed-size pages. Paging is used for faster access to data. When a program needs a page, it is available in the main memory as the operating system copies a certain number of pages from your storage device to the main memory. Paging allows the physical address space of a process to be noncontiguous. Data is retrieved from storage media by OS, in the same sized blocks called pages. Paging allows the physical address space of the process to be non-contiguous. The whole program had to fit into storage contiguously.</p><p>Paging is to deal with external fragmentation problems. This is to allow the logical address space of a process to be noncontiguous, which makes the process to be allocated physical memory.</p><h4>Paging in x86</h4><p>Paging in x86 consists of a page directory that can contain references to 1024 page tables, each of which can point to 1024 sections of physical memory called page frames. Each page frame is 4096 bytes large. In a virtual address, the highest 10 bits specifies the offset of a page directory entry 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. The PDE and PTE structure is very similar to each other: 32 bits, 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><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*ZA9elHKrPtoE8XO-PYLo2Q.png" /><figcaption>linear address translation to a 4KByte page using 32-Bit paging</figcaption></figure><p>The 20 bits pointing to the current PDT is stored in the register cr3. The lower 12 bits of cr3 are used for configuration.</p><h4>Identity Paging</h4><p>Identity paging is the simplest kind of paging. When we map each virtual address onto the same physical address it is 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 also be done at run-time by using ordinary assembly code instructions.</p><h4>Enabling Paging</h4><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.</p><p>The following assembly code shows an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc22574432b6b6f327a137ad2e418e21/href">https://medium.com/media/bc22574432b6b6f327a137ad2e418e21/href</a></iframe><h3>Paging and the Kernel</h3><p>We want the kernel to be part of the user-mode process’ address space. During system calls, we don’t have to change any paging structures to get access to the kernel’s code and data. The kernel pages will require privilege level 0 for access, to prevent a user process from reading or writing kernel memory.</p><h4>Placing the Kernel at 0xC0000000</h4><p>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 <em>higher-half kernel</em>. The kernel can be placed at any address higher than 0 to get the same benefits. If the user-mode process is larger than 3 GB, some pages will need to be swapped out by the kernel. We won&#39;t be discussing swapping pages in this article series.</p><p>It is better to place the kernel at 0xC0100000 than 0xC0000000, since this makes it possible to map (0x00000000, 0x00100000) to (0xC0000000, 0xC0100000). This way, the entire range (0x00000000, &quot;size of kernel&quot;) of memory is mapped to the range (0xC0000000, 0xC0000000 + &quot;size of kernel&quot;).</p><p>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. 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>For this, we have to modify the link.ld to implement this. The following code shows an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cf344e85a792ef61a5080d5eb7439ea/href">https://medium.com/media/8cf344e85a792ef61a5080d5eb7439ea/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>If we skip the identity mapping for the first 4 MB, the CPU would generate a page fault immediately after paging was enabled when trying to fetch the next instruction from memory. After the table has been created, a jump can be done to a label to make eip point to a virtual address in the higher half.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/633166794c3ad122f4c8571f875f446a/href">https://medium.com/media/633166794c3ad122f4c8571f875f446a/href</a></iframe><p>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. 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><h4>Virtual Memory Through Paging</h4><p>Paging enables allows for fine-grained access control to memory. and it creates the illusion of contiguous memory. User-mode processes, and the kernel, can access memory as if it were contiguous, and the contiguous memory can be extended without the need to move data around in memory. We can also allow the user-mode programs access to all memory below 3 GB, but unless they actually use it, we don’t have to assign page frames to the pages. This allows processes to have code located near 0x00000000 and the stack at just below 0xC0000000, and still does not require more than two actual pages.</p><p>This is the end of this week’s article. See you in the next one.</p><p>Thanks for reading!.</p><p>References,</p><p><a href="https://littleosbook.github.io/">The little book about OS development</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c69587d08df4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Build An Operating System: User Modes- Part 06]]></title>
            <link>https://pwickramathunge.medium.com/how-to-build-an-operating-system-user-modes-part-06-65d433cdd061?source=rss-21dcb68bd36e------2</link>
            <guid isPermaLink="false">https://medium.com/p/65d433cdd061</guid>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[user-mode]]></category>
            <dc:creator><![CDATA[Pubudu Wickramathunge]]></dc:creator>
            <pubDate>Fri, 27 Aug 2021 14:20:26 GMT</pubDate>
            <atom:updated>2021-08-27T14:20:26.092Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the sixth article of this building an own operating system article series. If you didn’t read the first five articles in this series, I recommend you to read those articles first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0PXQzid7tFCainqdtlR-fA.jpeg" /></figure><p>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><h3>User Mode</h3><p>The system is in user mode when the operating system is running a user application such as handling a text editor. The transition from user mode to kernel mode occurs when the application requests the help of the operating system or an interrupt or a system call occurs.</p><p>The mode bit is set to 1 in the user mode. It is changed from 1 to 0 when switching from user mode to kernel mode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*qD2AsYzrgRBvHGjHPIx95Q.png" /></figure><p>There’s quite a way to go until the OS created in this article series can execute programs in user mode, but this article will show how to easily execute a small program in kernel mode.</p><h3>Loading an External Program</h3><h4>GRUB Modules</h4><p>We will use a feature in GRUB called modules to load the program.</p><p>GRUB can load arbitrary files into memory from the ISO image, and these files are usually referred to as <em>modules</em>. To make GRUB load a module, edit the file iso/boot/grub/menu.lst and add the following line at the end of the file:</p><pre>module /modules/program</pre><p>Now create the folder iso/modules using this command:</p><pre>mkdir -p iso/modules</pre><p>The application program will be created later in this article.</p><p>The code that calls kmain must be updated to pass information to kmain about where it can find the modules. We also want to tell GRUB that it should align all the modules on page boundaries when loading them.</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>MAGIC_NUMBER  equ 0x1BADB002      ; define the magic number constant<br>ALIGN_MODULES   equ 0x00000001    ; tell GRUB to align modules<br><br>; calculate the checksum (all options + checksum should equal 0)<br>CHECKSUM        equ -(MAGIC_NUMBER + ALIGN_MODULES)<br><br>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>The below code shows the updated “loader.s” file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/375736e092b37d3552abda0ab08a15dc/href">https://medium.com/media/375736e092b37d3552abda0ab08a15dc/href</a></iframe><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 want to push ebx on the stack before calling kmain to make it an argument for kmain.</p><h3>Executing a 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.</p><p>This is an example of such a short program:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de48dd5ccf8071a456df5ab358492339/href">https://medium.com/media/de48dd5ccf8071a456df5ab358492339/href</a></iframe><p>After compiling this code using nasm -f bin program.s -o program we should move the program file to the folder iso/modules.</p><h4>Finding the Program in Memory</h4><p>To find the program, Assuming that the contents of ebx is passed as an argument to kmain, we can do this entirely from C. The pointer in ebx points to a <em>multiboot</em> structure. Following multiboot.h file describe the structure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8abb624de0df591126b7616646ad4403/href">https://medium.com/media/8abb624de0df591126b7616646ad4403/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>Now we should check that the module got loaded correctly by GRUB. To that, we need to check the flags field of the multiboot_info_t structure. We should also check the field mods_count to make sure it is exactly 1.</p><p>Finally, we need to jump to the code loaded by GRUB. It is easier to call the code from C, we should update the kmain.c file with the following code.</p><pre>typedef void (*call_module_t)(void);<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>The final kmain.c file will look like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bd895908ad3d355fcea7ea2ec7b0b12/href">https://medium.com/media/5bd895908ad3d355fcea7ea2ec7b0b12/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, we should see 0xDEADBEEF in the register eax via the Bochs log.</p><p>We have successfully started a program in our OS!</p><p>This is the end of this week&#39;s article. See you with the next article.</p><p>Thanks for reading!.</p><p>References,</p><p><a href="https://littleosbook.github.io/">The little book about OS development</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65d433cdd061" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Build An Operating System: Interrupts and Inputs- Part 05]]></title>
            <link>https://pwickramathunge.medium.com/how-to-build-an-operating-system-interrupts-and-inputs-part-05-3945f1ece742?source=rss-21dcb68bd36e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3945f1ece742</guid>
            <dc:creator><![CDATA[Pubudu Wickramathunge]]></dc:creator>
            <pubDate>Fri, 20 Aug 2021 17:18:50 GMT</pubDate>
            <atom:updated>2021-08-20T18:21:26.320Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the fifth article of this building an own operating system article series. If you didn’t read the first four articles in this series, I recommend you to read those articles first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*WCluTKowavdW7r6AddyAtw.png" /></figure><p>Our operating system can now produce output. So the next step is getting input. To that, the OS must be able to handle interrupts in order to read information from the keyboard.</p><p>The idea of the interrupt is at the core of the modern operating system design. By its nature, an operating system is linear and cannot handle more than one computing task at any given time. However, as modern operating systems have become more advanced, engineers and developers have included interrupt functionality to help the operating system handle many different programs by switching in and out of various tasks, with minimal inconvenience to the user. This means modern operating systems can perform many different tasks in ways that do not delay user activity. Now, while a user is viewing or using one program, the operating system can be in the background working on some other task. When the user generates an event that requires the operating system to focus on the primary program that is being used, an interrupt can facilitate a quick response.</p><p>A code module characterized as an interrupt handler uses an available queue to prioritize different programs at different times. In some cases, a piece of code called a scheduler is also used. Many different kinds of interrupts enhance the capability of an operating system to provide on-demand services to users while handling more and more additional computing tasks in the background.</p><h4>What Does Interrupt Do?</h4><p>An interrupt is a function of an operating system that provides multi-process multi-tasking. The interrupt is a signal that prompts the operating system to stop work on one process and start work on another.</p><h3>Interrupt Descriptor Table (IDT)</h3><p>The kernel needs to maintain one IDT (Interrupt Descriptor Table), which actually maps the interrupt line with the interrupt handler routine. This table has 256 entries and each entry has 8 bytes. The first 32 entries of this table are used for exceptions and the remaining are used for hardware interrupts received from the ‘outside world’. This table can contain three different types of entries; these three different types are as follows:</p><ul><li>Task handler</li><li>Interrupt handler</li><li>Trap handler</li></ul><p>The difference between an interrupt handler and a trap handler is that the interrupt handler disables interrupts, which means you cannot get an interrupt while at the same time handling an interrupt. In this article series, 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><pre>Bit:        | 31 16 |15| 14 13| 12 | 11| 10 9 8 | 7 6 5| 4 3 2 1 0 |<br>Content:|offset high|P | DPL  | 0  | D | 1  1 0 | 0 0 0| reserved  |</pre><p>The lowest 32 bits are presented in the following figure:</p><pre>Bit:     | 31              16 | 15              0 |<br>Content: | segment selector   | offset low        |</pre><p>A description for each name can be found below:</p><p>offset high — The 16 highest bits of the 32-bit address in the segment.<br>offset low — The 16 lowest bits of the 32 bits address in the segment.<br>p — If the handler is present in memory or not (1 = present, 0 = not present).<br>DPL — Descriptor Privilege Level, the privilege level the handler can be called from (0, 1, 2, 3).<br>D — Size of gate, (1 = 32 bits, 0 = 16 bits).<br>segment selector — The offset in the GDT.<br>r — Reserved.</p><p>The offset is a pointer to code (preferably an assembly code label). For example, to create an entry for a handler whose code starts at 0xDEADBEEF and that runs in privilege level 0 (therefore using the same code segment selector as the kernel) the following two bytes would be used:</p><pre>0xDEAD8E00<br>    0x0008BEEF</pre><p>If the IDT is represented as an unsigned integer idt[512] then to register the above example as 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 instead of using bytes (or unsigned integers) use packed structures 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 the interrupt that has taken place. Moreover, Interrupt Number is not pushed onto the stack. So, the interrupt that has occurred can be identified only by knowing the code that is executing. Ex:- if the handler registered for interrupt 14 is executing, then interrupt 14 has occurred.</p><p>Once the interrupt handler has done its task, it uses the <em>iret</em> instruction to return. The instruction <em>iret </em>expects the stack to be the same as at the time of the interrupt. Hence, any values pushed onto the stack by the interrupt handler should be popped from the stack. Before returning, <em>iret</em> restores <em>eflags</em> by popping the value from the stack and then finally jumps to <em>cs: eip </em>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><p>Now make a file called interrupts.h in your working directory to save the following C function declarations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eabe4ad670a31002fc5abf073d1f5931/href">https://medium.com/media/eabe4ad670a31002fc5abf073d1f5931/href</a></iframe><h3>Creating a Generic Interrupt Handler</h3><p>The generic interrupt handling layer is designed to provide a complete abstraction of interrupt handling for device drivers. It is able to handle all the different types of the interrupt controller hardware.</p><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><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35b0e2ff350f333f5154ec55a7512976/href">https://medium.com/media/35b0e2ff350f333f5154ec55a7512976/href</a></iframe><p>The common_interrupt_handler does the following:</p><ul><li>Push the registers on the stack.</li><li>Call the C function interrupt_handler.</li><li>Pop the registers from the stack.</li><li>Add 8 to esp (because of the error code and the interrupt number pushed earlier).</li><li>Execute iret to return to the interrupted code.</li></ul><p>Since the macros declare global labels the addresses of the interrupt handlers can be accessed from C or assembly code when creating the IDT.</p><h3>Loading the IDT</h3><p>The IDT is loaded with the lidt assembly code instruction which takes the address of the first element in the table. It is easiest to wrap this instruction and use it from C:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbc61268edd8b73463accd964a3b1183/href">https://medium.com/media/cbc61268edd8b73463accd964a3b1183/href</a></iframe><h3>Programmable Interrupt Controller (PIC)</h3><p>In computing, a programmable interrupt controller (PIC) is an integrated circuit that helps a microprocessor (or CPU) handle interrupt requests coming from multiple different sources (like external I/O devices) which may occur simultaneously. It helps prioritize IRQs so that the CPU switches execution to the most appropriate interrupt handler (ISR) after the PIC assesses the IRQ’s relative priorities.</p><p>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>The following table lists the hardware interrupts:</p><pre>--------------------------------------------------------------------<br>  PIC 1   |  Hardware         |    PIC 2   |  Hardware                      --------------------------------------------------------------------           <br>       0  |  Timer            |         8  |  Real Time Clock <br>       1  |  Keyboard         |         9  |  General I/O <br>       2  |  PIC 2            |        10  |  General I/O <br>       3  |  COM 2            |        11  |  General I/O <br>       4  |  COM 1            |        12  |  General I/O <br>       5  |  LPT 2            |        13  |  Coprocessor <br>       6  |  Floppy disk      |        14  |  IDE Bus <br>       7  | LPT 1             |        15  |  IDE Bus</pre><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>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 <strong><em>0x20</em></strong> to the PIC that raised the interrupt. Implementing a <strong><em>pic_acknowledge</em></strong> function can thus be done as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0cd4d6154c10a80a4b003f4072a26a6/href">https://medium.com/media/d0cd4d6154c10a80a4b003f4072a26a6/href</a></iframe><h3>Reading Input from the Keyboard</h3><p>The keyboard creates scan codes rather than ASCII characters. A scan code describes a button, both when it is pressed and when it is released. The scan code for the recently pushed button may be retrieved from the data I/O port on the keyboard, which contains the address 0x60. The following example demonstrates how this may be done:</p><p>All the things implement by following C code Keyboard. c file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a06412b2f7a3382d77412a3880406793/href">https://medium.com/media/a06412b2f7a3382d77412a3880406793/href</a></iframe><p>The next step is to write a function that translates a scan code to the corresponding ASCII character. If you want to map the scan codes to ASCII characters as is done on an American keyboard then Andries Brouwer has a great tutorial.</p><p>Remember, since the keyboard interrupt is raised by the PIC, you must call <strong><em>pic_acknowledge</em></strong> 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>Hope you understand how to works Interrupts and Input in an operating system. See you in the next article.</p><p>Thank You for Reading!</p><p>References.</p><p><a href="https://littleosbook.github.io/">The little book about OS development</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3945f1ece742" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Build An Operating System: Segmentation- Part 04]]></title>
            <link>https://pwickramathunge.medium.com/how-to-build-an-operating-system-segmentation-part-04-504c145a8283?source=rss-21dcb68bd36e------2</link>
            <guid isPermaLink="false">https://medium.com/p/504c145a8283</guid>
            <category><![CDATA[operating-systems]]></category>
            <dc:creator><![CDATA[Pubudu Wickramathunge]]></dc:creator>
            <pubDate>Fri, 13 Aug 2021 17:11:35 GMT</pubDate>
            <atom:updated>2021-08-13T17:11:35.193Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the fourth article of this building an own operating system article series. If you didn’t read the first three articles in this series, I recommend you to read those articles first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*sTqXlyFNV6v5-iuDMqai9Q.png" /></figure><h3>What is Segmentation in OS?</h3><p>Memory management is the functionality of an operating system that handles or manages primary memory and moves processes back and forth between main memory and disk during execution. Memory management keeps track of each and every memory location, regardless of either it is allocated to some process or it is free. It checks how much memory is to be allocated to processes. It decides which process will get memory at what time. It tracks whenever some memory gets freed or unallocated and correspondingly it updates the status.</p><ul><li>Like Paging, Segmentation is another non-contiguous memory allocation technique.</li><li>In segmentation, the process is not divided blindly into fixed-size pages.</li><li>Rather, the process is divided into modules for better visualization.</li></ul><h4>Characteristics</h4><ul><li>Segmentation is a variable size partitioning scheme.</li><li>In segmentation, secondary memory and main memory are divided into partitions of unequal size.</li><li>The size of partitions depends on the length of the modules.</li><li>The partitions of secondary memory are called segments.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*ysA1QP5YqM-jUzWPYY7fOA.png" /><figcaption>Translation of logical addresses to linear addresses</figcaption></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><h4>Accessing Memory</h4><p>Most of the time when accessing memory there is no need to explicitly specify the segment to use. The processor has six 16-bit segment registers: cs, ss, ds, es, gs and fs. The register cs is the code segment register and specifies the segment to use when fetching instructions. The register ss is used whenever accessing the stack (through the stack pointer esp), and ds is used for other data accesses. The OS is free to use the registers es, gs and fs however, it wants.</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, in order to use the implicit style shown above, you must store the segment selectors in their indented registers.</p><h4>Local Descriptor Table (LDT)</h4><p>A Local Descriptor Table (LDT) is a memory table used in the x86 architecture in protected mode and containing memory segment descriptors. An LDT is set up and managed by user-space processes, and all processes have their own LDT. There will be generally one LDT per user process, describing privately held memory. The operating system will switch the current LDT when scheduling a new process, using the LLDT machine instruction or when using a TSS. LDTs can be used if a more complex segmentation model is desired. So, in this article, we will use GDT.</p><h4>The Global Descriptor Table (GDT)</h4><p>The list of selectors that the processor uses is not actually kept inside the processor. Instead, it’s kept somewhere in memory (in an area carefully guarded by our kernel) and our code lets the CPU know at some point where to find it. This is in fact a required step for getting into protected mode. This list of selectors in memory is called the <strong>global descriptor table (GDT)</strong> and it must carefully follow a specific format.</p><p>A GDT/LDT is an array of 8-byte segment descriptors. The first descriptor in the GDT is always a null descriptor and can never be used to access memory. 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>The 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 four privilege levels PL0, PL1, PL2, and PL3, where PL0 is the most privileged. The kernel should be able to do anything, therefore it uses segments with DPL set to 0. This is also called kernel mode. The current privilege level (CPL) is determined by the segment selector in CS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*bt3OrY9qdCN2-_yhrjl62w.png" /><figcaption>The segment descriptors needed</figcaption></figure><p>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><h4>Loading the GDT</h4><p>The processor is loaded into the GDT with the <strong>lgdt</strong> assembly code instruction which contains the struct address which determines the beginning and the size of the GDT. (Inside the memory_segment.h file)</p><pre><strong>struct</strong> gdt {<br>        unsigned int address;<br>        unsigned short size;<br>    } __attribute__((packed))</pre><p>If the eax registry content contains the address of a structure of this kind, the GDT may be loaded with the following assembly code:</p><pre><strong>lgdt</strong> [<strong>eax</strong>]</pre><p>It might be easier if you make this instruction available from C, the same way as was done with the assembly code instructions in and out.</p><p>After the GDT has been loaded the segment registers need to be loaded with their corresponding segment selectors. The content of a segment selector is described in the figure and table below:</p><pre>Bit:     | 15                                3 | 2  | 1 0 |<br>Content: | offset (index)                      | ti | rpl |</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*v05xWr9yyRoFHqCuRx0CRg.png" /><figcaption>The layout of segment selectors</figcaption></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>After all steps, the gdt.s file will look like this,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9468d2fa19a517afb24e04343001c80/href">https://medium.com/media/b9468d2fa19a517afb24e04343001c80/href</a></iframe><p>By following this repository you can find the full code set that you need for this segmentation process.</p><p>Thanks for reading! See you next week with part 05.</p><p><a href="https://github.com/PubuduWickramathunge/WickOS.git">GitHub - PubuduWickramathunge/WickOS</a></p><p>Reference: <em>The little book about OS development/Erik Helin, Adam Renberg</em></p><p><a href="https://littleosbook.github.io/">The little book about OS development</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=504c145a8283" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Build An Operating System: Play with `Outputs`-Part 02]]></title>
            <link>https://pwickramathunge.medium.com/how-to-build-an-operating-system-play-with-outputs-part-02-ba2f9e50b743?source=rss-21dcb68bd36e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba2f9e50b743</guid>
            <category><![CDATA[operating-systems]]></category>
            <dc:creator><![CDATA[Pubudu Wickramathunge]]></dc:creator>
            <pubDate>Fri, 06 Aug 2021 17:03:50 GMT</pubDate>
            <atom:updated>2021-08-13T04:23:56.863Z</atom:updated>
            <content:encoded><![CDATA[<h3>How To Build An Operating System: Play with `Outputs`-Part 03</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*zDq0VDadTqVW6katzuS2Kg.png" /></figure><p>This is the third article of this building an own operating system article series. In this article, I will be discussing how to display text on the console and how to write data to the serial port after that I will teach you how to create the first driver for our OS.</p><h3>Interacting with the Hardware</h3><p>Memory-mapped I/O and I/O ports are the usual ways to interact with the hardware. If the hardware uses memory-mapped I/O, you can write to a specific memory address and the hardware will be updated with the new data. One example of this is the framebuffer, which will be discussed in more detail later. For example, if you write the value 0x410F to address 0x000B8000, you will see the letter A in white color on a black background</p><p>If the hardware uses I/O ports then the assembly code instructions out and in must be used to communicate with the hardware. The instruction out takes two parameters: the address of the I/O port and the data to send. The instruction in takes a single parameter, the address of the I/O port, and returns data from the hardware. One can think of I/O ports as communicating with hardware the same way as you communicate with a server using sockets. The cursor of the framebuffer is one example of hardware controlled via I/O ports on a PC.</p><h3>The Framebuffer</h3><p>The framebuffer is a hardware device that is 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.</p><p>In computing, a screen buffer is a part of computer memory used by a computer application for the representation of the content to be shown on the computer display. The screen buffer may also be called the video buffer, the regeneration buffer, or regen buffer for short. Screen buffers should be distinguished from video memory. To this end, the term off-screen buffer is also used.</p><p>The information in the buffer typically consists of color values for every pixel to be shown on the display. Color values are commonly stored in 1-bit binary, 4-bit palettized, 8-bit palettized, 16-bit high color, and 24-bit true-color formats. An additional alpha channel is sometimes used to retain information about pixel transparency. The total amount of memory required for the frame buffer depends on the resolution of the output signal and the color depth or palette size.</p><h4>Writing text to the console</h4><p>Writing text to the console via the framebuffer is done with memory-mapped I/O. The starting address of the memory-mapped I/O for the framebuffer is 0x000B8000 . The memory is divided into 16-bit cells, where the 16 bits determine both the character, the foreground color, and the background color. The highest eight bits is the ASCII value of the character, bit 7 - 4 the background, and bit 3 - 0 the foreground, as can be seen in the following figure:</p><pre>Bit:     | 15 14 13 12 11 10 9 8 | 7 6 5 4 | 3 2 1 0 |<br>Content: | ASCII                 | FG      | BG      |</pre><p>These are the available colors.</p><p>color : value</p><p>Black : 0<br>Blue : 1<br>Green : 2<br>Cyan : 3<br>Red : 4<br>Magenta : 5<br>Brown : 6<br>Light grey : 7<br>Dark grey : 8<br>Light blue : 9<br>Light green : 10<br>Light cyan : 11<br>Light red : 12<br>Light magenta : 13<br>Light brown : 14<br>White : 15</p><p>The first cell corresponds to row zero, column zero on the console. 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 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, char *fb = (char *) 0x000B8000. Then, writing A at 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><h4>Moving the Cursor</h4><p>Two different I/O ports use to move the cursor of the framebuffer. The cursor’s position is determined with a 16 bits integer: 0 means row zero, column zero; 1 means row zero, column one; 80 means row one, column zero, 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<em> </em>cdecl calling standard.</p><p>Now we should store the following function in a file called io.s.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d641f5f322d535b4692a081375e838f4/href">https://medium.com/media/d641f5f322d535b4692a081375e838f4/href</a></iframe><p>After that creating a header io.h, the out assembly code instruction can be conveniently accessed from C.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e7993737d7fb0e2a87b2bd12562e5a7/href">https://medium.com/media/9e7993737d7fb0e2a87b2bd12562e5a7/href</a></iframe><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>The write the function writes the contents of the buffer buf of length len to the screen. The write the function should automatically advance the cursor after a character has been written and scroll the screen if necessary.</p><h3>The Serial Ports</h3><p>A serial port is an interface that uses to communicate between hardware devices and although it is available on almost all motherboards. The serial port is easy to use, and, more importantly, it can be used as a logging utility in <em>Bochs</em> too. In this section, we will only use the serial ports for output, not input. The serial ports are completely controlled via I/O ports.</p><h4>Configuring the Serial Port</h4><p>First, we need to send configuration data to the serial port. 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>Here, we need to configure, how data is being sent over the line. The serial port has an <em>I/O port</em>, which is a configuration line command port. First, the data transmission speed will be configured. The serial port features an internal clock with a 115200 Hz frequency. Setting speed to a serial port implies sending divisions, such as transmission 2, at a rate of 115200/2 = 57600 Hz.</p><p>Even if the divisor is a 16-bit number, we can only send 8 bits at a time. So, we need to 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><pre>#include &quot;io.h&quot;</pre><pre>    #define SERIAL_COM1_BASE  0x3F8  /* COM1 base port */</pre><pre>    #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)</pre><pre>    #define SERIAL_LINE_ENABLE_DLAB         0x80</pre><pre>void serial_configure_baud_rate(unsigned short com, unsigned short divisor)<br>{<br>    outb(SERIAL_LINE_COMMAND_PORT(com), SERIAL_LINE_ENABLE_DLAB);<br>    outb(SERIAL_DATA_PORT(com), (divisor &gt;&gt; 8) &amp; 0x00FF);<br>    outb(SERIAL_DATA_PORT(com), 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><pre>Bit:     | 7 | 6 | 5 4 3 | 2 | 1 0 |<br>Content: | d | b | prty  | s | dl  |</pre><p>A description for each name can be found in the table below:</p><p>NameDescriptiondEnables (d = 1) or disables (d = 0) DLAB<br>bIf break control is enabled (b = 1) or disabled (b = 0)<br>prtyThe number of parity bits to use<br>s The number of stop bits to use (s = 0 equals 1, s = 1 equals 1.5 or 2)<br>dl Describes the length of the data</p><p>We will use the most 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 function as FIFO queues. The FIFO queue configuration byte is depicted in the figure below:</p><pre><strong>Bit:     | 7 6 | 5  | 4 | 3   | 2   | 1   | 0 |<br>Content: | lvl | bs | r | dma | clt | clr | e |</strong></pre><p>Following are the meanings of the names mentioned above:</p><p>lvl How many bytes should be stored in the FIFO buffers<br>bs If the buffers should be 16 or 64 bytes large<br>r Reserved for future use<br>dma How the serial port data should be accessed<br>clt Clear the transmission FIFO buffer<br>clr Clear the receiver FIFO buffer<br>e If the FIFO buffer should be enabled or not</p><p>We’ll use the value 0xC7 = 11000111, which means:</p><ul><li>FIFO is enabled,</li><li>FIFO queues for both the receiver and the transmission are cleared and,</li><li>The queue size is set to 14 bytes.</li></ul><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.</p><p>The modem configuration byte is shown in the following figure:</p><pre>Bit:     | 7 | 6 | 5  | 4  | 3   | 2   | 1   | 0   |<br>Content: | r | r | af | lb | ao2 | ao1 | rts | dtr |</pre><p>A description for each name can be found in the table below:</p><p>Name Description<br>r Reserved<br>af Autoflow control enabled<br>lb Loopback mode (used for debugging serial ports)<br>ao2 Auxiliary output 2, used for receiving interrupts<br>ao1 Auxiliary output 1<br>rts Ready To Transmit<br>dtr Data Terminal Ready</p><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><h4>Writing Data to the Serial Port</h4><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:</p><pre>global inb</pre><pre>    ; 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><pre>/* in file io.h */</pre><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><pre>#include &quot;io.h&quot;</pre><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><p>After all the final serial_port.h header file will look like the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f298434cd007c78bf931dd04cb102eed/href">https://medium.com/media/f298434cd007c78bf931dd04cb102eed/href</a></iframe><p>The output from serial port one will now be stored in the file com1.out. Now you can run your OS using the make run command.</p><p>This is all for this article. Hope you enjoyed it!</p><p>You can prefer The little book about OS development/Erik Helin, Adam Renberg and my git repository for more help.</p><ul><li><a href="https://littleosbook.github.io/">The little book about OS development</a></li><li><a href="https://github.com/PubuduWickramathunge/WickOS">GitHub - PubuduWickramathunge/WickOS</a></li></ul><p>Thank you for reading. See you in the next article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba2f9e50b743" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>