Главная » Просмотр файлов » Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU

Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (779891), страница 50

Файл №779891 Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (Symbian Books) 50 страницаWiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (779891) страница 502018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 50)

They are called with interrupts enabled and with the kernellock count equal to 1; this guarantees that they will not be re-entered orpreempted, either by another IDFC or by a thread.Most interrupts do not need further processing after the ISR has run. Forexample, the system tick ISR runs every millisecond but, unless a timerexpires on this particular tick, no IDFCs need to run and no reschedule isrequired.

In this common case, to save the time taken to run the scheduler(lines 17–36 in the code sample ARM IRQ postamble, as opposed toline 38) we use a flag, known as the DFC pending flag, to indicate thatone or more IDFCs have been added to the pending queue. The interruptpostamble only needs to call the scheduler if this flag is set. The flag isreset when all pending IDFCs have been processed.We use a similar flag, the reschedule needed flag, to indicate thatchanges to the ready list have occurred that may require a new threadto be scheduled. After IDFCs have been run, we will only select a newthread to run if this flag is set; the flag is cleared as part of the reschedule.There are two places where the scheduler, and hence IDFCs, may run.The first is during the interrupt postamble (line 29 in the code sampleARM IRQ postamble) and the second is at the point where a threadreleases the kernel lock.In the first place, IDFCs will run if they were added by any of the ISRsthat ran during interrupt processing.

A new thread will then be selectedto run if any of these IDFCs causes a thread with a priority greater than orequal to that of the interrupted thread to become ready.228INTERRUPTS AND EXCEPTIONSIn the second place, IDFCs will run if they have been added by thethread that held the kernel lock or by ISRs that ran while the kernel lockwas held. A new thread may then be selected for three different reasons:1.If any thread with a priority greater than or equal to that of theinterrupted thread is made ready (either by the IDFCs or by the threadthat held the kernel lock)2.If the thread that held the kernel lock removes itself from the readylist3.If thread priorities are changed by the thread that held the kernellock.Figure 6.4 illustrates the processing of an IDFC in the case where thekernel was originally locked and where no thread switch is requiredfollowing the IDFC.timeIDFCIDFC QueuedSchedulerHardwareInterruptNo thread switchrequiredISRKernel lockreleasedThreadFigure 6.4 IDFC processing6.3.2.3 DFCsAs I will explain in Section 6.3.2.4, IDFCs must be short and there arerestrictions on which kernel services they may use.

For these reasonsIDFCs are rarely used directly except by RTOS personality layers. Instead,ISRs generally use Deferred Function Calls (known as DFCs) when theywant to schedule a thread or perform other tasks not possible from withinthe ISR itself. DFCs make use of IDFCs in their implementation, so ISRsindirectly use IDFCs whenever they use DFCs.A DFC is an object that specifies a function to be called in a particularkernel thread.

DFCs are added to DFC queues. Exactly one kernel thread isassociated with each DFC queue, but not all kernel threads are associatedwith a DFC queue.INTERRUPTS229DFCs have priorities that are between 0 and 7 inclusive. Within anygiven DFC queue, the associated kernel thread schedules DFCs cooperatively. It removes the highest priority DFC from the queue and callsits function. When the function returns, the kernel thread processes thenext highest priority DFC; it processes DFCs with the same priority inthe order that they were added to the queue. Once there are no DFCsremaining on the queue, the kernel thread blocks until another DFC isadded to the queue.

Each DFC must run to completion before any otherson the same queue can run. However, since a different kernel threadservices each DFC queue, a DFC running in a higher priority thread maypreempt a DFC running in a lower priority thread.A DFC may be queued from any context – from an ISR, IDFC or thread.However, the kernel handles these contexts a little differently. If an ISRqueues a DFC, then the kernel adds it to the IDFC pending queue. (Thisis possible because IDFCs and DFCs are objects of the same type.) Then,when the scheduler runs, the nanokernel transfers the DFC to its final(DFC) queue and, if necessary, makes the corresponding kernel threadready.

Essentially, the DFC makes use of an IDFC with a callback functionsupplied by the kernel, which transfers the DFC to its final queue. Thistwo-stage process is necessary because a DFC runs in a kernel thread andISRs are not allowed to signal threads; however IDFCs are. Of course, if anIDFC or a thread queues a DFC, this two-stage procedure is not necessary;instead the kernel adds the DFC is directly to its final (DFC) queue.Figure 6.5 illustrates the processing of a DFC queued by an ISR in thecase where the kernel is unlocked when the interrupt occurs and wherethe DFC thread has higher priority than the interrupted thread.timeDFC runs inThread 2Thread 2DFCcompletesDFC first runsas IDFCIDFCDFCQueuedSchedulerISRHardwareInterruptThread 2made readyThread 1resumesKernel notlockedThread 1Figure 6.5DFC processing6.3.2.4 Kernel services in ISRs, IDFCs and DFCsAs I said earlier, to minimize interrupt latency we keep interrupts enabledmost of the time – the only exceptions being a small number of short230INTERRUPTS AND EXCEPTIONSsections of code.

Because of this, most operating system data structuresmight be in an inconsistent state during an ISR. This means that, duringISR processing, we can make no assumptions about the state of any ofthe following:• The thread ready list• Nanokernel threads• Fast mutexes and fast semaphores• DFC queues• Virtual memory mappings for most memory areas accessible fromuser mode.ISRs cannot manipulate any Symbian OS thread or wait object, since thesystem lock fast mutex must be held while doing that. Nor can an ISRaccess user memory, such as the stacks and heaps of a user-mode thread.In fact, the only services available to ISRs are:• Queuing IDFCs and DFCs• Queuing and canceling nanokernel timers• Enabling and disabling interrupts.Earlier, I said that IDFCs would only run after an ISR if the kernelwere unlocked at the time the interrupt is serviced.

This means that allnanokernel objects will be in a consistent state when IDFCs run, and soIDFCs can do a lot more than ISRs. They can:• Make nanokernel threads ready• Manipulate DFC final queues• Signal fast semaphores• Perform all operations available to ISRs.However IDFCs may not block waiting for another thread to run. This isbecause IDFCs run with the kernel locked, which means that the kernelcannot reschedule. Since waiting on a fast semaphore or fast mutexis effectively blocking, IDFCs cannot do this either. And to take thisargument to its conclusion, the prohibition on the use of fast mutexes inIDFCs also means that they may not perform any operations on SymbianOS threads or wait objects, since these are protected by the system lockfast mutex.Similarly, the address space of a non-running user process is onlyguaranteed to be consistent when the system lock is held.

Since it is notINTERRUPTS231known which process is currently running when an IDFC runs, it maynot access any user memory. Another reason for this prohibition is thatexceptions are not tolerated during IDFCs.Note that IDFCs run with preemption disabled, so they should be keptas short as possible.DFCs run in the context of a kernel thread.

In principle, this could bea bare nanokernel thread (NThread) but in practice, with the possibleexception of code running in an RTOS personality layer, DFCs run ina Symbian OS kernel thread (DThread). This means that the full rangeof kernel services is available to DFCs, including but not limited tothe following:• Waiting on or signaling either nanokernel or Symbian OS wait objects• Allocating or freeing memory on the kernel heap• Accessing user memory• Completing Symbian OS asynchronous requests (TRequestStatus).6.3.2.5 Round-robin schedulingThe kernel schedules threads with equal priorities in a round-robinfashion.

That is, each thread executes for a certain amount of time (itstimeslice) and then the kernel schedules the next thread in cyclic orderwith the same priority. We implement this using the iTime field in thenanothread control block – this counts the number of nanokernel timerticks remaining in the thread’s time slice. The kernel decrements iTimeon each nanokernel tick provided this field was initially positive. If iTimebecomes zero, the kernel sets the reschedule needed flag, which causesthe scheduler to run at the next opportunity.

This is the only occasionwhere an interrupt triggers a reschedule directly rather than via an IDFC.6.3.3 Using interrupts6.3.3.1 The interrupt APIsDevice drivers and extensions gain access to interrupts via a genericinterrupt management API, which I will describe later. The base porterimplements this API in the ASSP module, if there is one, or in the variant,if there is not.

In systems with an ASSP, parts of the implementationmay remain in the variant – typically those parts dealing with interruptsources outside the ASSP and that make use of a second-level dispatcher. However, the public functions themselves will be implementedin the ASSP.The interrupt management API is encapsulated in a static class, Interrupt, defined as follows:232INTERRUPTS AND EXCEPTIONStypedef void (*TIsr)(TAny*);class Interrupt{public:static TInt Bind(TInt aId, TIsr aIsr, TAny* aPtr);static TInt Unbind(TInt aId);static TInt Enable(TInt aId);static TInt Disable(TInt aId);static TInt Clear(TInt aId);static TInt SetPriority(TInt aId, TInt aPriority);};The interrupt management API uses a 32-bit integer identifier to specifythe interrupt source that is referred to.

The mapping between interruptsources and numeric identifiers is usually defined in a public header fileexported from the ASSP module. A second public header file, exportedfrom the variant, defines identifiers for interrupt sources external tothe ASSP.Next I shall describe each interrupt management method in turn.TInt Interrupt::Bind(TInt aId, TIsr aIsr, TAny* aPtr);This method associates an ISR with the interrupt source whose numericidentifier is specified by parameter aId. Parameter aIsr specifies theinterrupt service routine. Following a successful return from Interrupt::Bind(), interrupts from the specified source cause functionaIsr() to be called.

The aPtr parameter is passed to aIsr as anargument. This will typically be a pointer to some data required by theISR – for example the ‘‘physical channel’’ object for an interrupt in aphysical device driver.Interrupt::Bind() returns an error code if the specified interruptidentifier is invalid or if the requested interrupt source has alreadybeen bound.TInt Interrupt::Unbind(TInt aId);This method disables interrupts from the specified interrupt source andthen removes any ISR that is currently bound to it.

Характеристики

Тип файла
PDF-файл
Размер
6,63 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6367
Авторов
на СтудИзбе
309
Средний доход
с одного платного файла
Обучение Подробнее