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

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

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

If aDfc is TRUE, the callbackoccurs in the context of the timer DFC, otherwise it occurs in the timer ISR.Again(aTime)This sets a timer for aTime ticks from its last expiry time. This is usedto implement periodic timers that are immune to delays in processingthe timer callbacks. The callback occurs in the same context as theprevious one.Summary of nanokernel timer control block:FieldDescriptioniNext, iPrevLink pointers for linking the timer into timer queues.iPtrArgument passed to callback function when timer completes.iFunctionPointer to timer expiry handler function.iTriggerTimeNumber of the tick at which timer is due to expire.iCompleteInDfcBoolean flag – TRUE means run timer expiry handler in DFC,FALSE means run it in ISR.iStateIndicates which queue the timer is currently linked into, ifany, and whether the timer is currently being moved.Summary of nanokernel timer queue control block:FieldDescriptioniTickQ[32]32 pairs of linked lists, one pair correspondingto each of the next 32 ticks.

One of the pairholds timers to be completed in the tick ISRand the other holds timers to be completed inthe timer DFC.iPresentBit mask corresponding to iTickQ[32]. Bit nis set if and only if iTickQ[n] isnon-empty – that is at least one of the twolinked lists is non-empty.TIMERSField199DescriptioniMsCountThe number of the next tick.iHoldingQQueue of timers that expire more than 32 ticksin the future, ordered by time at which timerswere queued.iOrderedQQueue of timers that expire more than 32 ticksin the future, ordered by expiry time.iCompletedQQueue of timers that have expired and arewaiting to have their handlers called back inthe timer DFC.iDfcDFC used to transfer timers between queuesand to call back handlers for timers requiringDFC callback.iTransferringCancelledBoolean flag set if the timer that is currentlybeing transferred from iHoldingQ toiOrderedQ is canceled.

Cleared when a newtimer is removed from iHoldingQ for transferto iOrderedQ.iCriticalCancelledBoolean flag set if the timer on the orderedqueue that is currently being inspected during asort is canceled. Cleared when the sort steps onto a new timer.iDebugFnOnly used for testing/debugging.iDebugPtrOnly used for testing/debugging.iTickPeriodThe period of the nanokernel timer tick inmicroseconds.iRoundingSpare entry for use by the ASSP/variant codeinvolved in generating the tick interrupt.Figure 5.4 gives an approximate overview of the nanokernel timer andshows how it fits with the Symbian OS tick timer, which I will cover inthe next section.

To the left of the figure, you can see the control block ofthe nanokernel timer, which has pointers to the final timer queues (timersdue to expire in less than 32 ticks) and pointers to the holding queue and200EDCBAF 0 1KERNEL SERVICES23459 8 76Check every16 msNew timer set>32 ms awayCheck every1 msQueue DFC ifmove neeeded>32 ms awayNano Timer Control BlockiHoldingQISR NTimer 5DFC NTimer 11DFC NTimer 12iOrderedQISR NTimer 4DFC NTimer 10ISR NTimer 3New timer set<32 ms awayiOrderedQ is kept in time order>0iMsCount<32 ms awayPresentTime...4, 3, 2, 1, 00 1 0 1 0 163, 62, 61 ...0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1iTickQ[32]iCompletedQFinal Timer QueuesiDFCTimeiTransferringCancelled0/1iCriticalCancelled0/1<32 ms awayDFC ISRbased based0ISR NTimer 2DFC NTimer 8iDebugFnDFC NTimer 9DFC NTimer 7ISR NTimer 1IMsCount++mod 32iDebugPtrDFC NTimer 4iTickPeriodDFC NTimer 5DFC NTimer 6Timercompleted31iRoundingAn NTimer isscheduled for thenext Tick timereventDFC queued tocall timer backDFC for queuetransfer andcallbackDFC NTimer 1DFC NTimer 2DFC NTimer 3Start DFCSymbian OS Tick Timer Control BlockDrain Holding queue, moving entried>32 ms ahead to time orderedqueue, and entries <32 ms to FinalTimer queuesiNext, iPrevSymbian Timer 1Symbian Timer 2Symbian Timer 3iLastDeltaiLastTicksiRtcDrain head of Ordered queue to finalqueues, until entries >32 ms aheadiTickPeriodiTicksPerSecondiNominalTickPeriodiInTickDrain Completed queue, executingTimer callback for eachiRoundingiPrevRoundingiLastMsA new Tick Timer isrequestediMsTickPeriodEnd DFCiTickDfciMsTimerSome Callbacks willbe used to implementTick TimersTick TimersNTimer callbackKEYData pointerCallback schedules Symbian OSTimer DFCSymbian OS Timer DFCEnd CallbackDrain TTickQ, calling the callbacksExecution flowMovementElaborationReschedule next NTimer for nextTick Timer eventEnd DFCFigure 5.4 Nanokernel timersordered queue, for timers that are further in the future.

You can also seehow Symbian OS tick timers interact with nanokernel timers – the head ofa doubly linked list of ‘‘SymbianTimers’’ (actually TTickLink objects)is used to schedule a nanokernel timer for the next tick timer event.TIMERS201The figure also shows how DFCs drain the nanokernel timer queues,with some of the callbacks being used to schedule Symbian OS ticktimers – which I’ll discuss next.5.5.2 Symbian OS tick timersTick timers are general-purpose interval timers that are used where thereis no need for high resolution or great accuracy. They correspond to thetiming functions available to user-side code on EKA1. We represent atick timer using a TTickLink object, which I will describe in detaillater in this section. We keep active TTickLink objects on a doublylinked queue in order of expiry time. This queue is contained in a singleTTickQ object instance, along with other global state related to SymbianOS timers.

Adding TTickLinks to this queue is an O(N) operation sowe use a mutex, TTickQ::Mutex, to protect the queue.The tick queue operates according to a notional ‘‘Symbian OS nominaltick’’ which has a period of 15.625 ms (64 Hz frequency) – that is, thebehavior is the same as that which would be obtained by using a 64 Hzperiodic tick interrupt. In fact there is no such periodic tick – insteada single NTimer is used to trigger expiry of TTickLink timers. It isalways set to expire either when the first TTickLink should expire or in65536 Symbian OS ticks (1024 seconds), whichever is the sooner. Thelimit is imposed to ensure that differences calculated in microsecondsnever overflow a 32-bit signed quantity.

When the NTimer expires, itactivates a DFC that runs in the Symbian OS timer thread (TimerThread).This DFC dequeues and calls handlers for any TTickLink timers thathave expired, and then requeues the NTimer for the next TTickLinktimer expiry. The timer mutex is acquired at the beginning of the DFCand released at the end, so the mutex is held while the expiry handlersare called.Under this system, adding a new TTickLink to the queue willin general mean that we need to requeue the NTimer if the newtimer expires earlier than the previous earliest timer. The exceptionto this rule is if the TTickLink is added from another TTickLinkexpiry handler; in this case the main DFC routine will requeue theNTimer after all TTickLink expiry handlers for this tick have beencalled.

We use the TTickQ::iInTick flag to indicate that the DFCis in progress; it is set by the DFC after acquiring the timer mutex,so the code to add a TTickLink (which also runs with the timermutex held) will see it set if and only if called from the tick DFCitself.We’ve seen that the usual NTimer resolution is 1 ms, which meansthat a period of 15.625 ms cannot be generated exactly. And, of course,the NTimer resolution may not be 1 ms for manufacturer/device-specificreasons.

Hence the TTickLink timer queue uses a ‘‘pulse swallowing’’202KERNEL SERVICEStype algorithm – it sets up the NTimer to generate intervals that are amultiple of 1 ms, such that the average period of the Symbian OS tickis 15.625 ms. For example, if a periodic TTickLink were active witha period of 1 nominal Symbian OS tick, the NTimer would actuallytrigger at either 15 ms or 16 ms intervals with five out of every eightintervals being 16 ms and the other three out of eight being 15 ms. Thisworks by calculating the required NTimer interval in microseconds andaccumulating the error incurred in rounding to the period of NTimer.The error is taken into account on the next calculation.

In addition,we use the zero-drift mode of NTimer, where the interval is timedrelative to the last timer expiry. In fact the Symbian OS timers are allcalculated relative to the last such expiry. A count of nominal ticksis maintained to support the User::TickCount() function and asimilar count is maintained to serve as universal time. These countsare updated at the beginning of the DFC that services the TTickQ.The nanokernel tick count at which the NTimer triggered is savedand the tick count and RTC count are incremented by the number ofnominal ticks elapsed between this and the previous NTimer expiry.To obtain the current universal time in microseconds since 00:00:0001-01-0AD (standard Symbian OS time storage format), we use thefollowing formula:iRtc*iNominalTickPeriod + (NTickCount()-iLastMs-1)*NTimer periodwhere NTickCount() is the current NTimer tick count and the otherfields are defined in the tables below.

The extra −1 in the second termis due to the fact that NTickCount() is incremented immediately afterdetermining which timers to complete. This scheme allows the systemtime to be obtained to a 1 ms resolution (or whatever the resolution ofNTimer is on a particular platform).Summary of fields in TTickLink:FieldDescriptioniNext, iPrev Link pointers used to attach this object to the systemtick timer queue (TTickQ).iDeltaNumber of OS ticks between the expiry of this timerand the expiry of the following one (pointed to byiNext).

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

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

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

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