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

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

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

Alternatively, it may ignore the exception,in which case it is offered to the next handler.User-side exception handlersIf no kernel event handlers can deal with the exception, the last possibilityfor handling it is a user-side exception handler. If the exception occurredin user mode and a user-side exception handler is registered, then wemodify the user-mode stack pointer and the return address from theexception to cause the current thread to run the user-side exceptionhandler as soon as it returns to user mode.If none of the previous methods are able to handle the exception, thecurrent thread is terminated with the ‘‘KERN–EXEC 3’’ panic code.6.4.2 Uses of exceptions6.4.2.1 Trapping invalid pointersSince Symbian OS does not support demand-paged virtual memory, anyoccurrence of a page fault must come from the use of an invalid memorypointer.

In most cases this will result in the kernel terminating the threadthat caused the page fault. Exceptions to this rule are:242INTERRUPTS AND EXCEPTIONS• If the invalid pointer was passed in by other code, such as a serverreceiving a pointer from its client and using that pointer in an RMessagePtr2::Read() or Write() call. In this case the exception iscaught within the kernel and an error code is returned to the server• If the thread has set up a user-side exception handler to catchpage faults.6.4.2.2 Coprocessor lazy context switchIA-32 and some ARM CPUs have floating point coprocessors that containa substantial amount of extra register state.

For example, the ARM vectorfloating point (VFP) processor contains 32 words of additional registers.Naturally, these additional registers need to be part of the state of eachthread so that more than one thread may use the coprocessor and eachthread will behave as if it had exclusive access.In practice, most threads do not use the coprocessor and so we wantto avoid paying the penalty of saving the coprocessor registers on everycontext switch. We do this by using ‘‘lazy’’ context switching. Thisrelies on there being a simple method of disabling the coprocessor; anyoperation on a disabled coprocessor results in an exception.

Both theIA-32 and ARM processor have such mechanisms:• IA-32 has a flag (TS) in the CR0 control register which, when set, causesany FPU operations to raise a ‘‘Device Not Available’’ exception. TheCR0 register is saved and restored as part of the normal thread context• The ARM VFP has an enable bit in its FPEXC control register. When theenable bit is clear, any VFP operation causes an undefined instructionexception. The FPEXC register is saved and restored as part of thenormal thread context• Architecture 6 and some architecture 5 ARM devices also have acoprocessor access register (CAR).

This register selectively enablesand disables each of the 15 possible ARM coprocessors (other thanCP15 which is always accessible). This allows the lazy context switchscheme to be used for all ARM coprocessors. If it exists, the CAR issaved and restored as part of the normal thread context.The lazy context-switching scheme works as follows. Each thread startsoff with no access to the coprocessor; that is, the coprocessor is disabledwhenever the thread runs.When a thread, HAIKU, attempts to use the coprocessor, an exceptionis raised. The exception handler checks if another thread, SONNET,currently has access to (‘‘owns’’) the coprocessor. If so, the handlersaves the current coprocessor state in SONNET’s control block and thenmodifies SONNET’s saved state so that the coprocessor will be disabledABORTS, TRAPS AND FAULTS243when SONNET next runs.

If there wasn’t a thread using the coprocessor,then the handler doesn’t need to save the state of the coprocessor.Then coprocessor access is enabled for the current thread, HAIKU,and the handler restores the coprocessor state from HAIKU’s controlblock – this is the state at the point when HAIKU last used the coprocessor.If this is the first time HAIKU has used the coprocessor, a standard initialcoprocessor state will have been stored in HAIKU’s control block whenHAIKU was created, and this standard state will be loaded into thecoprocessor. HAIKU now owns the coprocessor.The exception handler then returns, and the processor retries the original coprocessor instruction. This now succeeds because the coprocessoris enabled.If a thread terminates while owning the coprocessor, the kernel marksthe coprocessor as no longer being owned by any thread.This scheme ensures that the kernel only saves and restores thecoprocessor state when necessary.

If, as is quite likely, the coprocessoris only used by one thread, then its state is never saved. (Of course, ifthe coprocessor were to be placed into a low power mode that causedit to lose state, the state would have to be saved before doing so andrestored when the coprocessor was placed back into normal operatingmode. However at the time of writing no coprocessors have such alow-power mode.)6.4.2.3 DebuggingExceptions are used in debugging to set software breakpoints.

The debugger replaces the instruction at which the user wants to place a breakpointwith an undefined instruction. When control flow reaches that point,an exception occurs and the debugger gains control. Registers may beinspected and/or modified and then execution resumes after the undefinedinstruction. The debugger must somehow arrange for the replaced instruction to be executed, possibly by software emulation, before resuming execution. There is more on this subject in Chapter 14, Kernel-Side Debug.6.4.3 APIs for exceptionsIn the following sections, I will describe the kernel exception APIs thatare available to device drivers and extensions.6.4.3.1 The XTRAP macroThis is a macro wrapper over the TExcTrap handlers that I described inSection 6.4.1.3. The macro is used as follows:XTRAP(result, handler, statements);XTRAPD(result, handler, statements);244INTERRUPTS AND EXCEPTIONSThe specified statements are executed under a TExcTrap harness.The parameter result is an integer variable that will contain the valueKErrNone after execution if no exception occurred.

The macro XTRAPDdeclares the variable result whereas XTRAP uses a preexisting variable.The parameter handler is a pointer to a function with signature:void (*TExcTrapHandler)(TExcTrap* aX, DThread* aThread, TAny* aContext);This function is called if an exception occurs during the execution ofstatements.If XT_DEFAULT is specified as the handler parameter, a defaulthandler is used that returns an error code KErrBadDescriptor on anyexception.Parameter aX points to the TExcTrap harness which caught theexception, aThread points to the control block of the executing threadand aContext points to a processor dependent structure which containsthe values of all the processor registers at the point where the exceptionoccurred.

In fact this is simply the processor state information saved inthe exception preamble by the nanokernel. The ARM version of this is:struct TArmExcInfo{TArmReg iCpsr;TIntiExcCode;TArmReg iR13Svc;// supervisor stack pointerTArmReg iR4;TArmReg iR5;TArmReg iR6;TArmReg iR7;TArmReg iR8;TArmReg iR9;TArmReg iR10;TArmReg iR11;TArmReg iR14Svc;// supervisor mode LRTArmReg iFaultAddress; // value of MMU FARTArmReg iFaultStatus;// value of MMU FSRTArmReg iSpsrSvc;// supervisor mode SPSRTArmReg iR13; // user stack pointerTArmReg iR14; // user mode LRTArmReg iR0;TArmReg iR1;TArmReg iR2;TArmReg iR3;TArmReg iR12;TArmReg iR15; // address of aborted instruction};If the exception can be handled, the function should call:aX->Exception(errorcode);ABORTS, TRAPS AND FAULTS245This will cause the execution of the XTRAP macro to terminate immediately without completing execution of statements; the resultsvariable is set to the errorcode passed in to the call.If the exception cannot be handled, the function should just return.The other exception handling strategies described in Section 6.4.1.3 willthen be attempted.The XTRAP macro is used to catch exceptions occurring in supervisormode, typically in conjunction with the kumemget() and kumemput()functions (described in Section 5.2.1.5) to access user-side memory fromplaces where it would not be acceptable to terminate the current threadon an exception.

Examples of these are code that runs with a fast mutexheld or inside a thread critical section. The XTRAP macro is the only wayto catch exceptions that occur with a fast mutex held.6.4.3.2 Kernel event handlersXTRAP handlers can only catch supervisor-mode exceptions in onethread, and are normally used to catch exceptions within a singlefunction call. We use kernel event handlers when we want to catchexceptions occurring in multiple threads or in user-mode over extendedperiods of time. We implement kernel event handlers using the classDKernelEventHandler, the public interface of which follows:class DKernelEventHandler : public DBase{public:// Values used to select where to insert the handler in the queueenum TAddPolicy{EAppend,};enum TReturnCode{// Run next handler if set,// ignore remaining handlers if clearedERunNext = 1,// Available for EEventUserTrace only.// Ignore trace statement if set.ETraceHandled = 0x40000000,// Available for hardware exceptions only.// Do not panic thread if set.EExcHandled = 0x80000000,};/** Pointer to C callback function called when an event occurs.aEvent designates what event is dispatched.a1 and a2 are event-specific.aPrivateData is specified when the handler is created, typically apointer to the event handler.The function is always called in thread critical section.

*/246INTERRUPTS AND EXCEPTIONStypedef TUint (*TCallback)(TKernelEvent aEvent, TAny* a1, TAny* a2,TAny* aP);public:// external interfaceIMPORT_C static TBool DebugSupportEnabled();IMPORT_C DKernelEventHandler(TCallback aCb, TAny* aP);IMPORT_C TInt Add(TAddPolicy aPolicy = EAppend);IMPORT_C TInt Close();inline TBool IsQueued() const;};If you are writing an extension or a device driver and you want touse a kernel event handler, follow these steps.

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

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

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

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