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

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

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

The exception modeshave a single, small, shared stack between them – they do not have a perthread stack. The preamble must switch the processor into mode svc, sothat the exception handler can run in the context of the thread causing theexception, and the kernel can reschedule correctly.

The ARM exceptionpreamble proceeds as follows:1. Saves a small number of registers on the mode abt or mode undstack, including the address of the instruction that caused theexception2. Checks the saved PSR to ensure that the exception occurred in eithermode usr or mode svc. If not, the exception must have occurredeither in an ISR or during the exception preamble itself. In eithercase, this is a fatal error, and a kernel fault will be raised3. Enables IRQ interrupts.

IDFCs queued by IRQs or FIQs will not runnow, because the processor mode is abt or und, which is equivalentto the kernel lock being held (see Section 6.3.1.4)238INTERRUPTS AND EXCEPTIONS4.Checks if the kernel lock is currently held. If so, this is a fatal error,as code holding the kernel lock is not allowed to fault. If not, locksthe kernel and switches to mode svc. The current thread’s supervisormode stack is now active5.Checks that there is enough space remaining on the supervisor stackto store the full processor state.

If not, the supervisor stack hasoverflowed, which is a fatal error6.Transfers the registers saved on the mode abt or mode und stack tothe mode svc stack. Saves the rest of the processor registers on themode svc stack. Also saves the fault address register and the faultstatus register, which give additional information about the cause ofan MMU-detected exception such as a page fault7.Unlocks the kernel. Any deferred IDFCs and/or reschedules willrun now8.Calls the exception handler registered for the current nanothread,passing a pointer to the saved processor state on the stack.Handling exceptions on IA-32 processorsOn IA-32 processors, exceptions automatically switch to privilege level 0and the current thread’s supervisor stack becomes active, as I described inSection 6.2.2.

The return address from the exception is either the addressof the aborted instruction for an abort or the address of the followinginstruction for a trap, and the processor automatically saves this on thesupervisor stack along with the flag’s register. If the exception occurredin user mode, the processor also automatically saves the user-side stackpointer. The processor does not disable interrupts (because Symbian OSuses trap gates for exceptions) and the preamble can be preempted atany time. This is not a problem because the current thread’s supervisorstack is active throughout the preamble.

The IA-32 exception preambleproceeds as follows:1.If the exception does not push an error code onto the stack (seeSection 6.2.2), the preamble pushes a zero error code2.Saves all processor integer registers and segment selectors on thesupervisor stack. Also pushes the fault address register; this is onlyvalid for page faults but is nevertheless stored for all exceptions3.Checks the interrupt nest count. If it is greater than −1, then theexception occurred during an ISR, which we treat as a fatal error4.Checks if the kernel lock is currently held. If so, this is a fatal error5.Calls the exception handler registered for the current nanothread,passing a pointer to the saved processor state on the stack.ABORTS, TRAPS AND FAULTS2396.4.1.2 PostambleIf the exception was not fatal, then the postamble runs after the nanothread’s exception handler has returned.

The postamble restores all ofthe processor state from the stack, with the exception of the supervisorstack pointer. The processor will restore this automatically by poppingthe saved state when it returns from the exception. The last instructionof the exception postamble will be a ‘‘return from exception’’ instruction, which restores both the program counter and the status register.Execution then returns to the saved program counter value, which meansthat either the processor retries the aborted instruction or it executesthe instruction after the faulting one. It is worth pointing out that theexception handler may previously have modified the saved state bychanging values in the stack, but these modifications only take effect atthis point.6.4.1.3 Symbian OS exception handlerAll Symbian OS threads are provided with a standard exception handler.This implements several strategies for dealing with the exception.

Thesestrategies are tried one after another until either one of them successfullyhandles the exception or they all fail, in which case the thread causingthe exception is terminated.Magic handlerThe first strategy is the so-called ‘‘magic’’ handler. This works slightlydifferently on the ARM and IA-32 versions of the kernel.On ARM, the exception handler checks for a data abort occurring inmode svc where the address of the aborted instruction is one of a shortlist known to the exception handler.

If these conditions are all satisfied,the magic handler is used; this simply resumes execution at the instructionafter the aborted instruction with the Z (zero) flag set, and R12 set to thedata address that caused the data abort.On IA-32, the exception handler checks for an exception occurringat CPL = 0, that is, in supervisor mode, and checks the iMagicExcHandler field of the current thread. If the latter is non-null and theexception occurred at CPL = 0, the Symbian OS exception handler callsthe function pointed to by iMagicExcHandler, passing a pointer to theprocessor state saved by the exception preamble. If this function returnszero, it means that the magic handler has handled the exception andmodified the saved processor state appropriately (typically the saved EIPwill be modified), so the Symbian OS exception handler simply returnsand execution resumes according to the modified saved state. If thereturn value is nonzero, the Symbian OS exception handler proceeds tothe TExcTrap strategy.240INTERRUPTS AND EXCEPTIONSThe magic handler is used to safely handle3 exceptions that arecaused by dereferencing user-supplied pointers in frequently used kernelfunctions, such as DThread::RequestComplete(), which is usedto complete Symbian OS asynchronous requests.

The advantage of themagic handler is that it is very fast to set up – in fact on ARM it requiresno setup at all and on IA-32 we only need to write a single pointer tothe current thread control block. Fast set up is important, since the setupoverhead is incurred in the normal case where no exception occurs.

Thedisadvantage is that it can only be used in functions written in assemblerbecause the magic handler must inspect and manipulate saved processorregister values directly. In C++, we don’t know what register the compileris going to use for what.TExcTrap handlersThe second strategy is the use of the TExcTrap class. This supports thecatching of exceptions in C++ code and allows the handler to be writtenin C++. The price of this additional flexibility is that it takes longerto set up the TExcTrap before executing the code that might causean exception.A thread wishing to catch exceptions occurring in a section of codeallocates a TExcTrap structure on its supervisor stack and initializes itwith a pointer to the function that is to be called if an exception occurs.The initialization function saves the processor registers in the TExcTrapstructure and attaches this structure to the thread.

If an exception occurs,the Symbian OS exception handler sees that the thread has installed aTExcTrap handler and calls the nominated handler function, passingpointers to the TExcTrap, the current thread and to the processorcontext saved by the nanokernel exception preamble. The handler canthen inspect the saved context and any additional information passed inthe TExcTrap, and decide to either retry the aborted instruction or toreturn an error code. In the latter case the processor registers saved in theTExcTrap are restored to allow C++ execution to continue correctly.Coprocessor fault handlerThe two strategies for handling exceptions that I have just described allowthe catching of exceptions that occur with a fast mutex held.

If neither ofthese methods successfully handles the exception, and the current threadholds a fast mutex, then the kernel will treat this as a fatal error. It doesthis because all of the exception-handling schemes that I am about todescribe make use of fast mutexes.The next check the kernel makes is for coprocessor faults. On ARM,the check is for ‘‘undefined instruction’’ exceptions on coprocessorinstructions; on IA-32 the check is for ‘‘device not available’’ exceptions.3If it’s good enough for Star Trek, it’s good enough for me.ABORTS, TRAPS AND FAULTS241If the exception is of this type, and there is a context switch handlerregistered for the coprocessor involved, the registered handler is called.(We don’t need to make the check on IA-32 as there is always a handlerfor the IA-32 FPU.) The return value indicates whether the exception hasbeen handled successfully.If the exception was handled successfully, the kernel restores theprocessor state and then either retries the coprocessor instruction orcontinues execution with the next instruction, depending on the reasonfor the exception.

Coprocessor handlers can be used for two differentpurposes. One is to save and restore the coprocessor state as necessaryto enable multiple threads to use the coprocessor. When a new threadattempts to use the coprocessor, an exception results; the exceptionhandler saves the coprocessor state for the previous thread and restoresthe state for the current thread, and the instruction is then retried so itcan execute correctly in the context of the current thread. This scheme isused for the IA-32 FPU and ARM VFP and I will describe it in more detailin Section 6.4.2.2.

The other purpose for a coprocessor handler is toemulate a coprocessor that is not actually present. In this case executionwill resume after the coprocessor instruction.Kernel event handlersThe exception is then offered to all the kernel event handlers. The kernelcalls each handler, passing a pointer to the processor context saved bythe nanokernel exception preamble. The handler has the option to handlethe exception, possibly modifying the saved processor context, and thenresume the aborted program.

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

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

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

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