LwIP 之三 操作系统隔离接口 sys_arch
??目前,網絡上多數文章所使用的 LwIP 版本為1.4.1。最新版本為 2.0.3。從 1.4.1 到 2.0.3(貌似從2.0.0開始), LwIP 的源碼有了一定的變化,甚至于源碼的文件結構也不一樣,內部的一些實現源文件也被更新和替換了。
簡介
?? LwIP 為了適應不同的操作系統,在代碼中沒有使用和某一個操作系統相關的系統調用和數據結構。而是在 LwIP 和操作系統之間增加了一個操作系統封裝層。操作系統封裝層為操作系統服務(定時,進程同步,消息傳遞)提供了一個統一的接口。
??在 LwIP 源碼的doc/sys_arch.txt文件中,有詳細的說明需要移植者實現那些文件及函數。以下主要是針對該文件的一些翻譯。
??The operating system emulation layer provides a common interface between the LwIP code and the underlying operating system kernel. The general idea is that porting LwIP to new architectures requires only small changes to a few header files and a new sys_arch implementation. It is also possible to do a sys_arch implementation that does not rely on any underlying operating system.
??操作系統仿真層提供 LwIP 代碼和底層操作系統內核之間的通用接口。 總體思路是將 LwIP 移植到新體系結構中只需對少量頭文件和對新sys_arch實現進行小改動即可,且可以不依賴任何底層操作系統的sys_arch實現。
??The sys_arch provides semaphores, mailboxes and mutexes to LwIP . For the full LwIP functionality, multiple threads support can be implemented in the sys_arch, but this is not required for the basic LwIP functionality. Timer scheduling is implemented in LwIP , but can be implemented by the sys_arch port ( LwIP _TIMERS_CUSTOM==1).
??sys_arch為 LwIP 提供信號量,郵箱和互斥量。 對于完整的 LwIP 功能,可以在sys_arch中實現多線程支持,但對于基本的 LwIP 功能來說,這不是必需的。 定時器調度在 LwIP 中實現,但可以通過sys_arch( LwIP _TIMERS_CUSTOM == 1)實現。
??In addition to the source file providing the functionality of sys_arch,the OS emulation layer must provide several header files defining macros used throughout LwIP . The files required and the macros they must define are listed below the sys_arch description.
??除了提供sys_arch功能的源文件之外,操作系統仿真層還必須提供幾個用于定義整個 LwIP 中使用的宏的頭文件。 所需的文件和宏必須安裝如下列出的描述進行定義。
??Semaphores can be either counting or binary - LwIP works with both kinds. Mailboxes should be implemented as a queue which allows multiple messages to be posted (implementing as a rendez-vous point where only one message can be posted at a time can have a highly negative impact on performance). A message in a mailbox is just a pointer, nothing more.
??信號量可以是計數或二進制 —— LwIP 可以同時使用這兩種類型。 郵箱應該作為允許發布多個郵件的隊列來實現(作為一次只能發布一條郵件的rendez-vous點,可能會對性能產生很大的負面影響)。 郵箱中的消息只是一個指針,僅此而已。
??Semaphores are represented by the type “sys_sem_t” which is typedef’d in the sys_arch.h file. Mailboxes are equivalently represented by the type “sys_mbox_t”. Mutexes are represented by the type “sys_mutex_t”. LwIP does not place any restrictions on how these types are represented internally.
??信號量由sys_arch.h文件中typedef的類型“sys_sem_t”表示。 郵箱等同于“sys_mbox_t”類型。 互斥體由“sys_mutex_t”類型表示。 LwIP 并沒有對這些類型如何在內部表現出任何限制。
例如,在使用FreeRTOS時移植時,sys_arch.h文件中有如下語句
??Since LwIP 1.4.0, semaphore, mutexes and mailbox functions are prototyped in a way that allows both using pointers or actual OS structures to be used. This way, memory required for such types can be either allocated in place (globally or on the stack) or on the heap (allocated internally in the "_new()" functions).
??從 LwIP 1.4.0版本開始,信號量,互斥和郵箱功能的原型方式允許使用指針或實際的OS結構體。 這樣,這些類型所需的內存可以在使用的地方分配(全局或堆棧)或在堆上(在“ _ new()”函數內部分配)。
sys_arch
??該部分主要指需要實現的各函數,通常做法為建立一個名為sys_arch.c的文件,在其中實現以下函數:
??The following functions must be implemented by the sys_arch: 以下函數必須由sys_arch實現:
- void sys_init(void):Is called to initialize the sys_arch layer.被調用來初始化sys_arch層。
- err_t sys_sem_new(sys_sem_t *sem, u8_t count):Creates a new semaphore. The semaphore is allocated to the memory that ‘sem’ points to (which can be both a pointer or the actual OS structure).創建一個新的信號量。信號量分配給’sem’指向的內存(可以是指針或實際的OS結構)。
??The “count” argument specifies the initial state of the semaphore (which iseither 0 or 1).“count”參數指定信號的初始狀態(可以是0或1)。
??If the semaphore has been created, ERR_OK should be returned. Returning any other error will provide a hint what went wrong, but except for assertions, no real error handling is implemented. 如果信號量已經創建,則應返回ERR_OK。 返回任何其他錯誤將提供一個出了什么問題的提示,但除了斷言之外,沒有實現真正的錯誤處理。 - void sys_sem_free(sys_sem_t *sem):Deallocates a semaphore.釋放一個信號量
- void sys_sem_signal(sys_sem_t *sem):Signals a semaphore. 指示信號量
- u32_t sys_arch_sem_wait(sys_sem_t *sem, u32_t timeout):Blocks the thread while waiting for the semaphore to be signaled. If the “timeout” argument is non-zero, the thread should only be blocked for the specified time (measured in milliseconds). If the “timeout” argument is zero, the thread should be blocked until the semaphore is signalled.在等待信號量發出信號時阻塞線程。 如果“超時”參數不為零,則線程只應在指定時間內被阻塞(以毫秒為單位)。 如果“超時”參數為零,則線程應被阻塞,直到信號被發信號。
??If the timeout argument is non-zero, the return value is the number of milliseconds spent waiting for the semaphore to be signaled. If the semaphore wasn’t signaled within the specified time, the return value is SYS_ARCH_TIMEOUT. If the thread didn’t have to wait for the semaphore(i.e., it was already signaled), the function may return zero.如果超時參數非零,則返回值是等待信號量發送信號所用的毫秒數。 如果在指定時間內沒有發出信號量,則返回值為SYS_ARCH_TIMEOUT。 如果線程不必等待信號量(即它已經被發信號),該函數可能返回零。
??Notice that LwIP implements a function with a similar name, sys_sem_wait(), that uses the sys_arch_sem_wait() function.請注意, LwIP 實現了一個具有類似名稱的函數sys_sem_wait(),該函數使用了sys_arch_sem_wait() 函數。 - int sys_sem_valid(sys_sem_t *sem): Returns 1 if the semaphore is valid, 0 if it is not valid.如果信號量有效返回1,如果無效則返回0。
??When using pointers, a simple way is to check the pointer for != NULL.當使用指針時,一個簡單的方法是檢查指針 != NULL。
??When directly using OS structures, implementing this may be more complex.當直接使用OS結構時,實現這可能會更復雜。
??This may also be a define, in which case the function is not prototyped. 這也可能是一個定義,在這種情況下,函數不是原型的。 - void sys_sem_set_invalid(sys_sem_t *sem): Invalidate a semaphore so that sys_sem_valid() returns 0. 使信號量失效,以便sys_sem_valid() 返回0。
??ATTENTION: This does NOT mean that the semaphore shall be deallocated:sys_sem_free() is always called before calling this function! 注意:這并不意味著信號量應該被釋放:在調用這個函數之前總是要調用sys_sem_free()!
??This may also be a define, in which case the function is not prototyped. 這也可能是一個定義,在這種情況下,函數不是原型的。 - void sys_mutex_new(sys_mutex_t *mutex):Creates a new mutex. The mutex is allocated to the memory that ‘mutex’ points to (which can be both a pointer or the actual OS structure).創建一個新的互斥體。 互斥量被分配給’互斥’指向的內存(可以是指針或實際的操作系統結構)。
??If the mutex has been created, ERR_OK should be returned. Returning any other error will provide a hint what went wrong, but except for assertions, no real error handling is implemented.如果該互斥體已創建,則應返回ERR_OK。 返回任何其他錯誤將提供一個出了什么問題的提示,但除了斷言之外,沒有實現真正的錯誤處理。 - void sys_mutex_free(sys_mutex_t *mutex): Deallocates a mutex.釋放一個互斥信號量
- void sys_mutex_lock(sys_mutex_t *mutex):Blocks the thread until the mutex can be grabbed.阻塞線程直到可以獲取到互斥信號量。
- void sys_mutex_unlock(sys_mutex_t *mutex):Releases the mutex previously locked through ‘sys_mutex_lock()’.釋放先前通過sys_mutex_lock()鎖定的互斥鎖。
- void sys_mutex_valid(sys_mutex_t *mutex): Returns 1 if the mutes is valid, 0 if it is not valid.如果互斥信號量有效則返回1,如果無效則返回0
??When using pointers, a simple way is to check the pointer for != NULL.當使用指針時,一個簡單的方法是檢查指針 != NULL。
??When directly using OS structures, implementing this may be more complex.當直接使用OS結構時,實現這可能會更復雜。
??This may also be a define, in which case the function is not prototyped.這也可能是一個定義,在這種情況下,函數不是原型的。 - void sys_mutex_set_invalid(sys_mutex_t *mutex):Invalidate a mutex so that sys_mutex_valid() returns 0. 使互斥體失效,以便sys_mutex_valid()返回0。
??ATTENTION: This does NOT mean that the mutex shall be deallocated:sys_mutex_free() is always called before calling this function!這并不意味著該互斥體將被釋放:在調用此函數之前總是調用sys_mutex_free()!
??This may also be a define, in which case the function is not prototyped.這也可能是一個定義,在這種情況下,函數不是原型的。 - err_t sys_mbox_new(sys_mbox_t *mbox, int size):Creates an empty mailbox for maximum “size” elements. Elements stored in mailboxes are pointers. You have to define macros “_MBOX_SIZE” in your LwIP opts.h, or ignore this parameter in your implementation and use a default size.創建最多包含size個元素的控郵箱。元素的指針存儲在郵箱中。必須在LwIP opts.h中定義宏值_MBOX_SIZE,或者忽略該參數,已使用默認大小。
??If the mailbox has been created, ERR_OK should be returned. Returning any other error will provide a hint what went wrong, but except for assertions,no real error handling is implemented.如果郵箱已被創建,則返回ERR_OK。返回任何其他錯誤將提供一個出了什么問題的提示,但除了斷言之外,沒有實現真正的錯誤處理。 - void sys_mbox_free(sys_mbox_t *mbox):Deallocates a mailbox. If there are messages still present in the mailbox when the mailbox is deallocated, it is an indication of a programming error in LwIP and the developer should be notified.
- void sys_mbox_post(sys_mbox_t *mbox, void *msg):Posts the “msg” to the mailbox. This function have to block until the “msg” is really posted.
- err_t sys_mbox_trypost(sys_mbox_t *mbox, void *msg):Try to post the “msg” to the mailbox. Returns ERR_MEM if this one is full, else, ERR_OK if the “msg” is posted.
- u32_t sys_arch_mbox_fetch(sys_mbox_t *mbox, void **msg, u32_t timeout):Blocks the thread until a message arrives in the mailbox, but does not block the thread longer than “timeout” milliseconds (similar to the sys_arch_sem_wait() function). If “timeout” is 0, the thread should be blocked until a message arrives. The “msg” argument is a result parameter that is set by the function (i.e., by doing “*msg =ptr”). The “msg” parameter maybe NULL to indicate that the message should be dropped.
??The return values are the same as for the sys_arch_sem_wait() function:Number of milliseconds spent waiting or SYS_ARCH_TIMEOUT if there was a timeout.
??Note that a function with a similar name, sys_mbox_fetch(), is implemented by LwIP . - u32_t sys_arch_mbox_tryfetch(sys_mbox_t *mbox, void **msg):This is similar to sys_arch_mbox_fetch, however if a message is not present in the mailbox, it immediately returns with the code SYS_MBOX_EMPTY. On success 0 is returned.
??To allow for efficient implementations, this can be defined as a
function-like macro in sys_arch.h instead of a normal function. For example, a naive implementation could be:
#define sys_arch_mbox_tryfetch(mbox,msg)
sys_arch_mbox_fetch(mbox,msg,1)
although this would introduce unnecessary delays. - int sys_mbox_valid(sys_mbox_t *mbox):Returns 1 if the mailbox is valid, 0 if it is not valid.
??When using pointers, a simple way is to check the pointer for != NULL.
??When directly using OS structures, implementing this may be more complex.
??This may also be a define, in which case the function is not prototyped. - void sys_mbox_set_invalid(sys_mbox_t *mbox):Invalidate a mailbox so that sys_mbox_valid() returns 0.
??ATTENTION: This does NOT mean that the mailbox shall be deallocated:sys_mbox_free() is always called before calling this function!
??This may also be a define, in which case the function is not prototyped.
??If threads are supported by the underlying operating system and if such functionality is needed in LwIP , the following function will have to be implemented as well:
- sys_thread_t sys_thread_new(char *name, void (* thread)(void *arg), void *arg, int stacksize, int prio):Starts a new thread named “name” with priority “prio” that will begin its execution in the function “thread()”. The “arg” argument will be passed as an argument to the thread() function. The stack size to used for this thread is the “stacksize” parameter. The id of the new thread is returned. Both the id and the priority are system dependent.
??When LwIP is used from more than one context (e.g. from multiple threads OR from main-loop and from interrupts), the SYS_LIGHTWEIGHT_PROT protection SHOULD be enabled!
- sys_prot_t sys_arch_protect(void):This optional function does a “fast” critical region protection and returns the previous protection level. This function is only called during very short critical regions. An embedded system which supports ISR-based drivers might want to implement this function by disabling interrupts. Task-based systems might want to implement this by using a mutex or disabling tasking. This function should support recursive calls from the same task or interrupt. In other words, sys_arch_protect() could be called while already protected. In that case the return value indicates that it is already protected.
??sys_arch_protect() is only required if your port is supporting an operating system. - void sys_arch_unprotect(sys_prot_t pval):This optional function does a “fast” set of critical region protection to the value specified by pval. See the documentation for sys_arch_protect() for more information. This function is only required if your port is supporting an operating system.
For some configurations, you also need:
- u32_t sys_now(void):This optional function returns the current time in milliseconds (don’t care for wraparound, this is only used for time diffs).
??Not implementing this function means you cannot use some modules (e.g. TCP timestamps, internal timeouts for NO_SYS==1).
Be careful with using mem_malloc() in sys_arch. When malloc() refers to mem_malloc() you can run into a circular function call problem. In mem.c mem_init() tries to allcate a semaphore using mem_malloc, which of course can’t be performed when sys_arch uses mem_malloc.
cc.h
通常做法為建立一個名為cc.h的文件,在其中定義以下類型及宏值:
??Architecture environment, some compiler specific, some environment specific (probably should move env stuff to sys_arch.h.)定義一些編譯器特定的數據類型和對其方式。
(1)Typedefs for the types used by LwIP -
u8_t, s8_t, u16_t, s16_t, u32_t, s32_t, mem_ptr_t
(2)Compiler hints for packing LwIP 's structures
- PACK_STRUCT_FIELD(x)
- PACK_STRUCT_STRUCT
- PACK_STRUCT_BEGIN
- PACK_STRUCT_END
(3)Platform specific diagnostic output
- LwIP _PLATFORM_DIAG(x) - non-fatal, print a message.
- LwIP _PLATFORM_ASSERT(x) - fatal, print message and abandon execution.
- Portability defines for printf formatters:
U16_F, S16_F, X16_F, U32_F, S32_F, X32_F, SZT_F
(4)“lightweight” synchronization mechanisms
- SYS_ARCH_DECL_PROTECT(x) - declare a protection state variable.
- SYS_ARCH_PROTECT(x) - enter protection mode.
- SYS_ARCH_UNPROTECT(x) - leave protection mode.
(5)If the compiler does not provide memset() this file must include a definition of it, or include a file which defines it.如果編譯系統中沒有包含 memset(),則需要自己包含該函數
(6)This file must either include a system-local errno.h which defines the standard nix error codes, or it should #define LwIP _PROVIDE_ERRNO to make LwIP /arch.h define the codes which are used throughout.該文件還必須包含本地系統的 errno.h 文件(該文件包含了標準nix錯誤碼),或者可以定義宏值#define LwIP _PROVIDE_ERRNO(直接在 LwIP opts.h中定義即可)來使用 LwIP 自己的這個頭文件。
??示例文件如下(系統為FreeRTOS時):
perf.h
??Architecture specific performance measurement.架構特定的性能測量。沒搞明白這句啥意思!這是 LwIP 的作者測試用的?
Measurement calls made throughout LwIP , these can be defined to nothing.
- PERF_START - start measuring something.
- PERF_STOP(x) - stop measuring something, and record the result.
??通常做法為建立一個名為perf.h的文件,在其中定義以上類型及宏值,但是這兩個宏值具體干啥用還沒搞清楚!示例文件如下:
/** Copyright (c) 2001-2003 Swedish Institute of Computer Science.* All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met:** 1. Redistributions of source code must retain the above copyright notice,* this list of conditions and the following disclaimer.* 2. Redistributions in binary form must reproduce the above copyright notice,* this list of conditions and the following disclaimer in the documentation* and/or other materials provided with the distribution.* 3. The name of the author may not be used to endorse or promote products* derived from this software without specific prior written permission. ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE.** This file is part of the LwIP TCP/IP stack.* * Author: Adam Dunkels <adam@sics.se>**/ #ifndef __PERF_H__ #define __PERF_H__#define PERF_START /* null definition */ #define PERF_STOP(x) /* null definition */#endif /* __PERF_H__ */sys_arch.h
該文件主要是針對上面sys_arch.c的配套頭文件,里面有各種函數的聲明。
(1)Arch dependent types for the following objects:sys_sem_t, sys_mbox_t, sys_thread_t, And, optionally:sys_prot_t需要定義以上這些類型(sys_prot_t是可選的)
(2)Defines to set vars of sys_mbox_t and sys_sem_t to NULL.將以下兩個宏值定位NULL
- SYS_MBOX_NULL NULL
- SYS_SEM_NULL NULL
??示例文件如下(系統為FreeRTOS時):
/** Copyright (c) 2001-2003 Swedish Institute of Computer Science.* All rights reserved.** Redistribution and use in source and binary forms, with or without modification,* are permitted provided that the following conditions are met:** 1. Redistributions of source code must retain the above copyright notice,* this list of conditions and the following disclaimer.* 2. Redistributions in binary form must reproduce the above copyright notice,* this list of conditions and the following disclaimer in the documentation* and/or other materials provided with the distribution.* 3. The name of the author may not be used to endorse or promote products* derived from this software without specific prior written permission.** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY* OF SUCH DAMAGE.** This file is part of the LwIP TCP/IP stack.** Author: Adam Dunkels <adam@sics.se>**/ #ifndef __SYS_RTXC_H__ #define __SYS_RTXC_H__#include "FreeRTOS.h" #include "task.h" #include "queue.h" #include "semphr.h"#define SYS_MBOX_NULL (xQueueHandle)0 #define SYS_SEM_NULL (xSemaphoreHandle)0 #define SYS_DEFAULT_THREAD_STACK_DEPTH configMINIMAL_STACK_SIZEtypedef xSemaphoreHandle sys_sem_t; typedef xSemaphoreHandle sys_mutex_t; typedef xQueueHandle sys_mbox_t; typedef xTaskHandle sys_thread_t;typedef struct _sys_arch_state_t {// Task creation data.char cTaskName[configMAX_TASK_NAME_LEN];unsigned short nStackDepth;unsigned short nTaskCount; } sys_arch_state_t;//extern sys_arch_state_t s_sys_arch_state;//void sys_set_default_state(); //void sys_set_state(signed char *pTaskName, unsigned short nStackSize);/* Message queue constants. */ #define archMESG_QUEUE_LENGTH ( 6 ) #endif /* __SYS_RTXC_H__ */其他文件
例如cpu.hWindows下需要的bpstruct.h和epstruct.h
總結
最終需要在sys_arch中的文件如下圖:
總結
以上是生活随笔為你收集整理的LwIP 之三 操作系统隔离接口 sys_arch的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LwIP 之二 网络接口 netif(e
- 下一篇: FreeRTOS 之 在Cortex-M