2 Chapter 2: System Structures Operating System ServicesUser Operating System InterfaceSystem CallsTypes of System CallsSystem ProgramsOperating System Design and Implementation ()Operating System StructureVirtual Machines ()Operating System Generation ()System Boot
3 OS提供processes執行的環境。我們可以不同的的觀點來看OS：1. focuses on the services that a system provides2. on the interface that it makes available to users and programmers3. its components and their interconnections
4 2.1 Operating System Services OS提供的services主要有兩大類：1. helpful to the users (方便易用)2. 透過資源分享確保系統有效率的運作 (有效的運用資源)
5 2.1 Operating System Services 使用者介面程式的執行輸入和輸出作業檔案系統的使用通信錯誤的偵測資源的分配使用量統計保護和安全
6 Operating System Services One set of operating-system services provides functions that are helpful to the user:User interface - Almost all operating systems have a user interface (UI)Varies between Command-Line (CLI), Graphics User Interface (GUI), BatchCLI: where the user provides the input by typing a command string with the computer keyboard and the system provides output by printing text on the computer monitor. Used for system administration tasks etc.GUI: which accept input via devices such as computer keyboard and mouse and provide articulated graphical output on the computer monitor. There are at least two different principles widely used in GUI design: Object-oriented user interfaces (OOUIs) and application oriented interfacesBatch interfaces: are non-interactive user interfaces, where the user specifies all the details of the batch job in advance to batch processing, and receives the output when all the processing is done. The computer does not prompt for further input after the processing has started.
7 Operating System Services One set of operating-system services provides functions that are helpful to the user:Program execution - The system must be able to load a program into memory and to run that program, end execution, either normally or abnormally (indicating error)I/O operations - A running program may require I/O, which may involve a file or an I/O device.File-system manipulation - The file system is of particular interest. Obviously, programs need to read and write files and directories, create and delete them, search them, list file Information, permission management.
8 Operating System Services (Cont.) One set of operating-system services provides functions that are helpful to the user (Cont):Communications – Processes may exchange information, on the same computer or between computers over a networkCommunications may be via shared memory or through message passing (packets moved by the OS)Error detection – OS needs to be constantly aware of possible errorsMay occur in the CPU and memory hardware, in I/O devices, in user programFor each type of error, OS should take the appropriate action to ensure correct and consistent computingDebugging facilities can greatly enhance the user’s and programmer’s abilities to efficiently use the system
9 Operating System Services (Cont.) Another set of OS functions exists for ensuring the efficient operation of the system itself via resource sharingResource allocation - When multiple users or multiple jobs running concurrently, resources must be allocated to each of themMany types of resources - Some (such as CPU cycles,mainmemory, and file storage) may have special allocation code, others (such as I/O devices) may have general request and release code.Accounting - To keep track of which users use how much and what kinds of computer resourcesProtection and security - The owners of information stored in a multiuser or networked computer system may want to control use of that information, concurrent processes should not interfere with each otherProtection involves ensuring that all access to system resources is controlledSecurity of the system from outsiders requires user authentication, extends to defending external I/O devices from invalid access attemptsIf a system is to be protected and secure, precautions must be instituted throughout it. A chain is only as strong as its weakest link.
10 2.2 User Operating System Interface 兩種基本的users與OS之間溝通的方法Command-line interface (CLI) or command interpreter：allows users to directly enter commands that are to be performed by the OS.Graphical user interface (GUI)：provides a mouse-based window-and-menu system as an interface.
11 Command interpreter / CLI 有些OS在Kernel中包含了command interpreter(命令直譯程式)。而有些OS(例如 Windows XP & Unix)將command interpreter視為一個特殊程式(that is running when a job is initiated or when a user first logs on interactive systems )。稱為shellsTo get and execute the next user-specified command.利用CLI輸入指令。有很多情況是用來做檔案處理，例如：create, delete, list, print, copy, execute等等MS-DOS & Unix的shells用此方式運作
12 Command interpreter / CLI Implement方式The command interpreter itself contains the code to execute the command.The number of commands that can be given determines the size of the command interpreter.Implement most commands through system programsThe command interpreter 本身不了解此command，it merely use the command to identify a file to be loaded into memory and executed..The command interpreter, which can be small, does not have to be changed for new commands to be added.
13 Graphical User Interface / GUI User-friendly desktop metaphor interfaceUsually mouse, keyboard, and monitorIcons represent files, programs, actions, etcVarious mouse buttons over objects in the interface cause various actions (provide information, options, execute function, open directory (known as a folder)Many systems now include both CLI and GUI interfaces例如：Microsoft Windows is GUI with CLI “command” shell
14 2.3 System CallsProgramming interface to the services provided by the OSSystem calls: The mechanism used by an application program to request service from the OS例如：在Unix-based and POSIX-based systems, popular system calls are open, read, write, close, kill, exit…Typically written in a high-level language (C or C++)
15 Example of System Calls System call sequence to copy the contents of one file to another fileFig. 2.1 Example of how system calls are used.
16 Application programming interface (API) Mostly accessed by programs via a high-level Application Program Interface (API) rather than direct system call use應用程序介面為：「『電腦作業系統』或『程式函式庫』提供給應用程式呼叫使用的原始碼」。其主要目的是讓應用程式開發人員得以呼叫一組常式功能，而無須考慮其底層的原始碼為何、或理解其內部工作機制的細節。API本身是抽象的，它僅定義了一個介面，而不涉入應用程式如何實現的細節。
17 Application programming interface (API) Why use APIs rather than system calls?Concerns program portability一個程式設計者希望他用API設計的程式可以在其他能支援相同API的系統中執行。對程式設計者而言，API比實際system calls簡易多了
18 Example of Standard API Consider the ReadFile() function in theWin32 API—a function for reading from a fileA description of the parameters passed to ReadFile()HANDLE file—the file to be readLPVOID buffer—a buffer where the data will be read into and written fromDWORD bytesToRead—the number of bytes to be read into the bufferLPDWORD bytesRead—the number of bytes read during the last readLPOVERLAPPED ovl—indicates if overlapped I/O is being used
19 System-Call Interface Serves as the link to system calls made available by the operating system.Intercepts function calls in the API and invokes the necessary system call within the OSa number is associated with each system call, and the system-call interface maintains a table indexed according to these numbersThe system call interface invokes the intended system call in the OS kernel and returns the status of the system call and any return values.
20 System Call Implementation The caller need know nothing about how the system call is implementedJust needs to obey API and understand what OS will do as a result callMost details of OS interface hidden from programmer by APIManaged by run-time support library (set of functions built into libraries included with compiler)
21 API – System Call – OS Relationship Fig. 2.2 The handling of a user application invoking the open() system call.
22 System Call Parameter Passing Often, more information is required than simply identity of desired system callExact type and amount of information vary according to OS and call
23 System Call Parameter Passing Three general methods used to pass parameters to the OSSimplest: pass the parameters in registersIn some cases, may be more parameters than registers (next approach)Parameters stored in a block, or table, in memory, and address of block passed as a parameter in a registerThis approach taken by Linux and SolarisParameters placed, or pushed, onto the stack by the program and popped off the stack by the operating systemBlock and stack methods do not limit the number or length of parameters being passed (therefore some OS prefer these two approaches)
24 Parameter Passing via Table Fig. 2.3 Passing of parameters as a table.
25 2.4 Types of System Calls 系統呼叫可概略分成五類: p. 47 Process control File managementDevice managementInformation maintenanceCommunications
26 2.4 Types of System Calls 行程的控制(process control) 正常結束，中止執行(end, abort) 載入，執行(load, execute)建立行程，終止行程(create process, terminate process)獲取行程屬性，設定行程屬性(get process attributes，set process attributes)等待時間(wait for time)等待事件，顯示事件(wait event, signal event)配置及釋放記憶體空間(allocate and free memory)檔案的管理(File management)建立檔案，刪除檔案(create file, delete file)開啟，關閉(open,Close)讀出，寫入，重定位置(read, write, reposition)獲取檔案屬性，設定檔案屬性(get file attributes, set file attributes)
27 2.4 Types of System Calls 裝置的管理(Device management) 要求裝置，釋回裝置(request device, release device)讀出，寫入，重定位置(read, write, reposition)獲取裝置屬性，設定裝置屬性(get device attributes, set device attributes)遇輯上地加入或移去裝置(logically attach or detach devices)資訊維護(Information maintenance)取得時間或日期，設定時間或日期(get time or date, set time or date)取得系統資料，設定系統資料(get system data, set system data)取得行程、檔案或裝置的屬性(get process, file, or device attributes)設定行程、檔案或裝置的屬性(set process，file，or device attributes)
28 2.4 Types of System Calls 通信(communication) 建立，刪除通信連接(create, delete communication connection)傳送，接收訊息(send, receive messages)傳輸狀況訊息(transfer status information)連接或分離遠程裝置(attach or detach remote devices)
29 2.5 System ProgramsSystem programs provide a convenient environment for program development and execution. The can be divided into:File manipulationStatus informationFile modificationProgramming language supportProgram loading and executionCommunicationsApplication programsMost users’ view of the operation system is defined by system programs, not the actual system calls
30 System ProgramsProvide a convenient environment for program development and executionSome of them are simply user interfaces to system calls; others are considerably more complexFile management - Create, delete, copy, rename, print, dump, list, and generally manipulate files and directoriesStatus informationSome ask the system for info - date, time, amount of available memory, disk space, number of usersOthers provide detailed performance, logging, and debugging informationTypically, these programs format and print the output to the terminal or other output devicesSome systems implement a registry - used to store and retrieve configuration information
31 System Programs (cont’d) File modificationText editors to create and modify filesSpecial commands to search contents of files or perform transformations of the textProgramming-language support - Compilers, assemblers, debuggers and interpreters sometimes providedProgram loading and execution- Absolute loaders, relocatable loaders, linkage editors, and overlay-loaders, debugging systems for higher-level and machine languageCommunications - Provide the mechanism for creating virtual connections among processes, users, and computer systemsAllow users to send messages to one another’s screens, browse web pages, send electronic-mail messages, log in remotely, transfer files from one machine to another
32 2.7 Operating-System Structure 一個像現代作業系統這麼龐大&複雜的系統，如果要有合適且易於修改的功能，就必須小心的規劃。A common approach it to partition the task into small components rather than have one monolithic system.Each of these module should be a well-defined portion of the sytem, with carefully defined inputs, outputs, and functions
33 2.7 Operating-System Structure Simple Structure:MS-DOS – written to provide the most functionality in the least spaceNot divided into modulesAlthough MS-DOS has some structure, its interfaces and levels of functionality are not well separated
34 MS-DOS Layer Structure Application programs are able to access the basic I/O routines to write directly to the display and disk drives.Such freedom leaves MS-DOS vulnerable to errant (or malicious) programs, causing entire system creashes when user programs fail.Hareware limitation: Intel 8088 provides no dual mode and no hardware protection.Fig. 2.7 MS-DOS layer structure.
35 Layered ApproachThe operating system is divided into a number of layers (levels), each built on top of lower layers. The bottom layer (layer 0), is the hardware; the highest (layer N) is the user interface.With modularity, layers are selected such that each uses functions (operations) and services of only lower-level layers
36 Layered Operating System Fig. 2.9 A layered operating system.
37 The Advantages of the Layered Approach 分層方式最主要的好處是結構簡單和除錯。層次選定之後，每一個層次只能使用較低層的功能與服務。這種方式更容易做系統的除錯與驗證。第一層改正時，不必考慮系統的其餘部份，因為根據定義，它只甩了基礎的硬體 (假設它是正確的)去完成它的功能。一旦第一層改正後，在第二層的工作可以假設它的功能正確。在特定層次除錯時，如果發現錯誤，我們可以知道錯誤必定在那一層，因為在它底下的層都已改正。如此一來，當系統分層時，系統的設計與製作都可以簡化。
38 The Problems of the Layered Approach 如何適當的定義每一個層次：因為每ㄧ層只可以使用比自己低的層。例如：備用儲存體的裝置驅動程式(disk space used by virtual-memory algorithms)必須在比memory-management routines還低層，因為記憶體管理需要使用備用儲存體的ability.比較沒有效率：因為需要一層一層往下呼叫Microkernels & Modules的設計概念
39 UNIX System StructureFig. 2.8 UNIX system structure.
40 Microkernel System Structure Moves as much from the kernel into “user” space (移去kernel非必要的元件將OS結構系統化)主要功能：提供client program和同樣在使用者空間執行的 various services之間通訊的便利Communication takes place between user modules using message passing如果client program需要存取一個檔案，就必須和檔案伺服器聯絡。The client progarm和服務者從未直接通訊。
41 Microkernel System Structure Benefits:Easier to extend a microkernelEasier to port the operating system to new architecturesMore reliable (less code is running in kernel mode)More secureDetriments:Performance overhead of user space to kernel space communication (The first release of Windows NT)Windows NT 4.0 paratially redressed the performce problem by moving layers from user space to kernel space and integrating them more closely.
42 Modules Most modern operating systems implement kernel modules Uses object-oriented approachEach core component is separateEach talks to the others over known interfacesEach is loadable as needed within the kernelOverall, similar to layers but with more flexible
43 Solaris Modular Approach Fig Solaris loadable modules.