Главная » Просмотр файлов » 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), страница 49

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

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

I will talk about this more later.Of these, the first is fundamental to the entire operation of the system.This is the way in which external events cause the appropriate kernel-sideand user-side tasks to run.6.3.1.4 PostambleThe postamble runs after the dispatcher returns, which it does when it hasserviced all pending interrupts.

The goal of the postamble is to restore theprocessor’s state and permit the interrupted program to resume. Howeverbefore this, it may need to schedule another thread to run.224INTERRUPTS AND EXCEPTIONSThe postamble performs the following actions:1.It checks what code was running when the interrupt was triggered.If that code was not running as part of a thread, then the postamblereturns from the interrupt immediately. This covers the case in whichone interrupt occurs during servicing of another. It also covers anycases in which the processor is in a transitional state (a thread stack isnot active).

Such a state can occur in ARM processors just after an abortor undefined instruction exception. The processor enters mode abt ormode und and the active stack is a shared exception stack rather thana thread stack. This stack is only used briefly to save registers beforeswitching to mode svc. However because a non-thread related stackis in use, rescheduling cannot occur.

Lines 1, 4, 6 and 7 in the codesample ARM IRQ postamble check for this – if the interrupted modeis neither usr nor svc, we return from the interrupt immediately.ARM IRQ postamble123456789101112131415161718192021222324252627282930313233343536MRSLDRADDANDLDRCMPCMPNECMPEQBNEMOVMSRLDRADDMOVCMPBEQSTRMSRLDMDBSTMFDLDMDBSTMFDSTMFDMOVMOVMSRADDMSRBLLDMFDADDMOVMOVMSRMSRLDMDBR0, SPSRR1, TheSchedulerR12, SP, #24R2, R0, #0x1FR3, [R1, #iKernCSLocked]R2, #0x10R2, #0x13R3, #0IrqExit0R2, #0xD2CPSR, R2R2, [R1, #iRescheduleNeededFlag]R3, R3, #1LR, #0x13R2, #0IrqExit0R3, [R1, #iKernCSLocked]CPSR, LRR12!, {R1-R3}SP!, {R1-R3}R12!, {R1-R3}SP!, {R1-R3}SP!, {R0, LR}R2, #0x13LR, #0x92CPSR, LRSP, R12, #24CPSR, R2RescheduleSP!, {R1, LR}SP, SP, #24R12, SPR2, #0xD2CPSR, R2SPSR, R1R12, {R0-R3, R12, PC}INTERRUPTS37 IrqExit0:38LDMFD225SP!, {R0-R3, R12, PC}2. It checks if preemption is disabled – if this is the case, it returns fromthe interrupt immediately (lines 5 and 8).3.

It checks if an IDFC (see Section 6.3.2.2) or a reschedule is pending;if not, it returns from the interrupt immediately. Lines 10, 11, 12, 15,16 are responsible for this. Note that the postamble must perform thischeck with all interrupts disabled, not just those at the same hardwarepriority as the one just serviced.

If this were not the case, a higherpriority interrupt, such as an FIQ, could run and queue an IDFCjust after the current interrupt (IRQ) performed the check. The FIQpostamble would not run the IDFC since it interrupted mode irq, andthe IRQ postamble would not run the IDFC since it already decidedthere was no IDFC pending. The IDFC would then be subject to anunpredictable delay, until either another interrupt occurred or thecurrent thread performed some action that resulted in rescheduling.4.

It disables preemption and re-enables interrupts (lines 13, 14, 17, 18).It transfers all saved state from the interrupt stack to the supervisorstack of the interrupted thread (lines 3 and 19–28). It calls the scheduler. This runs any pending IDFCs and then performs a context switchif one is needed. The call to the scheduler returns when the interrupted thread is next scheduled.

Internally, the scheduler performscontext switches by switching stacks. Any thread that is not currentlyexecuting has a call to the scheduler at the top of its call stack.5. It restores the interrupted thread state from the supervisor stack andreturns from the interrupt (lines 30–36).6.3.2 Interaction with schedulingThe processing required for an external event generally splits into anumber of stages with different response time requirements. For example,consider a PPP connection over a serial port. The UART receives dataand stores it in its internal FIFO.

When the FIFO is half-full, the UARTraises an interrupt, which must be serviced before the FIFO becomescompletely full to avoid data loss.So, the first stage of processing is to move the data from the UART’sreceive FIFO to an internal memory buffer – and the deadline for thisis the time taken to receive half a FIFO of data. Let’s say that this is 8characters at 115,200 bps, which gives us a time of 694 µs.The second stage of processing is to perform PPP framing, verify theframe check sequence, transition the PPP state machine and transmit anyacknowledgment required. The deadline for this is determined by the timethat the peer PPP entity will wait before timing out the acknowledgment.This will be much longer than the first stage deadline, so second-stage226INTERRUPTS AND EXCEPTIONSprocessing can occur at lower priority than the receive interrupt, in athread.

In this way, further receive interrupts will preempt the secondstage processing of earlier frames.In a similar way, the PPP thread must preempt other activities withlonger deadlines and long-running activities. The receive interrupt signalsthe PPP thread that data is available, which triggers the preemption.

Ingeneral terms, processing for events with short deadlines should preemptprocessing for events with longer deadlines. This is done by using threadswith differing priorities for the different types of event, with the most timecritical events being handled directly by ISRs.6.3.2.1 The kernel lockIn previous sections, it has become clear that there must be a methodby which interrupts can cause the appropriate threads to run so that anevent can be processed. In this way, the response can occur in stages,with the most urgent part being handled by the ISR itself and less urgentparts being handled by threads of decreasing priority.To ensure that response deadlines are met, the time between a hardware interrupt being signaled and the ISR running must be bounded (thatis, it must have a maximum latency) and we want this latency to beas short as possible.

This translates into a requirement that interrupts beenabled all the time apart from in sections of code whose execution timeis bounded and as short as possible. To satisfy this requirement, mostcode, whether kernel- or user-side, executes with interrupts enabled. Thisincludes code that manipulates global structures such as the thread readylist. To prevent such code from being re-entered and corrupting the globalstructure, a preemption lock (iKernCSLocked, usually known as thekernel lock) is employed.The kernel lock is a simple counter that is normally zero. Sections ofcode that need to protect themselves against rescheduling increment thekernel lock at the beginning of the critical section and decrement it atthe end.

Then, when an interrupt occurs, the kernel will only attempt areschedule if the kernel lock was zero at the time of the interrupt. This canbe seen in step 2 of the interrupt postamble described in Section 6.3.1.4,and in lines 3 and 8 of the code sample ARM IRQ postamble.Of course this method can only work if the ISR itself does not invokeany of these critical sections of code.

We disable rescheduling in certaincode sequences because they need to atomically manipulate structuressuch as the thread ready list. Disabling rescheduling prevents a secondthread from running and modifying these structures while the first threadis still halfway through its modification. However disabling reschedulingdoes not disable interrupts, so an ISR that modified the thread ready listdirectly would still conflict with threads modifying it.

Therefore ISRs maynot add a thread to the ready list. In fact, they may not use any OSservices other than those listed in Section 6.3.1.3.INTERRUPTS2276.3.2.2 IDFCsInterrupts cause the scheduling of a thread by means of an ImmediateDeferred Function Call (IDFC). IDFCs are objects that specify a functionthat will be called after the ISR, as soon as the system is in a suitable state.We call them ‘‘immediate’’ because they normally run before returningfrom the interrupt, not later on, in a kernel thread. The exception to thisis if the kernel was locked when the interrupt occurred, in which caseIDFCs are run immediately after the kernel is unlocked.It works like this.

First the ISR adds an IDFC to the IDFC pending queue, which is always accessed with interrupts disabled. Whenthe scheduler next runs, it calls the function associated with the IDFCdirectly. (The function is not called by a thread.) This is how the stateof the kernel lock governs when IDFCs are called. If an interrupt occurswhen the kernel lock count is nonzero, the ISR runs but nothing elsehappens. If an interrupt occurs when the kernel lock count is zero, theISR runs and afterwards, if IDFCs have been queued, the scheduler iscalled and it runs the IDFCs. The IDFCs may add one or more threadsto the ready list, after which the scheduler may select a new threadto run.IDFCs are called in the same order in which they were originallyqueued.

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

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

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

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