<?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 Rajat Khandelwal on Medium]]></title>
        <description><![CDATA[Stories by Rajat Khandelwal on Medium]]></description>
        <link>https://medium.com/@rajat.khandelwal.eee16?source=rss-c79f03f988e0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EKfIgHVJclMpTyOrLQoh7A.jpeg</url>
            <title>Stories by Rajat Khandelwal on Medium</title>
            <link>https://medium.com/@rajat.khandelwal.eee16?source=rss-c79f03f988e0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:36:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rajat.khandelwal.eee16/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[Dominion — A candid review]]></title>
            <link>https://medium.com/@rajat.khandelwal.eee16/dominion-a-candid-review-9dfe5209e41d?source=rss-c79f03f988e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dfe5209e41d</guid>
            <category><![CDATA[dinosaurs]]></category>
            <category><![CDATA[velociraptor]]></category>
            <category><![CDATA[jurassic-park]]></category>
            <category><![CDATA[jurassic-world]]></category>
            <category><![CDATA[jurassic-world-dominion]]></category>
            <dc:creator><![CDATA[Rajat Khandelwal]]></dc:creator>
            <pubDate>Thu, 09 Jun 2022 16:32:43 GMT</pubDate>
            <atom:updated>2022-06-09T16:32:43.433Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dominion — A candid review</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*3Qrn01kDEZsphYAQQI4gTA.jpeg" /><figcaption>Jurassic World: Dominion</figcaption></figure><p>Jurassic world: Dominion is set about 30 years after the fall of Isla Nublar due to catastrophic eruption of Mt. Sibo. During the course of Jurassic world: Fallen kingdom, we have seen that Lockwood becomes dead, following the release of all the dinosaurs captured from Nublar. The movie has also reflected a vague dominating scene with T-Rex and Lion facing each other. So, obviously, we had huge expectations from Dominion and the audience was curious to know as to what would happen in a world where dinosaurs co-live with humans?</p><p>If you have seen the trailer of Dominion, you would have seen a very lovely scene where baby Blue (Maisie names her Beta) is witnessed chasing after her mother. This scene seriously had a separate fan base. The trailer also depicts the capture of baby Blue and Owen promising her mother to bring her back.</p><p>That’s exactly what happens in the movie. The movie starts off with Owen, Claire and Maisie living off the grid somewhere in a snowy latitude. Fans would have easily understood that this was done to keep Maisie (a genetically designed replica of her mother) separate from the rest of the world. Soon after, astonishingly, Blue and her baby somehow emerges from the woods and Maisie and Owen meet her after a very long time. Seriously, Blue living in the same ecological place as Owen, how coincidental is that? Pretty soon, Blue and Maisie both are captured by Biosyn (an evil corporate involved with genetic mutation and research), let’s understand why?</p><p>So, Biosyn surprisingly has Henry as its chief research head. Biosyn plots to dominate the world with its indigenous grown crops and it achieves it by genetically mutating locusts which apparently feed only to the crops not cultivated by Biosyn and are pretty immune to death. The corporate’s plan takes a wrong turn as the whole ecological food balance starts collapsing across continents.</p><p>Henry is keen to fix “this terrible mistake”. And he can only do so by having baby Blue and Maisie studied. But why?</p><p>So apparently, Blue was designed with its DNA gaps filled with a African lizard which can reproduce without a partner. That explains how Blue had a baby.</p><p>In Fallen kingdom, Maisie was told a truth that Lockwood recreated her daughter, Charlotte after her death via genetic mutation which eventually was Maisie herself. But the story is entirely different. Charlotte was a chief scientist in Isla Sorna and had some defects in her DNA which caused her early death. But she wanted a baby more than anything, so she devised a technique which allowed to “repair/change” the DNA to something she wanted and voila, she created Masie in her own body but only with a repaired DNA.</p><p>Henry supposedly thinks that this technique could be used to treat the genetically modified locusts and so he wanted Maisie and Blue both.</p><p>Ok, where do Sattler, Ian and Grant come into picture? So, Sattler gets an invitation to interrogate the locusts which she traces back to Biosyn but required a concrete evidence, thus converged with Grant to collect a DNA sample of the genetically modified locusts from Biosyn itself. She receives an invitation from Ian who also works at Biosyn (kind of like an advisor). Ian lends her the security card to infiltrate Biosyn lab and they successfully collect the DNA sample.</p><p>Meanwhile, Maisie and Blue escape. Claire and Owen, desperate to find both finally trace their location to Biosyn and they all happen to meet in an underground mine under Biosyn.</p><p>They somehow escape (this involves help from a new friend Owen and Claire make along the way). Henry gets Maisie’s approval to examine her and he cures the locusts, eradicating the ecological disaster forthcoming.</p><p>That’s it!</p><p>The movie has great chase scenes. Owen and Claire on their way to find Maisie and baby Blue encounter some genetically modified hybrids. I remember atrociraptors who respond to a laser on a target (just like the indoraptor). They get chased by these animals.</p><p>What happened to Isla Sorna? This remains still a mystery after Dominion. The creators tried to recreate some scenes from Jurassic Park I. I recall one where Ian distracts Gigonotosaurus (this is supposed to be the largest carnivore which Biosyn creates and Dominion creators didn’t spend much time naming it) by lighting fire (same as he did in Park I by distracting T-Rex). Another one where dilophosaurus attacks Dennis in Park I has the same replication where Claire gets confined by a dilophosaurus in Dominion.</p><p>I personally wanted Spinosaurus to come back in the movie. It was a creatively designed animal in Park III which attacks T-Rex and wins the fight. Further, Gigonotosaurus doesn’t have much screen time. It’s as if the creators just wanted an animal which is new and apex but didn’t spend much time making it hostile. <br>Again, all the fans were curious to know about Blue and her baby and what would they contribute in the movie. Short answer, nothing! Baby Blue gets kidnapped and rescued, that’s it!</p><p>There is one question which is tickling my brains. What happened in those 30 years after Lockwood’s death. The original government order was to let the dinosaurs die on Isla Nublar but we have seen that some are brought back to Lockwood estate. Didn’t the government do something when these animals were out in the open?</p><p>Honestly, if you are a true Jurassic fan, you will like the trailer better than the movie itself. <strong>The movie, put together, honestly, is a slapdash of multiple irrelevant events happening around the globe.</strong></p><p>They even scripted Maisie into calming the baby Blue by verbally saying “Eyes on me”! When Owen said it, it gave me chills. Contradictory, when Maisie did, she looked a pretty stupid character to me. Bad script writing!</p><p>You cannot beat the level Park I set for us. This can easily be deduced after watching Dominion. However, the movie has great action scenes and sudden shock moments which makes it a must watch for everyone. For Jurassic fans, prepare to be a little disappointed, sadly!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dfe5209e41d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wielding terror inside]]></title>
            <link>https://medium.com/@rajat.khandelwal.eee16/wielding-terror-inside-96b6b6606a59?source=rss-c79f03f988e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/96b6b6606a59</guid>
            <category><![CDATA[alone]]></category>
            <category><![CDATA[anxiety-attacks]]></category>
            <category><![CDATA[panic-attack]]></category>
            <category><![CDATA[anxiety]]></category>
            <category><![CDATA[depression]]></category>
            <dc:creator><![CDATA[Rajat Khandelwal]]></dc:creator>
            <pubDate>Sun, 09 Jan 2022 10:34:15 GMT</pubDate>
            <atom:updated>2022-01-09T10:34:15.363Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WXHAN6Vg2p1vJX2knlrZ8A.jpeg" /></figure><p>Are we designed to suppress the horror inside?<br>Our minds trembling, hearts racing<br>Why don’t we just sit back and confide<br>The panic, deep beneath we are facing</p><p>Those ten minutes of quivering body<br>Seemed like an eternal lifetime<br>Why does it look like an absurd hobby<br>When I try to pretend to be fine</p><p>The profound pain felt in the chest<br>The body began perspiring like hell<br>Why was I choking on my own breath?<br>Thousands of feelings got suppressed by wrath</p><p>The pain slowly entered the mind<br>Brain started ticking swiftly beating the clock<br>What was I desperately trying to find?<br>The heart seemed like a burden beneath a rock</p><p>Trying to stand,<br>though I was shaken with tremor<br>Screaming, someone please give me a hand<br>Yet voice was as feeble as a feather</p><p>What does it feel like to be weak?<br>Hiding countless emotions, I feared were all<br>Everything around me seemed to be bleak<br>Pain kept surging like a high fall</p><p>It’s been years since the first one<br>Each time I encounter, numbness invades<br>Could have I shot myself with a gun?<br>As silence, is all I have left to crave</p><p>Why didn’t I tell someone, you ask?<br>I was afraid of being let go and looked beneath<br>This pain, is all but mine<br>Couldn’t afford to lose all as I gasp to breathe</p><p>You told me it was strong and not weak<br>But here I was, <br>Once again betrayed and forced not to speak<br>For the retarded one among you all!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96b6b6606a59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compiling your own kernel on your linux machine]]></title>
            <link>https://medium.com/@rajat.khandelwal.eee16/compiling-your-own-kernel-on-your-linux-machine-dc2ed503aba0?source=rss-c79f03f988e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc2ed503aba0</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[linux-tutorial]]></category>
            <category><![CDATA[debug]]></category>
            <category><![CDATA[kernel]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Rajat Khandelwal]]></dc:creator>
            <pubDate>Tue, 21 Sep 2021 17:35:29 GMT</pubDate>
            <atom:updated>2021-09-21T17:58:12.138Z</atom:updated>
            <content:encoded><![CDATA[<p>In our linux machine, sometimes we need to debug and see what’s going on inside kernel if we are debugging a user space activity. This is usually achieved by adding debug prints in the kernel to deeply inspect the debug.</p><p>Steps to build your own linux kernel on your machine:</p><p>Download the kernel version you want by visiting <a href="https://www.kernel.org/">https://www.kernel.org/</a>. The downloaded file contains a compressed kernel code.</p><p>Extract the tar file : tar -xvf linux-5.13.9.tar.xz</p><p>Install pre required packages : sudo apt-get install git fakeroot build-essential ncurses-dev xz-utils libssl-dev bc flex libelf-dev bison</p><p>The linux kernel comes with the default configuration. You can change the configuration in the following steps.</p><p>Navigate to linux-5.13.9 → cd linux-5.13.9</p><p>Copy existing configuration file: cp -v /boot/config-$(uname -r) .config</p><p>To make changes to configuration file run this → make menuconfig<br>The config window looks somewhat like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*aDdDqoxJa8cLWX79sajVBw.jpeg" /><figcaption>Kernel configuration</figcaption></figure><p>Make changes in the code, compile and build the kernel → make -j3 bindeb-pkg</p><p>Look for these statements at the end of operation:</p><p>dpkg-deb: building package ‘linux-headers-5.13.9’ in ‘../linux-headers-5.13.9_5.13.9–13_amd64.deb’.</p><p>dpkg-deb: building package ‘linux-image-5.13.9’ in ‘../linux-image-5.13.9_5.13.9–13_amd64.deb’.</p><p>Install the generated debs using dpkg :</p><p>sudo dpkg -i ../linux-image-5.13.9_5.13.9–13_amd64.deb</p><p>sudo dpkg -i ../linux-headers-5.13.9_5.13.9–13_amd64.deb</p><p>That’s it. Reboot the system!</p><p>There’s a twist. On first reboot, it won’t start the desired linux kernel automatically. You have to go into recovery screen and manually click on the version you just built. What to do to avoid such hassle?</p><p>Note down the row number in which the kernel version you built is present. Go to /etc/default/grub and edit it GRUB_DEFAULT=”1&gt;0&quot; → here 0 is the row number on which 5.13.9 is present in the recovery screen.</p><p>After editing update the grub configuration → sudo update-grub</p><p>Now whenever you reboot, it will automatically start the 0th kernel version in the recovery screen.</p><p>Happy debugging…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc2ed503aba0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A word to my sister on Rakhi]]></title>
            <link>https://medium.com/@rajat.khandelwal.eee16/a-word-to-my-sister-on-rakhi-35340f6512cb?source=rss-c79f03f988e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/35340f6512cb</guid>
            <category><![CDATA[sister-love]]></category>
            <category><![CDATA[brothers-and-sisters]]></category>
            <category><![CDATA[rakhi]]></category>
            <category><![CDATA[rakshabandhan]]></category>
            <dc:creator><![CDATA[Rajat Khandelwal]]></dc:creator>
            <pubDate>Mon, 23 Aug 2021 18:07:50 GMT</pubDate>
            <atom:updated>2021-08-23T18:12:43.784Z</atom:updated>
            <content:encoded><![CDATA[<p>My mind gave an intense look</p><p>For my heart was winning a race</p><p>My eyes rolled up to a face so beautiful</p><p>When you tied the knot of love and faith</p><p>The gentle touch of your palm on my cheek</p><p>Feels like anything but an oasis of serenity</p><p>For the love I seem to always seek</p><p>Always true and sings a melody</p><p>Heart is halfwit yet a mysterious mess</p><p>Cries when beats without a concurring match</p><p>Laughs when you smile like an alluring catch</p><p>But stops when your face frowns in the mist of sorrow and sadness</p><p>If beauty and brains were ever to be personified</p><p>It would seamlessly take your name</p><p>Your presence is enough to keep me occupied</p><p>Your smile is enough to keep me sane</p><p>I pray to God every day</p><p>For the goals you wish to achieve in life</p><p>My love for you is eternal and never decays</p><p>Your presence fills the darkness with light</p><p>No, I can’t express by mere words</p><p>How special you are to me</p><p>Nothing lets me down in this world</p><p>When you hold my hand and laugh with me</p><p>My lovely sister, whenever you smile</p><p>My heart finds a profound peace</p><p>Whenever you laugh</p><p>Light finds a way down the streets</p><p>Every time my pulse quickens</p><p>Whenever you look my way</p><p>Its the way you hold me in your arms</p><p>And make all problems go away</p><p>To all the dreams we shared together</p><p>To all the troubles we faced together</p><p>The weight on your shoulders i always promise to carry</p><p>For we are like tom and Jerry</p><p>Your smile is the one thing I could hold on to</p><p>Your voice is the one thing I could listen all night</p><p>My love for you is bewitching and true</p><p>Your presence makes my day joyful and bright</p><p>A hug is all I need from you</p><p>A hug is one among many things I’d give to you</p><p>You are the one and only precious thing to me</p><p>I could enchant your name each time I breathe</p><p>I will always protect you, my adorable sis</p><p>For in return, I desire nothing but a gentle kiss</p><p>This is all your brother wants to say</p><p>On this raksha Bandhan day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35340f6512cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scheduling and concurrency]]></title>
            <link>https://medium.com/@rajat.khandelwal.eee16/scheduling-and-concurrency-e5eb43a4f6c8?source=rss-c79f03f988e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5eb43a4f6c8</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[kernel]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[scheduling]]></category>
            <dc:creator><![CDATA[Rajat Khandelwal]]></dc:creator>
            <pubDate>Sat, 11 Jul 2020 09:07:56 GMT</pubDate>
            <atom:updated>2020-07-11T09:07:56.159Z</atom:updated>
            <content:encoded><![CDATA[<p>What processes currently seem to run simultaneous to you as you read this article? You probably are using a chromium browser to read this article, at the same time you may be listening to music on another program or playing some game, or writing a 1000 words essay for your prof in a text editor, and there are literally many background processes currently executing concurrently which you are not even aware of.</p><p>Of course, with the advent of multiprocessor systems, true parallelism can be exploited where processes actually run simultaneously. But there are more processes that execute than the number of cpu cores embedded in your system (yes, a practical setback).</p><p>How does OS schedule the processes? What algorithms are employed? Is the scheduling always efficient? If not, what are the trade offs? How can true concurrency be exploited? Can it ever be?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*UCygJ92SZMP-TY5Ts5HfPg.png" /></figure><p>Generally, the scheduling algorithms are divided into two categories. <strong>Preemptive </strong>and <strong>Cooperative</strong>. In preemptive scheduling, the OS decides when and what to run and thus it may schedule any process involuntarily. However, in cooperative scheduling, it is the decision of the process to give up the processor to execute some other process. In doing so, it will be placed at the end of the queue to restart its execution again.</p><p>I guess you may have figured out that time sharing systems like the one you are using right now have to be employed with preemptive algorithms where the OS is responsible for scheduling the processes which benefits the whole system efficiently. Leaving this task to the process will not benefit the system in any terms. Processes can monopolise the whole system which brings down the concurrency you expect. Moreover, a blocked process can bring down the entire system as the OS is not in control of the scheduling.</p><p>Thankfully, today the algorithms employed are all preemptive in nature which is handled by the OS itself. You may be shocked to know that Windows 3.1 and earlier had cooperative multitasking. Same was the case for Mac OS 9.</p><p>Let’s look at some of the scheduling algorithms.</p><h4>First come, first serve (FCFS)</h4><p>This is the most simplest scheduling algorithm that existed and quite useless actually. The idea is to execute the processes one by one as they enter the queue. The OS won’t perform any algorithm to preempt a process involuntarily. It is up to the process that it may halt and give the processor to some other process, until then it runs continuously. Generally, the process terminates by executing completely and then the control transfers to the next waiting process in queue.</p><p>The user won’t be able to see processes running concurrently. An I/O bound process may be forced to wait unless and until it is allowed to wake up by another process. Think about typing something through your keyboard and observing the display to occur very slowly!</p><h4>Shortest Job First</h4><p>Again, a cooperative algorithm. Whenever a process gives up the processor, the next process to execute will be the one having the shortest burst time.</p><p>Obviously, the average wait time will be low as compared to FCFS. But again, true concurrency cannot be established as there will be a considerable amount of delay in executing another process (due to the voluntarily action of preempting by a process).</p><p>There are other primitive algorithms as well like shortest remaining time first, longest job first, longest remaining time first, etc. But none of them promises true concurrency. The only significant difference between them can be seen in terms of average wait time.</p><p>So are cooperative algorithms of no use? In small systems where complex decisions are not required, cooperative algorithms can be employed. Of course, they are much easier to implement. The processes are scheduled to run one after the another but not to exploit concurrency rather to device a strategy which impacts other performance parameters like average waiting time, latency, throughput, etc.</p><p>In our daily use computer systems (laptops, PCs), time sharing is critical, which calls for true concurrency. The only way to do so is if we employ preemptive scheduling where the job of preempting a process will be done by the OS to achieve concurrency.</p><h4>Round robin scheduling</h4><p>The OS gives a specific time interval to each process to run until preempted. This time interval is called a <strong>time slice. </strong>So, whenever a process executes for a period equal to the time slice, it is stopped by the OS for the time being and context switched to another process. This goes on and on until the first process receives its time slice again.</p><p>The time slice is such that any process will seem to run continuously to the user. Although, the OS preempts it and then executes it again after all the other processes have shared their time slices, the interval is so low that the user is bound to think that the processes execute simultaneously.</p><p>Is that it? Have we established true concurrency and efficiency? Well, not yet.</p><p>The user interacts majorly via I/O bound processes. The terminal, a text editor, a word processor are all I/O bound processes. So, if a user presses a key, the process responsible for the character buffer should execute instantly to provide better responsiveness which is not the case if the above algorithm is employed.</p><p>Also, these I/O bound processes spend most of their time waiting for another input. Although the time spent in pressing two keys one after the other seems not much to the user, but it is to the processor. And hence, the I/O bound process waits for most of their time for another input.</p><p>It would be better if we somehow utilise the time spent in waiting and give it to another process that is ready. This considerably reduces latency of the system.</p><p>Both these challenges are not dealt by the above algorithm.</p><h4>Trade offs and desired characteristics</h4><p>The time slice given should not be too low as frequent switching of the processes employ additional overhead which increases latency of the system. On context switching, all the vital segments of the process are stored back in its control block or the task state segment (in x86 systems). They include general purpose registers, program counter, stack pointer, open files, user buffers, page table and TLB, etc. Moreover, switching from user space to kernel space incurs another overhead.</p><p>It should also be not too much or else the system’s throughput will decrease and concurrency will not be efficiently established.</p><p>Another trade off occurs between I/O bound and CPU bound processes. An I/O bound process waits for maximum of its time before it could be resumed. But it desires instant switching to give better responsiveness to the user. So, I/O processes craves frequent switching with less time spent in processor engagement. On the other hand, CPU bound processes spend most their time in running as they are not I/O driven. So they crave longer running time with less frequent switching. A matlab process which houses many complex calculations is an example. It almost spends its time completely on the processor.</p><p>CPU bound processes have to keep their caches hot so that they utilise their caches efficiently for longer duration to minimise latency. And thus they prefer longer running times.</p><h4>Priority based scheduling (employed by many OS)</h4><p>Generally the scheduling is done in favour to the I/O bound processes to give better responsiveness to the user. To implement this, the processes are given priority. A high priority process is bound to interrupt a low priority process, if running currently.</p><p>Linux implements this with the help of <strong>nice</strong> levels. The nice levels range from -20 to 19, giving a total of 40 priority levels. A process with a higher nice value has a low priority since it’s “nice” to others. Similarly, a process with a lower nice value has a high priority as it’s less “nice” to others.</p><p><em>You can even check the nice values of the processes currently in execution under the NI tab by executing the following command.</em></p><pre>ps -el</pre><p>Each priority level should be equipped with an absolute time slice or else a process can run continuously, thus not allowing low priority processes, even if they are ready, to get a share and run concurrently. When the time slice expires, context switch occurs to the next available process and the preempted process gets scheduled to run after the time slices of all processes are expired.</p><p>The idea is to give high priority processes a bigger time slice than the low priority processes to provide with better responsiveness for a longer period of time before context switch occurs.</p><p>Suppose, a process is currently in execution. A high priority process becomes available and thus the process gets preempted by the OS instantly. When the high priority process gets blocked again in the future, the OS can schedule the preempted process again depending upon its priority among other available processes.</p><p>So far no problems.</p><p>To implement concurrency, we put the process whose time slice has been expired to run after all the processes have expired their time slices. This, however, reduces responsiveness because the high priority processes won’t run for a considerable amount of time after their time slices have been expired.</p><p>So, generally, to favour high priority processes, they are allowed to be executed again even after their time slices expire. This however may cause starvation to the low priority process as the high priority processes may end up using almost all of the time of the processor.</p><p>Did you notice the trade off? To make the responsiveness better, concurrency may need to be compromised which reduces the overall throughput. Else, responsiveness degrades for the system to follow efficient concurrency.</p><h4>CFS to the rescue (Completely Fair Scheduler)</h4><p>CFS is a very popular algorithm which came into existence from the Linux kernel.</p><p>Much detail cannot be provided here since it requires deep knowledge about the internal kernel data structures.</p><p>The idea of the CFS is simple. Schedule the processes in such a way that each process gets a fair share of the processor without having to starve any.</p><p>To implement the above idea, the concept of priority is completely eradicated. Because, if the higher priority processes were to interrupt lower priority processes, the system may go to starvation.</p><p>CFS thus doesn’t allow the process get interrupted by another process. Rather, a process runs for the whole time slice given to it before being preempted.</p><p>The preemption can occur in two cases.</p><ol><li>When the time slice of a process expires, the scheduler may context switch.</li><li>When a process is blocked by the I/O, it may signal the scheduler to run another process instead.</li></ol><p>In both these cases, the next process to run is determined by the lowest run time among all the available processes at the moment. This ensures that a process with low run time will always execute once ready when a context switch occurs, thus preventing any process to starve. This ensures that all the processes receive a fair amount of time on the processor.</p><p>However, this doesn’t ensure that an I/O bound process is executed immediately when the buffer becomes available. But since such processes get a large time slice as compared to the CPU bound processes and it’s highly probable that they haven’t been run for a long time ensuring that the next context switch will favour these processes due to their lowest run times.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5eb43a4f6c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Threading]]></title>
            <link>https://medium.com/@rajat.khandelwal.eee16/threading-2a4327eab376?source=rss-c79f03f988e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a4327eab376</guid>
            <category><![CDATA[computer-architecture]]></category>
            <category><![CDATA[kernel]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[Rajat Khandelwal]]></dc:creator>
            <pubDate>Mon, 29 Jun 2020 19:19:00 GMT</pubDate>
            <atom:updated>2020-06-29T19:19:00.082Z</atom:updated>
            <content:encoded><![CDATA[<p>The modern computer systems can not be imagined with multiple cores in their processing units. Take an example of your mobile processors. You may be having an octa core processor embedded in your mobile phone (check it out).</p><p>Threading, simply defined is the execution of multiple units within a process which share the same address space (file descriptors, page table, user buffers, etc). Think of it as a single process with the advent of concurrency established by the kernel within the process.</p><p>What do threads of the process differ in? As each unit is executed separately and scheduled by the kernel, they must have their own code segment, memory stack and registers. However, a thread can access the memory of another thread of the same process.</p><p>That being said, what does threading establishes?</p><p><strong>Misconception : </strong>Threading increases the system’s performance.</p><p>When we tend to think it in an abstract way, it should, right? The answer is NO. Threads increase the system’s performance only when the number of threads in your process doesn’t exceed the number of processing cores.</p><p>But why?</p><p>Suppose you have a single processor system. The process is split up into different execution units and scheduled by the kernel to run. There always exists an overhead when the kernel switches context. If you look at the total time elapsed, it will be more than when the process was executed as whole.</p><p>The kernel has to save the existing thread’s registers, program counter, stack pointer then load the data of another thread which takes time. Moreover, switching from user to kernel space incurs another overhead.</p><p>Is there any benefit to perform threading on uni processor systems?</p><p>Yes indeed there is. Suppose a process is waiting for a user input. It may block for substantial amount of time until the input was made available. This may have some serious impact on the system’s performance. Also, the process may seem to have been blocked and unresponsive.</p><p>If threading was implemented, the process would continue with specific threads waiting for the input. This way process won’t be unresponsive and performance won’t degrade.</p><p>Can we perform better than this?</p><p>As stated earlier, threading should be avoided whenever possible if number of threads are less than number of cores. But the above example seriously requires threading like mechanism.</p><p>There exists 2 other ways to handle the above situation. Those are :</p><p><strong>Non-blocking I/O : </strong>If a request requires data which is yet not available it won’t halt the process, rather return immediately with an error. The user can issue the request again after a while. User has to make a system call to check if the data is available.</p><p><strong>Multiplexed I/O : </strong>The requests to be issued in the process is put in file descriptor sets. The sets automatically contain the files available for I/O whenever they become available which the user can check directly without issuing further I/O system calls.</p><p>Both of these doesn’t require process to be broken down, thus eradicating the overhead incurred in thread switching. The above two mechanism can’t be explained here as they require a much deeper understanding of kernel internals.</p><p>So far so good! Any problems that can occur in threading? Think about it before moving onto the next section.</p><p>As I have previously mentioned, threads may share the address space of one another belonging to the same process. But what if the kernel fails to synchronise the threads which use common address spaces effectively? That could leak to disastrous results, even resulting in program crash.</p><p>Let’s take an example to understand this completely.</p><pre>x++;</pre><p>The above code snippet is shared by two threads of a process which read a variable, increments it and stores it. Suppose the initial value of x is 10.</p><p>Let’s say, thread 1 has read the variable with initial value 10 and performed the increment operation. At that time, thread 2 reads the variable but since it hasn’t been written to the memory yet with updated value, it will be read with a value of 10 again. Now, both the threads will perform operations on 10 and write 11 to the memory location of x.</p><p>But shouldn’t the result be 12? There are two threads, so typically speaking, both threads updating the memory location by incrementing it should result in two increment operations which is not the case here.</p><p>This is a very simple example of a memory sharing case which could go wrong horribly.</p><p>Did you witness the chronology of the events? Threads were created to exploit concurrency and parallelism. Okay we did that. But then they again created a different problem which could potentially crash the program.</p><p><strong>Mutexes (Locks) to the rescue</strong></p><p>POSIX introduced a locking mechanism which effectively gets rid of the above described problem. Whenever a thread wishes to access a shared memory resource, it locks the part of the program and thus another thread wanting to do the same could not access it. When the first thread finishes it may unlock it for the next thread to continue its access.</p><p>Take a look at the code below:</p><pre>pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER<br>int ret = pthread_mutex_lock(&amp;mutex);<br>x++;<br>ret = pthread_mutex_unlock(&amp;mutex);</pre><p>The threads which are required to access “x++” will not be doing simultaneously. If a thread locks that part, another thread won’t be able to access it unless the previous thread unlocks it. Thereby, the thread will be blocked until the address space is not unlocked by the previous thread.</p><p>One can safely say that the above shared memory space will be accessed by threads one after the other. The program works fine.</p><p>Okay, now we have safely removed the problem we were going through. But it didn’t end here. There still exists another problem. Quite a hassle, right?</p><p><strong>Deadlocks</strong></p><p>Deadlocks exist when the process/thread is blocked infinitely, mainly due to dependency issues.</p><p>If I modify the above code snippet in the following manner:</p><pre>pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER<br>int ret = pthread_mutex_lock(&amp;mutex);<br>x++;<br>ret = pthread_mutex_lock(&amp;mutex);<br>ret = pthread_mutex_unlock(&amp;mutex);</pre><p>What if I lock the shared memory space when it was already locked?</p><p>The lock statement inside the shared memory space causes the thread to block infinitely because the statement waits for the mutex to be unlocked so that it could be locked again. But the mutex is currently being held by the same thread which is waiting for itself to release it. This infinitely blocks the thread and the other threads too which may be waiting for the mutex to be unlocked. This results in a deadlock state.</p><p>Another example would be when two or more threads are waiting for some thread to unlock a mutex so that they could access it. But if the thread fails to unlock the mutex, it creates a state of infinite blocking of the threads waiting for the mutex to be unlocked.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a4327eab376" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Users and Groups in a Linux Process]]></title>
            <link>https://medium.com/@rajat.khandelwal.eee16/users-and-groups-in-a-linux-process-bcca08b26468?source=rss-c79f03f988e0------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcca08b26468</guid>
            <category><![CDATA[process]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[user-id]]></category>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[system-call]]></category>
            <dc:creator><![CDATA[Rajat Khandelwal]]></dc:creator>
            <pubDate>Fri, 19 Jun 2020 15:25:16 GMT</pubDate>
            <atom:updated>2020-06-19T15:25:16.330Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello folks! This article aims towards developing an understanding as to how the Linux kernel manipulates processes in terms of security (which is yet another fundamental concept of Linux).</p><p>Ok, let’s begin!</p><h3><strong>sudo command in a shell</strong></h3><p>We’ll start by looking at a very general feature of Linux- the sudo command. So what does sudo do? Briefly, sudo gives administrative rights to a system user to access something which requires privileged permissions.</p><p>Let’s understand it by working out an exercise. Make a file with “Hello world” written into it by using the shell.</p><pre>echo Hello world &gt;&gt; ~/Desktop/newfile.txt</pre><p>Now change the owner of the file to the root along with the permissions by executing the following command :</p><pre>sudo chown root newfile.txt &amp;&amp; sudo chmod 0600 newfile.txt</pre><p>Since, you as a normal user don’t have any access (as the last two octal digits of the chmod arguments are zero), you won’t be able to access it. If you wish to try :</p><pre>gedit newfile.txt</pre><p>This command throws an error. But however if you behave as an administrator by using sudo, you will be able to access it with the permissions given to the root (read and write in our case).</p><pre>sudo gedit newfile.txt</pre><p>Normally, when you add a new user to your system, the sudo command won’t work. It’s because Linux allows the root to give administrator privileges to any user the root desires. When you add a new user, the root didn’t give you administrator privileges yet. This data is located in a configuration file /etc/sudoers. You can edit it using the visudo command. But the configuration file requires root privileges so you have to login into a user which already has access to root privileges and configure the sudoers file by writing the following text into the file :</p><pre>&lt;username&gt; ALL=(ALL:ALL) ALL</pre><h3><strong>User and group ids</strong></h3><p>Briefly speaking, after the bootloader stage 2 loads the kernel into the system, the first process started by the kernel is the init process, typically located in the /sbin/init path.</p><p>This init process configures the essentials and then loads the /sbin/getty process which prompts for a username. After having received a suitable user, the getty gives a userid to the /bin/login process which waits for the user to login into the system.</p><p>The kernel strictly talks in terms of user ids and not usernames. Usernames are just abstractions linux provides us. The mapping of the usernames and userids is present in the configuration file /etc/passwd. Similarly each user belong to a group. The respective mapping of group names and group ids is present in the /etc/group file.</p><p>As stated previously, the login process is given a specific uid to begin with. This login loads the initial processes into the system, which then loads some more and so on…. Basically, each process you are working with now is a direct/indirect child of the login process with uid equal to the user id which is currently logged in. This uid is termed as the real uid.</p><h3>The setuid binary file</h3><p>Suppose you come across a file which when listed using the ls command gives output in this manner :</p><pre>ls -ln file.out<br>-rwsr-xr-x 1 0 0 16840 Jun 19 20:02 file.out</pre><p>The ‘s’ here denotes that the file is a setuid file. That is, when a process invokes this file using exec() family of system calls, this file executes with its effective uid equal to the user id of it’s owner.</p><h3><strong>Real, effective and saved uids(user ids) and gids(groups ids)</strong></h3><p>While a process is currently running, it has three different types of uids and gids — real, effective and saved. We will look at each one of them.</p><p><strong>Real uid</strong><em> </em><strong>(ruid):</strong> As stated previously, real uid is the user id of the user currently logged in. The root can change the ruid in real time but no normal user can do so. While executing fork(), the real uid is copied into the new process. Same thing happens while executing an exec() family call.</p><p><strong>Effective uid (euid):</strong> Normally, the ruid and euid of any process is the same. But the difference can be seen while executing an exec() family call. If the parent process executes a setuid binary process, the euid of the setuid process will be the user id of the user it belongs to. For instance, /usr/bin/passwd is a program used to change the password of the user and root is it’s owner. So, whenever you exec onto this process, the euid will be that of the root (zero).</p><p>If the process you are about to execute with exec() call is not of the setuid binary instance, the euid will be the same as that of the calling process.</p><p>These types of elevated files should be written carefully. For instance, the passwd program checks the user who invoked the process and only allows the password modification for that particular user (root can access any user’s password). Since the passwd file executes as a root, it has to be written carefully as it is potentially capable of causing modifications into other users as well.</p><p>The euid is what the kernel checks for any permission. Normal users can modify the euid to the ruid and the suid. The root can modify it to anything. Moreover, the euid is copied directly when fork occurs.</p><p><strong>Saved uid (suid): </strong>When a process forks, the suid is copied to the new process. But when an exec family system call occurs, the kernel sets the suid to the euid of the newly created process. Normal users cannot modify the suid. Only root has the right to do so.</p><p>All these ids have similar meanings with respect to linux groups.</p><h3>The setuid and seteuid system calls</h3><p>Let’s begin by an exercise. I am creating a C file onto my desktop named “program.c” which is comprised of the following code :</p><pre>#define _GNU_SOURCE</pre><pre>#include&lt;stdio.h&gt;<br>#include&lt;unistd.h&gt;<br>#include&lt;sys/types.h&gt;<br>#include&lt;stdint.h&gt;<br>int main()<br>{<br>  uid_t ruid,euid,suid;<br>  int ret = getresuid(&amp;ruid,&amp;euid,&amp;suid);<br>  printf(&quot;%jd %jd %jd\n&quot;,(intmax_t)ruid,(intmax_t)euid,   (intmax_t)suid);<br> <br>  ret = setuid(1000);<br>  ret = getresuid(&amp;ruid,&amp;euid,&amp;suid);<br>  printf(&quot;%jd %jd %jd\n&quot;,(intmax_t)ruid,(intmax_t)euid,  (intmax_t)suid);<br>}</pre><p>Compile it using the following command :</p><pre>gcc -o program.out program.c</pre><p>Now change the owner of the binary to root and change the permissions.</p><pre>sudo chown root program.out &amp;&amp; sudo chmod 4755 program.out</pre><p>This changes the binary file owner to root and sets the permissions (read, write and execute for root and read/execute permission to any other user in any group). The first octal digit 4 stands for setuid. By allowing this, the binary process will have euid equal to the owner of the file (root in this case), when executed.</p><p>There are 3 types of special permissions : setuid (octal value 4) , setgid (octal value 2) and sticky bit(octal value 1).</p><p>Now, execute the binary as a regular user.</p><pre>./program.out</pre><p>The following output will be generated :</p><pre>1000 0 0<br>1000 1000 1000</pre><p>When the binary is invoked and since it has its setuid bit set, it’s euid will be equal to the root(0). Also, the kernel changes the suid to the euid and so suid will also be 0.</p><p>The setuid function when executed by a user sets the euid to the argument provided in the function (it can only be equal to the ruid or the suid). But a root sets all the 3 uids to the argument, which is exactly what happened in our case. The uid 1000 is my uid on the system which may be different in your case.</p><p>A setuid has the following structure :</p><pre>#include&lt;sys/types.h&gt;<br>#include&lt;unistd.h&gt;<br>int setuid(uid_t uid);</pre><p>This is defined by POSIX for the Linux environment.</p><p>But do you realize what happened when you executed the setuid function?</p><p>All the 3 uids changed to the specified value. That is, if you are executing something with an upper privilege, and lowered it by executing the setuid function, you won’t be able to retain the upper privilege (as both the ruid and the suid are set to the user id). If any one of them had a value equal to that of the upper privilege (for root, 0) executing the setuid function as a normal user could escalate the privilege because the user can only specify the uid argument in the function with value equal to ruid or suid. So, in our case, there is no means to escalate the privilege and this change will be permanent until you execute another process by calling exec family of system calls which is a setuid binary with escalated privileges.</p><p>Therefore, POSIX defined another function, the seteuid function which is defined as follows:</p><pre>#include&lt;sys/types.h&gt;<br>#include&lt;unistd.h&gt;<br>int seteuid(uid_t uid);</pre><p>The behaviour of the seteuid function is the same as that of setuid when the process has euid same as that of a normal user but when it is executed as a root/escalated privilege, the root won’t be able to set all the uids equal to the specified argument. It will only set the euid.</p><p>By executing the following C program :</p><pre>#define _GNU_SOURCE</pre><pre>#include&lt;stdio.h&gt;<br>#include&lt;unistd.h&gt;<br>#include&lt;sys/types.h&gt;<br>#include&lt;stdint.h&gt;<br>int main()<br>{<br>  uid_t ruid,euid,suid;<br>  int ret = getresuid(&amp;ruid,&amp;euid,&amp;suid);<br>  printf(&quot;%jd %jd %jd\n&quot;,(intmax_t)ruid,(intmax_t)euid,   (intmax_t)suid);<br> <br>  ret = seteuid(1000);<br>  ret = getresuid(&amp;ruid,&amp;euid,&amp;suid);<br>  printf(&quot;%jd %jd %jd\n&quot;,(intmax_t)ruid,(intmax_t)euid,  (intmax_t)suid);<br>}</pre><p>You get the results as follows :</p><pre>1000 0 0<br>1000 1000 0</pre><p>As you can see the root only modified the euid of the process. Now as a user, you can escalate the privilege of the process at any time because you now have root privilege (0) defined in the suid of the process. So, lowering the privilege won’t be permanent in this case.</p><p>Note : similar case happens with the group ids.</p><h3>The getresuid, getuid and geteuid system calls</h3><p>getresuid saves the ruid, euid, and suid into the pointer arguments provided in the function. getuid only saves the real uid into the return variable. geteuid only saves the effective uid into the return variable.</p><p>getresuid returns -1 on error and 0 if success. getuid and geteuid don’t throw any error.</p><p>Similar functions for group ids are getresgid, getgid and getegid.</p><pre>//getuid and geteuid defined as per POSIX standard:<br>#include&lt;sys/types.h&gt;<br>#include&lt;unistd.h&gt;<br>uid_t getuid(void);<br>uid_t geteuid(void);</pre><pre>//getresuid defined as per POSIX standard:<br>#define _GNU_SOURCE<br>#include&lt;unistd.h&gt;<br>int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);</pre><h3>A piece of advice</h3><p>It is highly desirable that you lower down the privileges if you don’t wish to perform something with escalated privileges shortly. A potential threat can harm your system because of the escalated privileges.</p><h3>Can you get the result?</h3><p>What will be the result of the following program?</p><pre>#define _GNU_SOURCE</pre><pre>#include&lt;stdio.h&gt;<br>#include&lt;unistd.h&gt;<br>#include&lt;sys/types.h&gt;<br>#include&lt;stdint.h&gt;<br>int main()<br>{<br>  uid_t ruid,euid,suid;<br>  int ret = getresuid(&amp;ruid,&amp;euid,&amp;suid);<br>  printf(&quot;%jd %jd %jd\n&quot;,(intmax_t)ruid,(intmax_t)euid,   (intmax_t)suid);<br> <br>  ret = seteuid(1000);<br>  ret = getresuid(&amp;ruid,&amp;euid,&amp;suid);<br>  printf(&quot;%jd %jd %jd\n&quot;,(intmax_t)ruid,(intmax_t)euid,  (intmax_t)suid);<br>}</pre><p>The program.out binary generated is modified by executing the following command :</p><pre>sudo chown root program.out &amp;&amp; sudo chmod 4700 program.out</pre><p>It’s clear that you will have to use sudo to execute the binary as no permissions are provided to the users in general. The set uid value is set. What will be the result when the binary gets executed?</p><pre>sudo ./program.out</pre><p>The result :</p><pre>0 0 0 <br>0 1000 0</pre><p>The user will invoke the binary while behaving as a root user (sudo command). And thus the ruid, euid, and suid will be of the root (0, 0, 0). Upon calling seteuid function, the root only modifies the euid of the process according to the given argument.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcca08b26468" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>