# CH1 問題討論與解答
- **Practice Exercises**
1. What are the three main purposes of an operating system? (東東)
- To provide an environment for a computer user to execute programs on computer hardware in a convenient and efficient manner.
- An <u>environment</u> between <u>applications</u> and and <u>hardware</u>


- <u>User Interface</u>
- Command Line Interface
<img src="https://ubuntucommunity.s3.dualstack.us-east-2.amazonaws.com/original/2X/f/f5787298cfda955e0e223f461e962d7dc8c376cc.png" width=400px>
- GUI (Graphic user Interface
ex: Windows, macOS, Android, iOS)
<img src="https://1.bp.blogspot.com/-rTXDKiQ3xYI/YMmFs-mn3TI/AAAAAAAAE3A/uVtMzTisL28kASy6W8SnvJp43_NwwhzlgCLcBGAsYHQ/s16000/bandicam%2B2021-06-16%2B12-55-23-653.png" width=400px>
<img src="https://img.technews.tw/wp-content/uploads/2020/06/23061324/2020-06-23-05.17.23.png" width=400px>
- To allocate the separate resources of the computer as needed to solve the problem given. The allocation process should be as fair and efficient as possible.
- <u>Resource Allocation</u>
<img src="https://i.imgur.com/UJXANBY.png" width=400px>
- <u>Process Allocation</u>
<img src="http://gs-blog-images.s3-ap-southeast-1.amazonaws.com/gate-exam/wp-content/uploads/2015/11/27025952/image0019.png" width=400px>
- As a control program it serves two major functions:
1. supervision of the execution of user programs to prevent errors and improper use of the computer
- Error Detection
- <img src="https://i.imgur.com/jOeLREH.png">
- <img src="https://miro.medium.com/max/1024/0*AFanMpbTy5FdCuJv.png" width=600px>
2. management of the operation and control of I/O devices.

2. We have stressed the need for an operating system to make efficient use of the computing hardware. When is it appropriate for the operating system to forsake this principle and to “waste” resources? Why is such a system not really wasteful? (承翰)
<b>A:Such operation system is not really wasteful because of enhancing the convenience of using computer. A graphical user interface may waste more resources than CLI,but it optimizes the user's interaction with the system.</b><br>
<b>For example,when we use computer by prompt. It may not use so much resourses.But when we use GUI to interact with PC,it may use the required tools such as mouse,USB,etc.</b>
3. What is the main difficulty that a programmer must overcome in writing an operating system for a real-time environment? (彭彭)
- Define what is real-time environment?
- Hard RTOS
- Soft RTOS
- Keys for a real-time system
- Minimum Interrupt Latency
- Minimum Context Switching Latency
- CPU scheduling
- Preemption
- Sharing Resources if Possible
- Interrupts
- Temporarily Disableable
- Defer Non-Critical Interrupts if Possible
- Memory Management
- No Memory Leak
- Compile-Time Binding
4. Keeping in mind the various definitions of operating system, consider whether the operating system should include applications such as web browsers and mail programs. Argue both that it should and that it should not, and support your answers. (東東 4)
- An argument in favor of including popular applications with the operating system is that if the application is embedded within the operating system, it is likely to be better able to take advantage of features in the kernel and therefore have performance advantages over an application that runs outside of the kernel.
- Arguments against embedding applications within the operating system typically dominate however:
1. the applications are applications - and not part of an operating system
2. any performance benefits of running within the kernel are offset by security vulnerabilities
3. it leads to a bloated operating system.
[A modern perspective](https://www.quora.com/Is-web-browser-and-email-are-part-of-operating-system)
5. How does the distinction between kernel mode and user mode function as a rudimentary form of protection (security) system? (宜蓁)
<b>The distinction between kernel mode and user mode provides a rudimentary form of protection in the following manner. Certain instructions can be executed only when the CPU is in kernel mode. Similarly, hardware devices can be accessed only when the program is in kernel mode, and interrupts can be enabled or disabled only when the CPU is in kernel mode. Consequently, the CPU has very limited capability when executing in user mode, thereby enforcing protection of critical resources.</b>
- The hardware allows `privileged instructions` to be executed only in kernel mode. If an attempt is made to execute a privileged instruction in user mode, the hardware does not execute the instruction but rather treats it as illegal and traps it to the operating system.
6. Which of the following instructions should be privileged? (東 6)
1. Set value of timer.
2. Read the clock.
3. Clear memory.
4. Issue a trap instruction.
5. Turn off interrupts.
6. Modify entries in device-status table.
7. Switch from user to kernel mode.
8. Access I/O device.
Privileged Instructions possess the following characteristics :
- If any attempt is made to execute a Privileged Instruction in User Mode, then it will not be executed and treated as an illegal instruction. The Hardware traps it in the Operating System.
- Before transferring the control to any User Program, it is the responsibility of the Operating System to ensure that the Timer is set to interrupt. Thus, if the timer interrupts then the Operating System regains the control.
Thus, any instruction which can modify the contents of the Timer is Privileged Instruction.
- Privileged Instructions are used by the Operating System in order to achieve correct operation.
What are Non-Privileged Instructions?
> The Instructions that can run only in User Mode are called Non-Privileged Instructions .
The following operations need to be privileged
- Set value of timer
- Clear memory
- Turn off interrupts
- Modify entries in device-status table
- access I/O device
The rest can be performed in user mode.
7. Some early computers protected the operating system by placing it in a memory partition that could not be modified by either the user job or the operating system itself. Describe two difficulties that you think could arise with such a scheme. (彭彭 3)
- Operating System should restart for any updates.
- Some data (password for example) required by OS should save in user memory space without protection.
8. Some CPUs provide for more than two modes of operation. What are two possible uses of these multiple modes? (Ariana)
https://graceful-deposit-2ae.notion.site/exercise-1-8-20993330f2734e42a7843c235491c338
9. Timers could be used to compute the current time. Provide a short description of how this could be accomplished. (邱)
<b>Answer: A program could use following approach to compute the current time using timer interrputs.
1. Set a timer for some time in the future and go to sleep.
2. An interrupt wake up the program, which is using to keep track of the number of interrupts it has received, it also can update its local state.
3. Repeat this process of cotinually setting timer interrupts and updating its local state when these timer interrupts are raised.</b>
10. Give two reasons why caches are useful. What problems do they solve? What problems do they cause? If a cache can be made as large as the device for which it is caching (for instance, a cache as large as a disk), why not make it that large and eliminate the device? (邱 3)
<b>1. Two Reason why cahces are useful</b>
- Cache is a relatively fast memory. so getting some data from cache is faster than getting it from main or secondary memory.
- Caches are particularly useful when we need to exchange data - transfer speeds are much faster when using caches, and the transfer can be done without using the main memory.
<img src="https://i.imgur.com/r0ZaBhU.png" width='300' height='300'>
<img src="https://i.imgur.com/oebfMIb.png" width='300' height='300'>
<img src="https://i.imgur.com/I57MM6d.png">
<b>What problems do caches cause?</b>

<b>The main problems caused by caches are inconsistency, and cache miss.</b>
- **cache inconsistency**: a copy of data may exist simultaneously in several caches. Since the various CPUs can all execute in parallel, we must make sure that an update to the value of data in one cache is immediately reflected in all other caches where data resides.
- **cache miss**: if data is not in the cache, we need to go to main memory get the data and copy it to the cache and replace another cache data, if we don't have greate replacement policy, we will spend a lot of time transfering data to the cache.
<b>Why not make cache large and eliminate the device?</b>

<b>關於 Cache 的其他補充資料:https://zhuanlan.zhihu.com/p/31875174</b>
11. Distinguish between the client–server and peer-to-peer models of distributed systems. (Ariana 3)
- <b>client–server model</b>
- firmly distinguishes the roles of the client and server
- the client requests services that are provided by the server
- for example: email, web
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fb/Server-based-network.svg/1024px-Server-based-network.svg.png" width=400px>
- <b>peer-to-peer model</b>
- all nodes in the system are considered peers and thus may act as either clients or servers
- a node may request a service from another peer, otherwise may provide a service to other
peers in the system
- structured network / unstructured network / hybrid model
- for example: foxy, skype, bitcoin
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/3f/P2P-network.svg/1024px-P2P-network.svg.png" width=400px>
- **Excercises**
12. In a multiprogramming and time-sharing environment, several users share the system simultaneously. This situation can result in various security problems. (承翰 3)
<b>1.What are two such problems?</b>
<p style='color:blue'>there are some privacy problems:
<ol>
<li style='color:green'>If serveral users share the system,one user can read private information of others.</li>
<li style='color:green'>Continue to the previous issue , Maybe one user can destroy the data of others</li>
</ol>
</p>
<b>2. Can we ensure the same degree of security in a time-shared machine as in a dedicated machine? Explain your answer.</b>
<p style='color:blue'>we can never be sure that our software doesn't have bugs, so we can never be sure that we prevent all sharing of data and fairly allocate computer resources.
</p>
13. The issue of resource utilization shows up in different forms in different types of operating systems. List what resources must be managed carefully in the following settings: (悅心 3)
**1. Mainframe or minicomputer systems**
- **Memory Resources**
- **CPU Resources**
- **Storage**
Storage is an important resource that requires to be managed due to being shared among multiple users.
- **Network Bandwidth**
Sharing of data is a major activity in systems shared by multiple users. It is important to manage network bandwidth in such systems.
**2. Workstations connected to servers**
- **Memory Resources**
When Workstations are connected to servers, multiple applications run on multiple Workstations on a single server. This is an important factor due to which Memory management is required in Workstations connected to servers.
- **CPU Resources**
Multiple Workstations make request to access resources to accomplish the tasks assigned to them. To ensure the fair and efficient completion of tasks, it is important to manage CPU resources in workstations connected to servers.
**3. Mobile computers**
- **Power Consumption**
- **Memory Resources**
14. Under what circumstances would a user be better off using a timesharing system than a PC or a single-user workstation? (宜蓁 3)
* time-sharing system:
* **few other users**
* the task is **large**
* the hardware is **fast**
:::info
The full power of the system can be brought to bear on the user’s problem. The problem can be solved faster than on a personal computer.
:::
* personal computer:
* **lots of other users** need resources at the same time
* the job is **small** enough to be executed reasonably on it (performance is sufficient to execute the program)
15. Describe the differences between symmetric and asymmetric multiprocessing. What are three advantages and one disadvantage of multiprocessor systems? (東 5)
- Differences between symmetric and asymmetric multiprocessing
| Parameter | Symmetirc multiprocessing | Asymmetric multiprocessing|
|--------| -----|------|
|Diagram|  | 
|Relationship| All the processors are **equal and treated as the same**| Not all the processors have equal precedence|
|Approach| It uses the ready queue approach. Once a processor gets free it picks a job from the job queue| It follows the **master-slave** approach. The master processor assigns the job to other processors.|
|Cost|It is costlier in implementation | It is comparatively cheaper and easy to install|
|(Operating System Tasks)|All the processors can take part in the OS tasks based on availability. |OS tasks are carried only by the master processor. |
| Communication | All the processor communicates between them using the shared memory.| There is no communication overhead; all the processors are controlled by the master processor.|
|Design| Symmetric processing is complex in design| It is simple and easy to understand.|
|Architecture| All the processors have the same Architecture.| The architecture may vary for each processor.|
|Effect in Failure |If a processor is failed or stopped working the overall capacity of the computer drops.| The failed master processor is replaced by another slave processor and if a slave processor its tasks are switched to others.|
<br/>

- What are three advantages and one disadvantage of multiprocessor systems?
- <u>*Advantages*</u>
- **Increase Throughput**
Throughput = number of processes executed by the CPU at a given time
- **Increase Reliability**
As multiple processors share their work between one and another so work is completed with collaboration. That means these systems are reliable.
- **Cost Saving/Economic of scale**

- <u>*Disadvantages*</u>
OS implementation is complex and hence more expensive
- **Communication** between multiple processors
- **Deadlock**: If any processor is already using the I/O device then other processors cannot use the same I/O device which creates deadlock.
16. How do clustered systems differ from multiprocessor systems? What is required for two machines belonging to a cluster to cooperate to provide a highly available service? (月薪 4)
1-
- Clustered system are composed of two or more **individual systems** compiled together.
- It shares storage and are closely lined via LAN (Local Area Network) networking.
2-
- The state on the two machines should be **replicated** and should be **consistently updated**.
- When one of the machines fail, the other could then take-over the functionality of the failed machine.
17. Consider a computing cluster consisting of two nodes running a database. Describe two ways in which the cluster software can manage access to the data on the disk. Discuss the benefits and disadvantages of each. (彭彭 4)
* 1 for writing and replicating data to another, and 1 for reading.
Easy to synchronize data. single failure.
* every nodes for reading and writing, when writing, replicating data to another.
Hard to synchronize data. no single failure.
18. How are network computers different from traditional personal computers? Describe some usage scenarios in which it is advantageous to use network computers.(宜蓁 4)
- How are network computers different from traditional personal computers?
- **network computer**: it has a minimal operating system and mostly depends on the central server for the services.
- **personal computer**: it functions in a standalone manner providing all the required functionality.
:::info
- **The Network Computer**: a diskless desktop computer device.
- **A diskless node**: a personal computer without disk drives, which employs network booting to load its operating system from a server.
:::

(The IBM Network Station)
- Describe some usage scenarios in which it is advantageous to use network computers.
- **sharing of resources and data**: copy files from one machine to another (not secure like the personal computer)
19. What is the purpose of interrupts? How does an interrupt differ from a trap? Can traps be generated intentionally by a user program? If so, for what purpose? (承翰 4)
<b> <p style='color:orange'>An interrupt</p> is an electrical signal sent from one component of the
computer to another, signaling that an event has occurred which
requires immediate action by the component receiving the interrupt.
<p style='color:red'>A trap </p>is a specific type of interrupt which is generated by software either</b><br>
<ul>
<li>some unusual condition, such as an array index out of bounds, or </li>
<li>a request for an operating system service (a system call.)</li>
</ul><br>
<img src='https://img.onl/Xoei59'>
<b>User programs can generate traps, although not all high-level
programming languages make this facility directly available to the
programmer. (Ada, C and Java do allow the programmer to generate
traps. Traps are called “exceptions” in Ada and Java, and “signals”
in C. In addition, C allows programmers to bypass the API and make
system calls directly.)</b><br>
<b>Traps are used to notify the CPU that some unusual software event
has taken place, or that some special service has been requested by
the program. The CPU can then either terminate the program, or
interrupt the normal execution sequence of the program and transfer
control to a special segment of code.</b><br>
20. Direct memory access is used for high-speed I/O devices in order to avoid increasing the CPU’s execution load. (彭 5)
1. How does the CPU interface with the device to coordinate the transfer?
2. How does the CPU know when the memory operations are complete?
3. The CPU is allowed to execute other programs while the DMA controller is transferring data. Does this process interfere with the execution of the user programs? If so, describe what forms of interference are caused.
<br/>
- CPU initialize DMA controller with a count of the number of words to transfer and the memory address to use and command peripheral device controller (ex. Disk Controller) to init data transfer.
- DMA controller interrupts CPU if memory operations completed.
- Bus Mastering feature, supported by modern bus architecture (ex. PCI), controls which device can access memory.
21. Some computer systems do not provide a privileged mode of operation in hardware. Is it possible to construct a secure operating system for these computer systems? Give arguments both that it is and that it is not possible. (承翰 5)
<br>
<b>1、Theoretically, this can be done by running only one process at a time and carefully monitoring it and inspecting its output. However, this surely affects the efficency of the system (it will run much more slowly),and we must make sure to know the priority somehow (which is rathter hard if we do not have modes).</b>
<br>
<b>2、There are several possible approaches for implementing a secure operating system. One is to write a simulator for a dual-mode processor (one with a privileged mode) and to run the operating system on top of this emulator. A slight variant of this is to run user code only in an emulator; this is the approach you use in Nachos.</b>
<img src='https://jeffprogrammer.files.wordpress.com/2016/10/001.jpg'></img>
<a href='https://cseweb.ucsd.edu/classes/fa20/cse120-a/hw/hw1-sol.html'>2的資料來源</a>
<a href='https://www.w3study.wiki/a/202106/130670.html'> Nachos資料 </a>
22. Many SMP systems have different levels of caches; one level is local to each processing core, and another level is shared among all processing cores. Why are caching systems designed this way? (彭 6)
- Multi-level caches improve overall system performance.
- Many processes are executed only by 1 processor in lifetime, local cache can be the most efficiency way to cache data.
- If a process is executed by more than 1 processors, shared cache can confirm that data modified by 1 processor can be updated to another processor.
23. Consider an SMP system similar to the one shown in Figure 1.6. Illustrate with an example how data residing in memory could in fact have a different value in each of the local caches. (宜 6)

1. Say processor 1 reads data A with value 5 from main memory into its local cache. Similarly, processor 2 reads data A into its local cache as well.
2. Processor 1 then updates A to 10. However, since A resides in processor 1’s local cache, the update only occurs there and not in the local cache for processor 2.
24. Discuss, with examples, how the problem of maintaining coherence of cached data manifests itself in the following processing environments: (宇軒 5)

1. **Single-processor systems**
No difficulties, since access to interger A will always be to the copy at the highest level of hierarchy.
In a multitasking environment, CPU is switched back and forth among various processes, each process will obtain the most recently updated value of A.
2. **Multiprocessor systems**
Each of the CPU core might contain its own local cache, a copy of A may exist simultaneously in several caches, we must make sure that an update to the value of A is immediately reflected in all other caches where A resides.
this situation is called "cache coherency", is usually a hardware problem.
3. **Distributed systems**
several copies of the same file can be kept on different computers, various replicas may be accessed and updated concurrently.
some distributed systmens ensure when a replica is updated in one place, all other replicas are brought up to date as soon as possible.
25. Describe a mechanism for enforcing memory protection in order to prevent a program from modifying the memory associated with other programs. (宇軒 6)
**The processor could keep track of what locations are associated with each process and limit access to locations that are outside of a program’s extent. Information regarding the extent of a program’s memory could be maintained by using base and limits registers and by performing a check for every memory access.**
**Base register** : load the phsical location where the process start.
**Limits register** : load the length of the process.
26. Which network configuration—LAN or WAN—would best suit the following environments? (悅心 5)
:::info
依照地理位置界定電腦網路
- **Local Area Network (LAN 區域網路)**
在相對短的距離內連接電腦,讓它們可以共用資料、檔案及資源。 例如:連接辦公大樓、學校或醫院中的所有電腦,且通常由私人擁有及管理。
- **Wide Area Network(WAN 廣域網路)**
可在廣泛的區域連接不同電腦。例如:跨越不同地區甚或不同洲。 網際網路是規模最大的 WAN,連接全球數十億台電腦。 通常管理使用集體或分散式所有權模式。
:::
- 1. campus student union -> **LAN**
- 2. Several campus locations across a statewide university system -> **WAN**
- 3. A neighborhood -> **LAN**
27. Describe some of the challenges of designing operating systems for mobile devices compared with designing operating systems for traditional PCs. (月薪 6)
- **Kernel**
- **Middleware** must be designed to support a set of software frameworks that provide additional services to application developers.(touch, swip the screen)
- Must have a good **support for external peripheral devices** like GPS.
- Must balance the **performance** and **resources**.
28. What are some advantages of peer-to-peer systems over client-server systems?(Ariana 4)
<b><p style='color:green'>Advantages:</p></b>
* **Easy file sharing**: An advanced P2P network can share files quickly over large distances. It allows for convenient file sharing and eliminates the need for an intermediate server to do so.
* **Reduced costs**: There is no need to invest in a separate computer for a server when setting up a P2P network. It doesn’t require a full-time system administrator.
* **Scalability**: P2P network extends to include new clients easily. This benefit makes these networks more flexible than client-server networks.
* **Reliability**: Unlike a client-server network, which can fail if the central server malfunctions, a P2P network will remain functional even if the central server crashes. This also prevents bottlenecking since traffic is distributed across multiple computers.
* **High performance**: While a client-server network performs less effectively when more clients join the network, a P2P network can improve its performance when more clients join it. This is because each client in a P2P network is also a server that contributes resources to the network.
* **System back-up**: The networking in the P2P network will rarely stop making it highly reliable. In the event of a breakdown of one computer, the others will continue to work seamlessly. In addition, there is a slim chance of losing data and files being secured easily.
<b><p style='color:red'>Disadvantages: </p></b>
* **Network security**: As with most network systems, unsecured and unsigned codes may allow remote access to files on a victim's computer or even compromise the entire network.
* **Decentralization**: No centralized server is available to manage and control the access of data.
29. Describe some distributed applications that would be appropriate for a peer-to-peer system. (Ariana 5)
* file sharing: Napster.Gnutella.Foxy
* VoIP(Voice over IP): Skype
* Cryptocurrency: Bitcoin
* Freenet: WikiLeaks.Silk Road

30. Identify several advantages and several disadvantages of open-source operating systems. Include the types of people who would find each aspect to be an advantage or a disadvantage. (承翰 6)
<p style="color:red;">Advantages</p>
<ol>
<li> Cost Effective </li>
Generally an open source software is free to use.
<li> Reliability </li>
The open source software is created by expert developers and guided by them. Therefore, there is very less chance that someone will identify flaws in the software.
<li> Flexibility </li>
Unlike in proprietary software, users in open source software does not experience vendor lock-ins. Even if there are irrelevant features, the users can effectively remove them. This is because the source code is free to modify. Users do not need to stick to the provider's requirements.
<li> Scalability </li>
Similar to a Linux operating system, an open source software can also be scaled easily. According to the needs, an open source software can be scaled up and down so that businesses could achieve their desired results.
</ol>
<p style="color:red;">Disadvantages</p>
<ol>
<li>User Friendly</li>
Not all the open source applications are easy to use. The Graphical User Interface may not be user friendly for the users to understand. Only tech savvy people will be able to understand this interface.
If used in an organization, the employees must be trained accordingly to operate it. For this the companies need to hire trainers all which can cause additional expenses.
<li>Security</li>
As mentioned earlier, the source code present in an open source software is free to edit. The problem comes when someone misuses the code for their own benefits. While many of them use it for improving the software, others could invite vulnerabilities such as identity theft and malicious transfers.
<li>Compatibility</li>
Some applications cannot support both open source software and proprietary software. If proprietary hardware needs to run on an open source machine, it requires third party drivers. However, that cannot guarantee that the hardware will work on the host machine. Therefore, before purchasing a hardware it is recommended to check it is supported by the open source application.
</ol>
</p>