--- tags: OS --- # OS Homework 1: Kernel module 沈冠妤 105042015 外語20 ## :memo: Code Explain ### Step 1: Include header files ![](https://i.imgur.com/P9qm0ML.png) Include **<linux/slab.h>** for **kmalloc()** and **kfree()**. --- ### Step 2: Construct and traverse linked-list ![](https://i.imgur.com/ABE3G5x.png) Here I used a for-loop to construct five new nodes for the list. Then, iterate the list with **list_for_each()**. * **INIT_LIST_HEAD( list ):** initialize a list_head structure @list: list_head structure to be initialized * **list_add_tail( new, head )**: add a new entry @new: new entry to be added @head: the head of the added list * **list_for_each( pos, head )**: iterate over a list @pos: the list_head used as a loop cursor. @head: head of the list. * **list_entry( ptr, type, member )**: retrieve the struct for this entry @ptr: the list_head pointer. @type: the type of the struct this list is embedded in. @member: the name of the list_head. The constructed linked-list is as following: || Student ID | Year | Month | Day | |--| -------- | -------- | -------- |-------- | |Head| 105042015 | 1997 | 1 | 1| || 105042016 | 2000 | 3 | 6| || 105042017 | 2003 | 5 | 11| || 105042018 | 2006 | 7 | 16| |Tail| 105042019 | 2009 | 9 | 21| --- ### Step 3: Traverse backward and free list ![](https://i.imgur.com/uzr28K6.png) Iterate backwardly with list_for_each_prev(), and free memory with kfree(). * **list_for_each_prev( pos, head ):** iterates a list backwardly. @pos: the &struct list_head used as a cursor. @head: head of the list. --- ## :memo: Output Screenshot ![](https://i.imgur.com/NurCTLj.png) ## :memo: Problems Occured * Segmentation fault (core dumped) * rmmod: ERROR: Module kernel is in use 有些pointer錯誤好像會造成可以insmod,但無法rmmod的情況(用lsmod檢查,hw1.ko有被load進去)。 - [ ] 改程式上的錯誤 - [ ] 重開virtual box,強制卸載kernel module(但code沒改好再insmod依然會發生) ## :memo: Reference Function Explainations: https://github.com/torvalds/linux/blob/master/include/linux/list.h Tutorial on writing kernel modules: https://jerrynest.io/how-to-write-a-linux-kernel-module/