OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [rtos/] [ecos-2.0/] [packages/] [hal/] [synth/] [arch/] [v2_0/] [src/] [synth_intr.c] - Blame information for rev 174

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 27 unneback
//=============================================================================
2
//
3
//      synth_intr.c
4
//
5
//      Interrupt and clock code for the Linux synthetic target.
6
//
7
//=============================================================================
8
//####ECOSGPLCOPYRIGHTBEGIN####
9
// -------------------------------------------
10
// This file is part of eCos, the Embedded Configurable Operating System.
11
// Copyright (C) 2002 Bart Veer
12
// Copyright (C) 1998, 1999, 2000, 2001, 2002 Red Hat, Inc.
13
//
14
// eCos is free software; you can redistribute it and/or modify it under
15
// the terms of the GNU General Public License as published by the Free
16
// Software Foundation; either version 2 or (at your option) any later version.
17
//
18
// eCos is distributed in the hope that it will be useful, but WITHOUT ANY
19
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
20
// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
21
// for more details.
22
//
23
// You should have received a copy of the GNU General Public License along
24
// with eCos; if not, write to the Free Software Foundation, Inc.,
25
// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
26
//
27
// As a special exception, if other files instantiate templates or use macros
28
// or inline functions from this file, or you compile this file and link it
29
// with other works to produce a work based on this file, this file does not
30
// by itself cause the resulting work to be covered by the GNU General Public
31
// License. However the source code for this file must still be made available
32
// in accordance with section (3) of the GNU General Public License.
33
//
34
// This exception does not invalidate any other reasons why a work based on
35
// this file might be covered by the GNU General Public License.
36
//
37
// Alternative licenses for eCos may be arranged by contacting Red Hat, Inc.
38
// at http://sources.redhat.com/ecos/ecos-license/
39
// -------------------------------------------
40
//####ECOSGPLCOPYRIGHTEND####
41
//=============================================================================
42
//#####DESCRIPTIONBEGIN####
43
//
44
// Author(s):    bartv
45
// Contributors: bartv, asl
46
// Date:         2001-03-30
47
// Purpose:      Implement the interrupt subsystem for the synthetic target
48
//####DESCRIPTIONEND####
49
//=============================================================================
50
 
51
// sigprocmask handling.
52
//
53
// In the synthetic target interrupts and exceptions are based around
54
// POSIX sighandlers. When the clock ticks a SIGALRM signal is raised.
55
// When the I/O auxiliary wants to raise some other interrupt, it
56
// sends a SIGIO signal. When an exception occurs this results in
57
// signals like SIGILL and SIGSEGV. This implies an implementation
58
// where the VSR is the signal handler. Disabling interrupts would
59
// then mean using sigprocmask() to block certain signals, and
60
// enabling interrupts means unblocking those signals.
61
//
62
// However there are a few problems. One of these is performance: some
63
// bits of the system such as buffered tracing make very extensive use
64
// of enabling and disabling interrupts, so making a sigprocmask
65
// system call each time adds a lot of overhead. More seriously, there
66
// is a subtle discrepancy between POSIX signal handling and hardware
67
// interrupts. Signal handlers are expected to return, and then the
68
// system automatically passes control back to the foreground thread.
69
// In the process, the sigprocmask is manipulated before invoking the
70
// signal handler and restored afterwards. Interrupt handlers are
71
// different: it is quite likely that an interrupt results in another
72
// eCos thread being activated, so the signal handler does not
73
// actually return until the interrupted thread gets another chance to
74
// run. 
75
//
76
// The second problem can be addressed by making the sigprocmask part
77
// of the thread state, saving and restoring it as part of a context
78
// switch (c.f. siglongjmp()). This matches quite nicely onto typical
79
// real hardware, where there might be a flag inside some control
80
// register that controls whether or not interrupts are enabled.
81
// However this adds more system calls to context switch overhead.
82
//
83
// The alternative approach is to implement interrupt enabling and
84
// disabling in software. The sigprocmask is manipulated only once,
85
// during initialization, such that certain signals are allowed
86
// through and others are blocked. When a signal is raised the signal
87
// handler will always be invoked, but it will decide in software
88
// whether or not the signal should be processed immediately. This
89
// alternative approach does not correspond particularly well with
90
// real hardware: effectively the VSR is always allowed to run.
91
// However for typical applications this will not really matter, and
92
// the performance gains outweigh the discrepancy.
93
//
94
// Nested interrupts and interrupt priorities can be implemented in
95
// software, specifically by manipulating the current mask of blocked
96
// interrupts. This is not currently implemented.
97
//
98
// At first glance it might seem that an interrupt stack could be
99
// implemented trivially using sigaltstack. This does not quite work:
100
// signal handlers do not always return immediately, so the system
101
// does not get a chance to clean up the signal handling stack. A
102
// separate interrupt stack is possible but would have to be
103
// implemented here, in software, e.g. by having the signal handler
104
// invoke the VSR on that stack. Unfortunately the system may have
105
// pushed quite a lot of state on to the current stack already when
106
// raising the signal, so things could get messy.
107
 
108
// ----------------------------------------------------------------------------
109
#include <pkgconf/hal.h>
110
#include <pkgconf/hal_synth.h>
111
 
112
// There are various dependencies on the kernel, e.g. how exceptions
113
// should be handled.
114
#include <pkgconf/system.h>
115
#ifdef CYGPKG_KERNEL
116
# include <pkgconf/kernel.h>
117
#endif
118
 
119
#include <cyg/infra/cyg_type.h>         // base types
120
#include <cyg/infra/diag.h>
121
#include <cyg/hal/hal_arch.h>
122
#include <cyg/hal/hal_intr.h>
123
#include <cyg/hal/hal_io.h>
124
#include <cyg/infra/cyg_ass.h>          // Assertions are safe in the synthetic target
125
 
126
#include "synth_protocol.h"
127
 
128
// ----------------------------------------------------------------------------
129
// Statics.
130
 
131
// Are interrupts currently enabled?
132
volatile cyg_bool_t hal_interrupts_enabled = false;
133
 
134
// These flags are updated by the signal handler when a signal comes in
135
// and interrupts are disabled.
136
static volatile cyg_bool_t  synth_sigio_pending         = false;
137
static volatile cyg_bool_t  synth_sigalrm_pending       = false;
138
 
139
// The current VSR, to be invoked by the signal handler. This allows
140
// application code to install an alternative VSR, without that VSR
141
// having to check for interrupts being disabled and updating the
142
// pending flags. Effectively, the VSR is only invoked when interrupts
143
// are enabled.
144
static void (*synth_VSR)(void)                          = (void (*)(void)) 0;
145
 
146
// The current ISR status and mask registers, or rather software
147
// emulations thereof. These are not static since application-specific
148
// VSRs may want to examine/manipulate these. They are also not
149
// exported in any header file, forcing people writing such VSRs to
150
// know what they are doing.
151
volatile cyg_uint32 synth_pending_isrs      = 0;
152
volatile cyg_uint32 synth_masked_isrs       = 0xFFFFFFFF;
153
 
154
// The vector of interrupt handlers.
155
typedef struct synth_isr_handler {
156
    cyg_ISR_t*          isr;
157
    CYG_ADDRWORD        data;
158
    CYG_ADDRESS         obj;
159
    cyg_priority_t      pri;
160
} synth_isr_handler;
161
static synth_isr_handler synth_isr_handlers[CYGNUM_HAL_ISR_COUNT];
162
 
163
static void  synth_alrm_sighandler(int);
164
static void  synth_io_sighandler(int);
165
 
166
// ----------------------------------------------------------------------------
167
// Basic ISR and VSR handling.
168
 
169
// The default ISR handler. The system should never receive an interrupt it
170
// does not know how to handle.
171
static cyg_uint32
172
synth_default_isr(cyg_vector_t vector, cyg_addrword_t data)
173
{
174
    CYG_UNUSED_PARAM(cyg_vector_t, vector);
175
    CYG_UNUSED_PARAM(cyg_addrword_t, data);
176
    CYG_FAIL("Default isr handler should never get invoked");
177
    return CYG_ISR_HANDLED;
178
}
179
 
180
// The VSR is invoked
181
//  1) directly by a SIGALRM or SIGIO signal handler, if interrupts
182
//     were enabled.
183
//  2) indirectly by hal_enable_interrupts(), if a signal happened
184
//     while interrupts were disabled. hal_enable_interrupts()
185
//     will have re-invoked the signal handler.
186
//
187
// On entry interrupts are disabled, and there should be one or more
188
// pending ISRs which are not masked off.
189
//
190
// The implementation is as per the HAL specification, where
191
// applicable.
192
 
193
static void
194
synth_default_vsr(void)
195
{
196
    int         isr_vector;
197
    cyg_uint32  isr_result;
198
 
199
    CYG_ASSERT(!hal_interrupts_enabled, "VSRs should only be invoked when interrupts are disabled");
200
    CYG_ASSERT(0 != (synth_pending_isrs & ~synth_masked_isrs), "VSRs should only be invoked when an interrupt is pending");
201
 
202
    // No need to save the cpu state. Either we are in a signal
203
    // handler and the system has done that for us, or we are called
204
    // synchronously via enable_interrupts.
205
 
206
    // Increment the kernel scheduler lock, if the kernel is present.
207
    // This prevents context switching while interrupt handling is in
208
    // progress.
209
#ifdef CYGFUN_HAL_COMMON_KERNEL_SUPPORT
210
    cyg_scheduler_lock();
211
#endif
212
 
213
    // Do not switch to an interrupt stack - functionality is not
214
    // implemented
215
 
216
    // Do not allow nested interrupts - functionality is not
217
    // implemented.
218
 
219
    // Decode the actual external interrupt being delivered. This is
220
    // determined from the pending and masked variables. Only one isr
221
    // source can be handled here, since interrupt_end must be invoked
222
    // with details of that interrupt. Multiple pending interrupts
223
    // will be handled by a recursive call 
224
    HAL_LSBIT_INDEX(isr_vector, (synth_pending_isrs & ~synth_masked_isrs));
225
    CYG_ASSERT((CYGNUM_HAL_ISR_MIN <= isr_vector) && (isr_vector <= CYGNUM_HAL_ISR_MAX), "ISR vector must be valid");
226
 
227
    isr_result = (*synth_isr_handlers[isr_vector].isr)(isr_vector, synth_isr_handlers[isr_vector].data);
228
 
229
    // Do not switch back from the interrupt stack, there isn't one.
230
 
231
    // Interrupts were not enabled before, so they must be enabled
232
    // now. This may result in a recursive invocation if other IRQs
233
    // are still pending. The ISR should have either acknowledged or
234
    // masked the current interrupt source, to prevent a recursive
235
    // call for the current interrupt.
236
    hal_enable_interrupts();
237
 
238
    // Now call interrupt_end() with the result of the isr and the
239
    // ISR's object This may return straightaway, or it may result in
240
    // a context switch to another thread. In the latter case, when
241
    // the current thread is reactivated we end up back here. The
242
    // third argument should be a pointer to the saved state, but that
243
    // is only relevant for thread-aware debugging which is not yet
244
    // supported by the synthetic target.
245
    {
246
        extern void interrupt_end(cyg_uint32, CYG_ADDRESS, HAL_SavedRegisters*);
247
        interrupt_end(isr_result, synth_isr_handlers[isr_vector].obj, (HAL_SavedRegisters*) 0);
248
    }
249
 
250
    // Restore machine state and return to the interrupted thread.
251
    // That requires no effort here.
252
}
253
 
254
// Enabling interrupts. If a SIGALRM or SIGIO arrived at an inconvenient
255
// time, e.g. when already interacting with the auxiliary, then these
256
// will have been left pending and must be serviced now. Next, enabling
257
// interrupts means checking the interrupt pending and mask registers
258
// and seeing if the VSR should be invoked.
259
void
260
hal_enable_interrupts(void)
261
{
262
    hal_interrupts_enabled = true;
263
    if (synth_sigalrm_pending) {
264
        synth_sigalrm_pending = false;
265
        synth_alrm_sighandler(CYG_HAL_SYS_SIGALRM);
266
    }
267
    if (synth_sigio_pending) {
268
        synth_sigio_pending = false;
269
        synth_io_sighandler(CYG_HAL_SYS_SIGIO);
270
    }
271
 
272
    // The interrupt mask "register" may have been modified while
273
    // interrupts were disabled. If there are pending interrupts,
274
    // invoke the VSR. The VSR must be invoked with interrupts
275
    // disabled, and will return with interrupts enabled.
276
    // An alternative implementation that might be more accurate
277
    // is to raise a signal, e.g. SIGUSR1. That way all interrupts
278
    // come in via the system's signal handling mechanism, and
279
    // it might be possible to do something useful with saved contexts
280
    // etc., facilitating thread-aware debugging.
281
    if (0 != (synth_pending_isrs & ~synth_masked_isrs)) {
282
        hal_interrupts_enabled = false;
283
        (*synth_VSR)();
284
        CYG_ASSERT( hal_interrupts_enabled, "Interrupts should still be enabled on return from the VSR");
285
    }
286
}
287
 
288
// ----------------------------------------------------------------------------
289
// Other interrupt-related routines. Mostly these just involve
290
// updating some of the statics, but they may be called while
291
// interrupts are still enabled so care has to be taken.
292
 
293
cyg_bool_t
294
hal_interrupt_in_use(cyg_vector_t vec)
295
{
296
    CYG_ASSERT( (CYGNUM_HAL_ISR_MIN <= vec) && (vec <= CYGNUM_HAL_ISR_MAX), "Can only attach to valid ISR vectors");
297
    return synth_default_isr != synth_isr_handlers[vec].isr;
298
}
299
 
300
void
301
hal_interrupt_attach(cyg_vector_t vec, cyg_ISR_t* isr, CYG_ADDRWORD data, CYG_ADDRESS obj)
302
{
303
    CYG_ASSERT( (CYGNUM_HAL_ISR_MIN <= vec) && (vec <= CYGNUM_HAL_ISR_MAX), "Can only attach to valid ISR vectors");
304
    CYG_CHECK_FUNC_PTR( isr, "A valid ISR must be supplied");
305
    // The object cannot be validated, it may be NULL if chained
306
    // interrupts are enabled.
307
    CYG_ASSERT( synth_isr_handlers[vec].isr == &synth_default_isr, "Only one ISR can be attached to a vector at the HAL level");
308
    CYG_ASSERT( (false == hal_interrupts_enabled) || (0 != (synth_masked_isrs & (0x01 << vec))), "ISRs should only be attached when it is safe");
309
 
310
    // The priority will have been installed shortly before this call.
311
    synth_isr_handlers[vec].isr     = isr;
312
    synth_isr_handlers[vec].data    = data;
313
    synth_isr_handlers[vec].obj     = obj;
314
}
315
 
316
void
317
hal_interrupt_detach(cyg_vector_t vec, cyg_ISR_t* isr)
318
{
319
    CYG_ASSERT( (CYGNUM_HAL_ISR_MIN <= vec) && (vec <= CYGNUM_HAL_ISR_MAX), "Can only detach from valid ISR vectors");
320
    CYG_CHECK_FUNC_PTR( isr, "A valid ISR must be supplied");
321
    CYG_ASSERT( isr != &synth_default_isr, "An ISR must be attached before it can be detached");
322
    CYG_ASSERT( (false == hal_interrupts_enabled) || (0 != (synth_masked_isrs & (0x01 << vec))), "ISRs should only be detached when it is safe");
323
 
324
    // The Cyg_Interrupt destructor does an unconditional detach, even if the
325
    // isr is not currently attached.
326
    if (isr == synth_isr_handlers[vec].isr) {
327
        synth_isr_handlers[vec].isr     = &synth_default_isr;
328
        synth_isr_handlers[vec].data    = (CYG_ADDRWORD) 0;
329
        synth_isr_handlers[vec].obj     = (CYG_ADDRESS) 0;
330
    }
331
 
332
    // The priority is not updated here. This should be ok, if another
333
    // isr is attached then the appropriate priority will be installed
334
    // first.
335
}
336
 
337
void (*hal_vsr_get(cyg_vector_t vec))(void)
338
{
339
    CYG_ASSERT( (CYGNUM_HAL_VSR_MIN <= vec) && (vec <= CYGNUM_HAL_VSR_MAX), "Can only get valid VSR vectors");
340
    return synth_VSR;
341
}
342
 
343
void
344
hal_vsr_set(cyg_vector_t vec, void (*new_vsr)(void), void (**old_vsrp)(void))
345
{
346
    cyg_bool_t  old;
347
 
348
    CYG_ASSERT( (CYGNUM_HAL_VSR_MIN <= vec) && (vec <= CYGNUM_HAL_VSR_MAX), "Can only get valid VSR vectors");
349
    CYG_CHECK_FUNC_PTR( new_vsr, "A valid VSR must be supplied");
350
 
351
    // There is a theoretical possibility of two hal_vsr_set calls at
352
    // the same time. The old and new VSRs must be kept in synch.
353
    HAL_DISABLE_INTERRUPTS(old);
354
    if (0 != old_vsrp) {
355
        *old_vsrp = synth_VSR;
356
    }
357
    synth_VSR = new_vsr;
358
    HAL_RESTORE_INTERRUPTS(old);
359
}
360
 
361
void
362
hal_interrupt_mask(cyg_vector_t which)
363
{
364
    CYG_PRECONDITION( !hal_interrupts_enabled, "Interrupts should be disabled on entry to hal_interrupt_mask");
365
    CYG_ASSERT((CYGNUM_HAL_ISR_MIN <= which) && (which <= CYGNUM_HAL_ISR_MAX), "A valid ISR vector must be supplied");
366
    synth_masked_isrs |= (0x01 << which);
367
}
368
 
369
void
370
hal_interrupt_unmask(cyg_vector_t which)
371
{
372
    CYG_PRECONDITION( !hal_interrupts_enabled, "Interrupts should be disabled on entry to hal_interrupt_unmask");
373
    CYG_ASSERT((CYGNUM_HAL_ISR_MIN <= which) && (which <= CYGNUM_HAL_ISR_MAX), "A valid ISR vector must be supplied");
374
    synth_masked_isrs &= ~(0x01 << which);
375
}
376
 
377
void
378
hal_interrupt_acknowledge(cyg_vector_t which)
379
{
380
    cyg_bool_t old;
381
    CYG_ASSERT((CYGNUM_HAL_ISR_MIN <= which) && (which <= CYGNUM_HAL_ISR_MAX), "A valid ISR vector must be supplied");
382
 
383
    // Acknowledging an interrupt means clearing the bit in the
384
    // interrupt pending "register".
385
    // NOTE: does the auxiliary need to keep track of this? Probably
386
    // not, the auxiliary can just raise SIGIO whenever a device wants
387
    // attention. There may be a trade off here between additional
388
    // communication and unnecessary SIGIOs.
389
    HAL_DISABLE_INTERRUPTS(old);
390
    synth_pending_isrs &= ~(0x01 << which);
391
    HAL_RESTORE_INTERRUPTS(old);
392
}
393
 
394
void
395
hal_interrupt_configure(cyg_vector_t which, cyg_bool_t level, cyg_bool_t up)
396
{
397
    CYG_ASSERT((CYGNUM_HAL_ISR_MIN <= which) && (which <= CYGNUM_HAL_ISR_MAX), "A valid ISR vector must be supplied");
398
    // The synthetic target does not currently distinguish between
399
    // level and edge interrupts. Possibly this information will have
400
    // to be passed on to the auxiliary in future.
401
    CYG_UNUSED_PARAM(cyg_vector_t, which);
402
    CYG_UNUSED_PARAM(cyg_bool_t, level);
403
    CYG_UNUSED_PARAM(cyg_bool_t, up);
404
}
405
 
406
void
407
hal_interrupt_set_level(cyg_vector_t which, cyg_priority_t level)
408
{
409
    CYG_ASSERT((CYGNUM_HAL_ISR_MIN <= which) && (which <= CYGNUM_HAL_ISR_MAX), "A valid ISR vector must be supplied");
410
    // The legal values for priorities are not defined at this time.
411
    // Manipulating the interrupt priority level currently has no
412
    // effect. The information is stored anyway, for future use.
413
    synth_isr_handlers[which].pri = level;
414
}
415
 
416
// ----------------------------------------------------------------------------
417
// Exception handling. Typically this involves calling into the kernel,
418
// translating the POSIX signal number into a HAL exception number. In
419
// practice these signals will generally be caught in the debugger and
420
// will not have to be handled by eCos itself.
421
 
422
static void
423
synth_exception_sighandler(int sig)
424
{
425
    CYG_WORD    ecos_exception_number = 0;
426
    cyg_bool_t  old;
427
 
428
    // There is no need to save state, that will have been done by the
429
    // system as part of the signal delivery process.
430
 
431
    // Disable interrupts. Performing e.g. an interaction with the
432
    // auxiliary after a SIGSEGV is dubious.
433
    HAL_DISABLE_INTERRUPTS(old);
434
 
435
    // Now decode the signal and turn it into an eCos exception.
436
    switch(sig) {
437
      case CYG_HAL_SYS_SIGILL:
438
        ecos_exception_number = CYGNUM_HAL_EXCEPTION_ILLEGAL_INSTRUCTION;
439
        break;
440
      case CYG_HAL_SYS_SIGBUS:
441
      case CYG_HAL_SYS_SIGSEGV:
442
        ecos_exception_number = CYGNUM_HAL_EXCEPTION_DATA_ACCESS;
443
        break;
444
      case CYG_HAL_SYS_SIGFPE:
445
        ecos_exception_number = CYGNUM_HAL_EXCEPTION_FPU;
446
        break;
447
      default:
448
        CYG_FAIL("Unknown signal");
449
        break;
450
    }
451
 
452
#ifdef CYGPKG_KERNEL_EXCEPTIONS
453
    // Deliver the signal, usually to the kernel, possibly to the
454
    // common HAL. The second argument should be the current
455
    // savestate, but that is not readily accessible.
456
    cyg_hal_deliver_exception(ecos_exception_number, (CYG_ADDRWORD) 0);
457
 
458
    // It is now necessary to restore the machine state, including
459
    // interrupts. In theory higher level code may have manipulated
460
    // the machine state to prevent any recurrence of the exception.
461
    // In practice the machine state is not readily accessible.
462
    HAL_RESTORE_INTERRUPTS(old);
463
#else
464
    CYG_FAIL("Exception!!!");
465
    for (;;);
466
#endif    
467
}
468
 
469
// ----------------------------------------------------------------------------
470
// The clock support. This can be implemented using the setitimer()
471
// and getitimer() calls. The kernel will install a suitable interrupt
472
// handler for CYGNUM_HAL_INTERRUPT_RTC, but it depends on the HAL
473
// for low-level manipulation of the clock hardware.
474
//
475
// There is a problem with HAL_CLOCK_READ(). The obvious
476
// implementation would use getitimer(), but that has the wrong
477
// behaviour: it is intended for fairly coarse intervals and works in
478
// terms of system clock ticks, as opposed to a fine-grained
479
// implementation that actually examines the system clock. Instead use
480
// gettimeofday().
481
 
482
static struct cyg_hal_sys_timeval synth_clock   = { 0, 0 };
483
 
484
void
485
hal_clock_initialize(cyg_uint32 period)
486
{
487
    struct cyg_hal_sys_itimerval    timer;
488
 
489
    // Needed for hal_clock_read(), if HAL_CLOCK_READ() is used before
490
    // the first clock interrupt.
491
    cyg_hal_sys_gettimeofday(&synth_clock, (struct cyg_hal_sys_timezone*) 0);
492
 
493
    // The synthetic target clock resolution is in microseconds. A typical
494
    // value for the period will be 10000, corresponding to one timer
495
    // interrupt every 10ms. Set up a timer to interrupt in period us,
496
    // and again every period us after that.
497
    CYG_ASSERT( period < 1000000, "Clock interrupts should happen at least once per second");
498
    timer.hal_it_interval.hal_tv_sec    = 0;
499
    timer.hal_it_interval.hal_tv_usec   = period;
500
    timer.hal_it_value.hal_tv_sec       = 0;
501
    timer.hal_it_value.hal_tv_usec      = period;
502
 
503
    if (0 != cyg_hal_sys_setitimer(CYG_HAL_SYS_ITIMER_REAL, &timer, (struct cyg_hal_sys_itimerval*) 0)) {
504
        CYG_FAIL("Failed to initialize the clock itimer");
505
    }
506
}
507
 
508
static void
509
synth_alrm_sighandler(int sig)
510
{
511
    CYG_PRECONDITION((CYG_HAL_SYS_SIGALRM == sig), "Only SIGALRM should be handled here");
512
 
513
    if (!hal_interrupts_enabled) {
514
        synth_sigalrm_pending = true;
515
        return;
516
    }
517
 
518
    // Interrupts were enabled, but must be blocked before any further processing.
519
    hal_interrupts_enabled = false;
520
 
521
    // Update the cached value of the clock for hal_clock_read()
522
    cyg_hal_sys_gettimeofday(&synth_clock, (struct cyg_hal_sys_timezone*) 0);
523
 
524
    // Update the interrupt status "register" to match pending interrupts
525
    // A timer signal means that IRQ 0 needs attention.
526
    synth_pending_isrs |= 0x01;
527
 
528
    // If any of the pending interrupts are not masked, invoke the
529
    // VSR. That will reenable interrupts.
530
    if (0 != (synth_pending_isrs & ~synth_masked_isrs)) {
531
        (*synth_VSR)();
532
    } else {
533
        hal_interrupts_enabled = true;
534
    }
535
 
536
    // The VSR will have invoked interrupt_end() with interrupts
537
    // enabled, and they should still be enabled.
538
    CYG_ASSERT( hal_interrupts_enabled, "Interrupts should still be enabled on return from the VSR");
539
}
540
 
541
// Implementing hal_clock_read(). gettimeofday() in conjunction with
542
// synth_clock gives the time since the last clock tick in
543
// microseconds, the correct unit for the synthetic target.
544
cyg_uint32
545
hal_clock_read(void)
546
{
547
    int elapsed;
548
    struct cyg_hal_sys_timeval  now;
549
    cyg_hal_sys_gettimeofday(&now, (struct cyg_hal_sys_timezone*) 0);
550
 
551
    elapsed = (1000000 * (now.hal_tv_sec - synth_clock.hal_tv_sec)) + (now.hal_tv_usec - synth_clock.hal_tv_usec);
552
    return elapsed;
553
}
554
 
555
// ----------------------------------------------------------------------------
556
// The signal handler for SIGIO. This can also be invoked by
557
// hal_enable_interrupts() to catch up with any signals that arrived
558
// while interrupts were disabled. SIGIO is raised by the auxiliary
559
// when it requires attention, i.e. when one or more of the devices
560
// want to raise an interrupt. Finding out exactly which interrupt(s)
561
// are currently pending in the auxiliary requires communication with
562
// the auxiliary.
563
//
564
// If interrupts are currently disabled then the signal cannot be
565
// handled immediately. In particular SIGIO cannot be handled because
566
// there may already be ongoing communication with the auxiliary.
567
// Instead some volatile flags are used to keep track of which signals
568
// were raised while interrupts were disabled. 
569
//
570
// It might be better to perform the interaction with the auxiliary
571
// as soon as possible, i.e. either in the SIGIO handler or when the
572
// current communication completes. That way the mask of pending
573
// interrupts would remain up to date even when interrupts are
574
// disabled, thus allowing applications to run in polled mode.
575
 
576
// A little utility called when the auxiliary has been asked to exit,
577
// implicitly affecting this application as well. The sole purpose
578
// of this function is to put a suitably-named function on the stack
579
// to make it more obvious from inside gdb what is happening.
580
static void
581
synth_io_handle_shutdown_request_from_auxiliary(void)
582
{
583
    cyg_hal_sys_exit(0);
584
}
585
 
586
static void
587
synth_io_sighandler(int sig)
588
{
589
    CYG_PRECONDITION((CYG_HAL_SYS_SIGIO == sig), "Only SIGIO should be handled here");
590
 
591
    if (!hal_interrupts_enabled) {
592
        synth_sigio_pending = true;
593
        return;
594
    }
595
 
596
    // Interrupts were enabled, but must be blocked before any further processing.
597
    hal_interrupts_enabled = false;
598
 
599
    // Update the interrupt status "register" to match pending interrupts
600
    // Contact the auxiliary to find out what interrupts are currently pending there.
601
    // If there is no auxiliary at present, e.g. because it has just terminated
602
    // and things are generally somewhat messy, ignore it.
603
    //
604
    // This code also deals with the case where the user has requested program
605
    // termination. It would be wrong for the auxiliary to just exit, since the
606
    // application could not distinguish that case from a crash. Instead the
607
    // auxiliary can optionally return an additional byte of data, and if that
608
    // byte actually gets sent then that indicates pending termination.
609
    if (synth_auxiliary_running) {
610
        int             result;
611
        int             actual_len;
612
        unsigned char   dummy[1];
613
        synth_auxiliary_xchgmsg(SYNTH_DEV_AUXILIARY, SYNTH_AUXREQ_GET_IRQPENDING, 0, 0,
614
                                (const unsigned char*) 0, 0,        // The auxiliary does not need any additional data
615
                                &result, dummy, &actual_len, 1);
616
        synth_pending_isrs |= result;
617
        if (actual_len) {
618
            // The auxiliary has been asked to terminate by the user. This
619
            // request has now been passed on to the eCos application.
620
            synth_io_handle_shutdown_request_from_auxiliary();
621
        }
622
    }
623
 
624
    // If any of the pending interrupts are not masked, invoke the VSR
625
    if (0 != (synth_pending_isrs & ~synth_masked_isrs)) {
626
        (*synth_VSR)();
627
    } else {
628
        hal_interrupts_enabled = true;
629
    }
630
 
631
    // The VSR will have invoked interrupt_end() with interrupts
632
    // enabled, and they should still be enabled.
633
    CYG_ASSERT( hal_interrupts_enabled, "Interrupts should still be enabled on return from the VSR");
634
}
635
 
636
// ----------------------------------------------------------------------------
637
// Here we define an action to do in the idle thread. For the
638
// synthetic target it makes no sense to spin eating processor time
639
// that other processes could make use of. Instead we call select. The
640
// itimer will still go off and kick the scheduler back into life,
641
// giving us an escape path from the select. There is one problem: in
642
// some configurations, e.g. when preemption is disabled, the idle
643
// thread must yield continuously rather than blocking.
644
void
645
hal_idle_thread_action(cyg_uint32 loop_count)
646
{
647
#ifndef CYGIMP_HAL_IDLE_THREAD_SPIN
648
    cyg_hal_sys__newselect(0,
649
                           (struct cyg_hal_sys_fd_set*) 0,
650
                           (struct cyg_hal_sys_fd_set*) 0,
651
                           (struct cyg_hal_sys_fd_set*) 0,
652
                           (struct cyg_hal_sys_timeval*) 0);
653
#endif
654
    CYG_UNUSED_PARAM(cyg_uint32, loop_count);
655
}
656
 
657
// ----------------------------------------------------------------------------
658
// The I/O auxiliary.
659
//
660
// I/O happens via an auxiliary process. During startup this code attempts
661
// to locate and execute a program ecosynth which should be installed in
662
// ../libexec/ecosynth relative to some directory on the search path.
663
// Subsequent I/O operations involve interacting with this auxiliary.
664
 
665
#define MAKESTRING1(a) #a
666
#define MAKESTRING2(a) MAKESTRING1(a)
667
#define AUXILIARY       "../libexec/ecos/hal/synth/arch/" MAKESTRING2(CYGPKG_HAL_SYNTH) "/ecosynth"
668
 
669
// Is the auxiliary up and running?
670
cyg_bool    synth_auxiliary_running   = false;
671
 
672
// The pipes to and from the auxiliary.
673
static int  to_aux      = -1;
674
static int  from_aux    = -1;
675
 
676
// Attempt to start up the auxiliary. Note that this happens early on
677
// during system initialization so it is "known" that the world is
678
// still simple, e.g. that no other files have been opened.
679
static void
680
synth_start_auxiliary(void)
681
{
682
#define BUFSIZE 256
683
    char        filename[BUFSIZE];
684
    const char* path = 0;
685
    int         i, j;
686
    cyg_bool    found   = false;
687
    int         to_aux_pipe[2];
688
    int         from_aux_pipe[2];
689
    int         child;
690
    int         aux_version;
691
#if 1
692
    // Check for a command line argument -io. Only run the auxiliary if this
693
    // argument is provided, i.e. default to traditional behaviour.
694
    for (i = 1; i < cyg_hal_sys_argc; i++) {
695
        const char* tmp = cyg_hal_sys_argv[i];
696
        if ('-' == *tmp) {
697
            // Arguments beyond -- are reserved for use by the application,
698
            // and should not be interpreted by the HAL itself or by ecosynth.
699
            if (('-' == tmp[1]) && ('\0' == tmp[2])) {
700
                break;
701
            }
702
            tmp++;
703
            if ('-' == *tmp) {
704
                // Do not distinguish between -io and --io
705
                tmp++;
706
            }
707
            if (('i' == tmp[0]) && ('o' == tmp[1]) && ('\0' == tmp[2])) {
708
                found = 1;
709
                break;
710
            }
711
        }
712
    }
713
    if (!found) {
714
        return;
715
    }
716
#else
717
    // Check for a command line argument -ni or -nio. Always run the
718
    // auxiliary unless this argument is given, i.e. default to full
719
    // I/O support.
720
    for (i = 1; i < cyg_hal_sys_argc; i++) {
721
        const char* tmp = cyg_hal_sys_argv[i];
722
        if ('-' == *tmp) {
723
            if (('-' == tmp[1]) && ('\0' == tmp[2])) {
724
                break;
725
            }
726
            tmp++;
727
            if ('-' == *tmp) {
728
                tmp++;
729
            }
730
            if ('n' == *tmp) {
731
                tmp++;
732
                if ('i' == *tmp) {
733
                    tmp++;
734
                    if ('\0' == *tmp) {
735
                        found = 1;  // -ni or --ni
736
                        break;
737
                    }
738
                    if (('o' == *tmp) && ('\0' == tmp[1])) {
739
                        found = 1;  // -nio or --nio
740
                        break;
741
                    }
742
                }
743
            }
744
        }
745
    }
746
    if (found) {
747
        return;
748
    }
749
#endif
750
 
751
    // The auxiliary must be found relative to the current search path,
752
    // so look for a PATH= environment variable.
753
    for (i = 0; (0 == path) && (0 != cyg_hal_sys_environ[i]); i++) {
754
        const char *var = cyg_hal_sys_environ[i];
755
        if (('P' == var[0]) && ('A' == var[1]) && ('T' == var[2]) && ('H' == var[3]) && ('=' == var[4])) {
756
            path = var + 5;
757
        }
758
    }
759
    if (0 == path) {
760
        // Very unlikely, but just in case.
761
        path = ".:/bin:/usr/bin";
762
    }
763
 
764
    found = 0;
765
    while (!found && ('\0' != *path)) {         // for every entry in the path
766
        char *tmp = AUXILIARY;
767
 
768
        j = 0;
769
 
770
        // As a special case, an empty string in the path corresponds to the
771
        // current directory.
772
        if (':' == *path) {
773
            filename[j++] = '.';
774
            path++;
775
        } else {
776
            while ((j < BUFSIZE) && ('\0' != *path) && (':' != *path)) {
777
                filename[j++] = *path++;
778
            }
779
            // If not at the end of the search path, move on to the next entry.
780
            if ('\0' != *path) {
781
                while ((':' != *path) && ('\0' != *path)) {
782
                    path++;
783
                }
784
                if (':' == *path) {
785
                    path++;
786
                }
787
            }
788
        }
789
        // Now append a directory separator, and then the name of the executable.
790
        if (j < BUFSIZE) {
791
            filename[j++] = '/';
792
        }
793
        while ((j < BUFSIZE) && ('\0' != *tmp)) {
794
            filename[j++] = *tmp++;
795
        }
796
        // If there has been a buffer overflow, skip this entry.
797
        if (j == BUFSIZE) {
798
            filename[BUFSIZE-1] = '\0';
799
            diag_printf("Warning: buffer limit reached while searching PATH for the I/O auxiliary.\n");
800
            diag_printf("       : skipping current entry.\n");
801
        } else {
802
            // filename now contains a possible match for the auxiliary.
803
            filename[j++]    = '\0';
804
            if (0 == cyg_hal_sys_access(filename, CYG_HAL_SYS_X_OK)) {
805
                found = true;
806
            }
807
        }
808
    }
809
#undef BUFSIZE
810
 
811
    if (!found) {
812
        diag_printf("Error: unable to find the I/O auxiliary program on the current search PATH\n");
813
        diag_printf("     : please install the appropriate host-side tools.\n");
814
        cyg_hal_sys_exit(1);
815
    }
816
 
817
    // An apparently valid executable exists (or at the very least it existed...),
818
    // so create the pipes that will be used for communication.
819
    if ((0 != cyg_hal_sys_pipe(to_aux_pipe)) ||
820
        (0 != cyg_hal_sys_pipe(from_aux_pipe))) {
821
        diag_printf("Error: unable to set up pipes for communicating with the I/O auxiliary.\n");
822
        cyg_hal_sys_exit(1);
823
    }
824
 
825
    // Time to fork().
826
    child = cyg_hal_sys_fork();
827
    if (child < 0) {
828
        diag_printf("Error: failed to fork() process for the I/O auxiliary.\n");
829
        cyg_hal_sys_exit(1);
830
    } else if (child == 0) {
831
        cyg_bool    found_dotdot;
832
        // There should not be any problems rearranging the file descriptors as desired...
833
        cyg_bool    unexpected_error = 0;
834
 
835
        // In the child process. Close unwanted file descriptors, then some dup2'ing,
836
        // and execve() the I/O auxiliary. The auxiliary will inherit stdin,
837
        // stdout and stderr from the eCos application, so that functions like
838
        // printf() work as expected. In addition fd 3 will be the pipe from
839
        // the eCos application and fd 4 the pipe to the application. It is possible
840
        // that the eCos application was run from some process other than a shell
841
        // and hence that file descriptors 3 and 4 are already in use, but that is not
842
        // supported. One possible workaround would be to close all file descriptors
843
        // >= 3, another would be to munge the argument vector passing the file
844
        // descriptors actually being used.
845
        unexpected_error |= (0 != cyg_hal_sys_close(to_aux_pipe[1]));
846
        unexpected_error |= (0 != cyg_hal_sys_close(from_aux_pipe[0]));
847
 
848
        if (3 != to_aux_pipe[0]) {
849
            if (3 == from_aux_pipe[1]) {
850
                // Because to_aux_pipe[] was set up first it should have received file descriptors 3 and 4.
851
                diag_printf("Internal error: file descriptors have been allocated in an unusual order.\n");
852
                cyg_hal_sys_exit(1);
853
            } else {
854
                unexpected_error |= (3 != cyg_hal_sys_dup2(to_aux_pipe[0], 3));
855
                unexpected_error |= (0 != cyg_hal_sys_close(to_aux_pipe[0]));
856
            }
857
        }
858
        if (4 != from_aux_pipe[1]) {
859
            unexpected_error |= (4 != cyg_hal_sys_dup2(from_aux_pipe[1], 4));
860
            unexpected_error |= (0 != cyg_hal_sys_close(from_aux_pipe[1]));
861
        }
862
        if (unexpected_error) {
863
            diag_printf("Error: internal error in auxiliary process, failed to manipulate pipes.\n");
864
            cyg_hal_sys_exit(1);
865
        }
866
        // The arguments passed to the auxiliary are mostly those for
867
        // the synthetic target application, except for argv[0] which
868
        // is replaced with the auxiliary's pathname. The latter
869
        // currently holds at least one ../, and cleaning this up is
870
        // useful.
871
        //
872
        // If the argument vector contains -- then that and subsequent
873
        // arguments are not passed to the auxiliary. Instead such
874
        // arguments are reserved for use by the application.
875
        do {
876
            int len;
877
            for (len = 0; '\0' != filename[len]; len++)
878
                ;
879
            found_dotdot = false;
880
            for (i = 0; i < (len - 4); i++) {
881
                if (('/' == filename[i]) && ('.' == filename[i+1]) && ('.' == filename[i+2]) && ('/' == filename[i+3])) {
882
                    j = i + 3;
883
                    for ( --i; (i >= 0) && ('/' != filename[i]); i--) {
884
                        CYG_EMPTY_STATEMENT;
885
                    }
886
                    if (i >= 0) {
887
                        found_dotdot = true;
888
                        do {
889
                            i++; j++;
890
                            filename[i] = filename[j];
891
                        } while ('\0' != filename[i]);
892
                    }
893
                }
894
            }
895
        } while(found_dotdot);
896
 
897
        cyg_hal_sys_argv[0] = filename;
898
 
899
        for (i = 1; i < cyg_hal_sys_argc; i++) {
900
            const char* tmp = cyg_hal_sys_argv[i];
901
            if (('-' == tmp[0]) && ('-' == tmp[1]) && ('\0' == tmp[2])) {
902
                cyg_hal_sys_argv[i] = (const char*) 0;
903
                break;
904
            }
905
        }
906
        cyg_hal_sys_execve(filename, cyg_hal_sys_argv, cyg_hal_sys_environ);
907
 
908
        // An execute error has occurred. Report this here, then exit. The
909
        // parent will detect a close on the pipe without having received
910
        // any data, and it will assume that a suitable diagnostic will have
911
        // been displayed already.
912
        diag_printf("Error: failed to execute the I/O auxiliary.\n");
913
        cyg_hal_sys_exit(1);
914
    } else {
915
        int     rc;
916
        char    buf[1];
917
 
918
        // Still executing the eCos application.
919
        // Do some cleaning-up.
920
        to_aux      = to_aux_pipe[1];
921
        from_aux    = from_aux_pipe[0];
922
        if ((0 != cyg_hal_sys_close(to_aux_pipe[0]))  ||
923
            (0 != cyg_hal_sys_close(from_aux_pipe[1]))) {
924
            diag_printf("Error: internal error in main process, failed to manipulate pipes.\n");
925
            cyg_hal_sys_exit(1);
926
        }
927
 
928
        // It is now a good idea to block until the auxiliary is
929
        // ready, i.e. give it a chance to read in its configuration
930
        // files, load appropriate scripts, pop up windows, ... This
931
        // may take a couple of seconds or so. Once the auxiliary is
932
        // ready it will write a single byte down the pipe. This is
933
        // the only time that the auxiliary will write other than when
934
        // responding to a request.
935
        do {
936
            rc = cyg_hal_sys_read(from_aux, buf, 1);
937
        } while (-CYG_HAL_SYS_EINTR == rc);
938
 
939
        if (1 != rc) {
940
            // The auxiliary has not started up successfully, so exit
941
            // immediately. It should have generated appropriate
942
            // diagnostics.
943
            cyg_hal_sys_exit(1);
944
        }
945
    }
946
 
947
    // At this point the auxiliary is up and running. It should not
948
    // generate any interrupts just yet since none of the devices have
949
    // been initialized. Remember that the auxiliary is now running,
950
    // so that the initialization routines for those devices can
951
    // figure out that they should interact with the auxiliary rather
952
    // than attempt anything manually.
953
    synth_auxiliary_running   = true;
954
 
955
    // Make sure that the auxiliary is the right version.
956
    synth_auxiliary_xchgmsg(SYNTH_DEV_AUXILIARY, SYNTH_AUXREQ_GET_VERSION, 0, 0,
957
                            (const unsigned char*) 0, 0,
958
                            &aux_version, (unsigned char*) 0, (int*) 0, 0);
959
    if (SYNTH_AUXILIARY_PROTOCOL_VERSION != aux_version) {
960
        synth_auxiliary_running = false;
961
        diag_printf("Error: an incorrect version of the I/O auxiliary is installed\n"
962
                    "    Expected version %d, actual version %d\n"
963
                    "    Installed binary is %s\n",
964
                    SYNTH_AUXILIARY_PROTOCOL_VERSION, aux_version, filename);
965
        cyg_hal_sys_exit(1);
966
    }
967
}
968
 
969
// Write a request to the I/O auxiliary, and optionally get back a
970
// reply. The dev_id is 0 for messages intended for the auxiliary
971
// itself, for example a device instantiation or a request for the
972
// current interrupt sate. Otherwise it identifies a specific device.
973
// The request code is specific to the device, and the two optional
974
// arguments are specific to the request.
975
void
976
synth_auxiliary_xchgmsg(int devid, int reqcode, int arg1, int arg2,
977
                        const unsigned char* txdata, int txlen,
978
                        int* result,
979
                        unsigned char* rxdata, int* actual_rxlen, int rxlen)
980
{
981
    unsigned char   request[SYNTH_REQUEST_LENGTH];
982
    unsigned char   reply[SYNTH_REPLY_LENGTH];
983
    int             rc;
984
    int             reply_rxlen;
985
    cyg_bool_t      old_isrstate;
986
 
987
    CYG_ASSERT(devid >= 0, "A valid device id should be supplied");
988
    CYG_ASSERT((0 == txlen) || ((const unsigned char*)0 != txdata), "Data transmits require a transmit buffer");
989
    CYG_ASSERT((0 == rxlen) || ((unsigned char*)0 != rxdata), "Data receives require a receive buffer");
990
    CYG_ASSERT((0 == rxlen) || ((int*)0 != result), "If a reply is expected then space must be allocated");
991
 
992
    // I/O interactions with the auxiliary must be atomic: a context switch in
993
    // between sending the header and the actual data would be bad.
994
    HAL_DISABLE_INTERRUPTS(old_isrstate);
995
 
996
    // The auxiliary should be running for the duration of this
997
    // exchange. However the auxiliary can disappear asynchronously,
998
    // so it is not possible for higher-level code to be sure that the
999
    // auxiliary is still running.
1000
    //
1001
    // If the auxiliary disappears during this call then usually this
1002
    // will cause a SIGCHILD or SIGPIPE, both of which result in
1003
    // termination. The exception is when the auxiliary decides to
1004
    // shut down stdout for some reason without exiting - that has to
1005
    // be detected in the read loop.
1006
    if (synth_auxiliary_running) {
1007
        request[SYNTH_REQUEST_DEVID_OFFSET + 0]     = (devid >>  0) & 0x0FF;
1008
        request[SYNTH_REQUEST_DEVID_OFFSET + 1]     = (devid >>  8) & 0x0FF;
1009
        request[SYNTH_REQUEST_DEVID_OFFSET + 2]     = (devid >> 16) & 0x0FF;
1010
        request[SYNTH_REQUEST_DEVID_OFFSET + 3]     = (devid >> 24) & 0x0FF;
1011
        request[SYNTH_REQUEST_REQUEST_OFFSET + 0]   = (reqcode >>  0) & 0x0FF;
1012
        request[SYNTH_REQUEST_REQUEST_OFFSET + 1]   = (reqcode >>  8) & 0x0FF;
1013
        request[SYNTH_REQUEST_REQUEST_OFFSET + 2]   = (reqcode >> 16) & 0x0FF;
1014
        request[SYNTH_REQUEST_REQUEST_OFFSET + 3]   = (reqcode >> 24) & 0x0FF;
1015
        request[SYNTH_REQUEST_ARG1_OFFSET + 0]      = (arg1 >>  0) & 0x0FF;
1016
        request[SYNTH_REQUEST_ARG1_OFFSET + 1]      = (arg1 >>  8) & 0x0FF;
1017
        request[SYNTH_REQUEST_ARG1_OFFSET + 2]      = (arg1 >> 16) & 0x0FF;
1018
        request[SYNTH_REQUEST_ARG1_OFFSET + 3]      = (arg1 >> 24) & 0x0FF;
1019
        request[SYNTH_REQUEST_ARG2_OFFSET + 0]      = (arg2 >>  0) & 0x0FF;
1020
        request[SYNTH_REQUEST_ARG2_OFFSET + 1]      = (arg2 >>  8) & 0x0FF;
1021
        request[SYNTH_REQUEST_ARG2_OFFSET + 2]      = (arg2 >> 16) & 0x0FF;
1022
        request[SYNTH_REQUEST_ARG2_OFFSET + 3]      = (arg2 >> 24) & 0x0FF;
1023
        request[SYNTH_REQUEST_TXLEN_OFFSET + 0]     = (txlen >>  0) & 0x0FF;
1024
        request[SYNTH_REQUEST_TXLEN_OFFSET + 1]     = (txlen >>  8) & 0x0FF;
1025
        request[SYNTH_REQUEST_TXLEN_OFFSET + 2]     = (txlen >> 16) & 0x0FF;
1026
        request[SYNTH_REQUEST_TXLEN_OFFSET + 3]     = (txlen >> 24) & 0x0FF;
1027
        request[SYNTH_REQUEST_RXLEN_OFFSET + 0]     = (rxlen >>  0) & 0x0FF;
1028
        request[SYNTH_REQUEST_RXLEN_OFFSET + 1]     = (rxlen >>  8) & 0x0FF;
1029
        request[SYNTH_REQUEST_RXLEN_OFFSET + 2]     = (rxlen >> 16) & 0x0FF;
1030
        request[SYNTH_REQUEST_RXLEN_OFFSET + 3]     = ((rxlen >> 24) & 0x0FF) | (((int*)0 != result) ? 0x080 : 0);
1031
 
1032
        // sizeof(synth_auxiliary_request) < PIPE_BUF (4096) so a single write should be atomic,
1033
        // subject only to incoming clock or SIGIO or child-related signals.
1034
        do {
1035
            rc = cyg_hal_sys_write(to_aux, (const void*) &request, SYNTH_REQUEST_LENGTH);
1036
        } while (-CYG_HAL_SYS_EINTR == rc);
1037
 
1038
        // Is there any more data to be sent?
1039
        if (0 < txlen) {
1040
            int sent    = 0;
1041
            CYG_LOOP_INVARIANT(synth_auxiliary_running, "The auxiliary cannot just disappear");
1042
 
1043
            while (sent < txlen) {
1044
                rc = cyg_hal_sys_write(to_aux, (const void*) &(txdata[sent]), txlen - sent);
1045
                if (-CYG_HAL_SYS_EINTR == rc) {
1046
                    continue;
1047
                } else if (rc < 0) {
1048
                    diag_printf("Internal error: unexpected result %d when sending buffer to auxiliary.\n", rc);
1049
                    diag_printf("              : this application is exiting immediately.\n");
1050
                    cyg_hal_sys_exit(1);
1051
                } else {
1052
                    sent += rc;
1053
                }
1054
            }
1055
            CYG_ASSERT(sent <= txlen, "Amount of data sent should not exceed requested size");
1056
        }
1057
 
1058
        // The auxiliary can now process this entire request. Is a reply expected?
1059
        if ((int*)0 != result) {
1060
            // The basic reply is also only a small number of bytes, so should be atomic.
1061
            do {
1062
                rc = cyg_hal_sys_read(from_aux, (void*) &reply, SYNTH_REPLY_LENGTH);
1063
            } while (-CYG_HAL_SYS_EINTR == rc);
1064
            if (rc <= 0) {
1065
                if (rc < 0) {
1066
                    diag_printf("Internal error: unexpected result %d when receiving data from auxiliary.\n", rc);
1067
                } else {
1068
                    diag_printf("Internal error: EOF detected on pipe from auxiliary.\n");
1069
                }
1070
                diag_printf("              : this application is exiting immediately.\n");
1071
                cyg_hal_sys_exit(1);
1072
            }
1073
            CYG_ASSERT(SYNTH_REPLY_LENGTH == rc, "The correct amount of data should have been read");
1074
 
1075
            // Replies are packed in Tcl and assumed to be two 32-bit
1076
            // little-endian integers.
1077
            *result   = (reply[SYNTH_REPLY_RESULT_OFFSET + 3] << 24) |
1078
                (reply[SYNTH_REPLY_RESULT_OFFSET + 2] << 16) |
1079
                (reply[SYNTH_REPLY_RESULT_OFFSET + 1] <<  8) |
1080
                (reply[SYNTH_REPLY_RESULT_OFFSET + 0] <<  0);
1081
            reply_rxlen = (reply[SYNTH_REPLY_RXLEN_OFFSET + 3] << 24) |
1082
                (reply[SYNTH_REPLY_RXLEN_OFFSET + 2] << 16) |
1083
                (reply[SYNTH_REPLY_RXLEN_OFFSET + 1] <<  8) |
1084
                (reply[SYNTH_REPLY_RXLEN_OFFSET + 0] <<  0);
1085
 
1086
            CYG_ASSERT(reply_rxlen <= rxlen, "The auxiliary should not be sending more data than was requested.");
1087
 
1088
            if ((int*)0 != actual_rxlen) {
1089
                *actual_rxlen  = reply_rxlen;
1090
            }
1091
            if (reply_rxlen) {
1092
                int received = 0;
1093
 
1094
                while (received < reply_rxlen) {
1095
                    rc = cyg_hal_sys_read(from_aux, (void*) &(rxdata[received]), reply_rxlen - received);
1096
                    if (-CYG_HAL_SYS_EINTR == rc) {
1097
                        continue;
1098
                    } else if (rc <= 0) {
1099
                        if (rc < 0) {
1100
                            diag_printf("Internal error: unexpected result %d when receiving data from auxiliary.\n", rc);
1101
                        } else {
1102
                            diag_printf("Internal error: EOF detected on pipe from auxiliary.\n");
1103
                        }
1104
                        diag_printf("              : this application is exiting immediately.\n");
1105
                    } else {
1106
                        received += rc;
1107
                    }
1108
                }
1109
                CYG_ASSERT(received == reply_rxlen, "Amount received should be exact");
1110
            }
1111
        }
1112
    }
1113
 
1114
    HAL_RESTORE_INTERRUPTS(old_isrstate);
1115
}
1116
 
1117
// Instantiate a device. This takes arguments such as
1118
// devs/eth/synth/ecosynth, current, ethernet, eth0, and 200x100 If
1119
// the package and version are NULL strings then the device being
1120
// initialized is application-specific and does not belong to any
1121
// particular package.
1122
int
1123
synth_auxiliary_instantiate(const char* pkg, const char* version, const char* devtype, const char* devinst, const char* devdata)
1124
{
1125
    int         result = -1;
1126
    char        buf[512 + 1];
1127
    const char* str;
1128
    int         index;
1129
 
1130
    CYG_ASSERT((const char*)0 != devtype, "Device instantiations must specify a valid device type");
1131
    CYG_ASSERT((((const char*)0 != pkg) && ((const char*)0 != version)) || \
1132
               (((const char*)0 == pkg) && ((const char*)0 == version)), "If a package is specified then the version must be supplied as well");
1133
 
1134
    index = 0;
1135
    str = pkg;
1136
    if ((const char*)0 == str) {
1137
        str = "";
1138
    }
1139
    while ( (index < 512) && ('\0' != *str) ) {
1140
        buf[index++] = *str++;
1141
    }
1142
    if (index < 512) buf[index++] = '\0';
1143
    str = version;
1144
    if ((const char*)0 == str) {
1145
        str = "";
1146
    }
1147
    while ((index < 512) && ('\0' != *str) ) {
1148
        buf[index++] = *str++;
1149
    }
1150
    if (index < 512) buf[index++] = '\0';
1151
    for (str = devtype; (index < 512) && ('\0' != *str); ) {
1152
        buf[index++] = *str++;
1153
    }
1154
    if (index < 512) buf[index++] = '\0';
1155
    if ((const char*)0 != devinst) {
1156
        for (str = devinst; (index < 512) && ('\0' != *str); ) {
1157
            buf[index++] = *str++;
1158
        }
1159
    }
1160
    if (index < 512) buf[index++] = '\0';
1161
    if ((const char*)0 != devdata) {
1162
        for (str = devdata; (index < 512) && ('\0' != *str); ) {
1163
            buf[index++] = *str++;
1164
        }
1165
    }
1166
    if (index < 512) {
1167
        buf[index++] = '\0';
1168
    } else {
1169
        diag_printf("Internal error: buffer overflow constructing instantiate request for auxiliary.\n");
1170
        diag_printf("              : this application is exiting immediately.\n");
1171
        cyg_hal_sys_exit(1);
1172
    }
1173
 
1174
    if (synth_auxiliary_running) {
1175
        synth_auxiliary_xchgmsg(SYNTH_DEV_AUXILIARY, SYNTH_AUXREQ_INSTANTIATE, 0, 0,
1176
                                buf, index,
1177
                                &result,
1178
                                (unsigned char*) 0, (int *) 0, 0);
1179
    }
1180
    return result;
1181
}
1182
 
1183
// ----------------------------------------------------------------------------
1184
// SIGPIPE and SIGCHLD are special, related to the auxiliary process.
1185
//
1186
// A SIGPIPE can only happen when the application is writing to the
1187
// auxiliary, which only happens inside synth_auxiliary_xchgmsg() (this
1188
// assumes that no other code is writing down a pipe, e.g. to interact
1189
// with a process other than the standard I/O auxiliary). Either the
1190
// auxiliary has explicitly closed the pipe, which it is not supposed
1191
// to do, or more likely it has exited. Either way, there is little
1192
// point in continuing - unless we already know that the system is
1193
// shutting down.
1194
static void
1195
synth_pipe_sighandler(int sig)
1196
{
1197
    CYG_ASSERT(CYG_HAL_SYS_SIGPIPE == sig, "The right signal handler should be invoked");
1198
    if (synth_auxiliary_running) {
1199
        synth_auxiliary_running   = false;
1200
        diag_printf("Internal error: communication with the I/O auxiliary has been lost.\n");
1201
        diag_printf("              : this application is exiting immediately.\n");
1202
        cyg_hal_sys_exit(1);
1203
    }
1204
}
1205
 
1206
// Similarly it is assumed that there will be no child processes other than
1207
// the auxiliary. Therefore a SIGCHLD indicates that the auxiliary has
1208
// terminated unexpectedly. This is bad: normal termination involves
1209
// the application exiting and the auxiliary terminating in response,
1210
// not the other way around.
1211
//
1212
// As a special case, if it is known that the auxiliary is not currently
1213
// usable then the signal is ignored. This copes with the situation where
1214
// the auxiliary has just been fork()'d but has failed to initialize, or
1215
// alternatively where the whole system is in the process of shutting down
1216
// cleanly and it happens that the auxiliary got there first.
1217
static void
1218
synth_chld_sighandler(int sig)
1219
{
1220
    CYG_ASSERT(CYG_HAL_SYS_SIGCHLD == sig, "The right signal handler should be invoked");
1221
    if (synth_auxiliary_running) {
1222
        synth_auxiliary_running   = false;
1223
        diag_printf("Internal error: the I/O auxiliary has terminated unexpectedly.\n");
1224
        diag_printf("              : this application is exiting immediately.\n");
1225
        cyg_hal_sys_exit(1);
1226
    }
1227
}
1228
 
1229
// ----------------------------------------------------------------------------
1230
// Initialization
1231
 
1232
void
1233
synth_hardware_init(void)
1234
{
1235
    struct cyg_hal_sys_sigaction action;
1236
    struct cyg_hal_sys_sigset_t  blocked;
1237
    int i;
1238
 
1239
    // Set up a sigprocmask to block all signals except the ones we
1240
    // particularly want to handle. However do not block the tty
1241
    // signals - the ability to ctrl-C a program is important.
1242
    CYG_HAL_SYS_SIGFILLSET(&blocked);
1243
    CYG_HAL_SYS_SIGDELSET(&blocked, CYG_HAL_SYS_SIGILL);
1244
    CYG_HAL_SYS_SIGDELSET(&blocked, CYG_HAL_SYS_SIGBUS);
1245
    CYG_HAL_SYS_SIGDELSET(&blocked, CYG_HAL_SYS_SIGFPE);
1246
    CYG_HAL_SYS_SIGDELSET(&blocked, CYG_HAL_SYS_SIGSEGV);
1247
    CYG_HAL_SYS_SIGDELSET(&blocked, CYG_HAL_SYS_SIGPIPE);
1248
    CYG_HAL_SYS_SIGDELSET(&blocked, CYG_HAL_SYS_SIGCHLD);
1249
    CYG_HAL_SYS_SIGDELSET(&blocked, CYG_HAL_SYS_SIGALRM);
1250
    CYG_HAL_SYS_SIGDELSET(&blocked, CYG_HAL_SYS_SIGIO);
1251
    CYG_HAL_SYS_SIGDELSET(&blocked, CYG_HAL_SYS_SIGHUP);
1252
    CYG_HAL_SYS_SIGDELSET(&blocked, CYG_HAL_SYS_SIGINT);
1253
    CYG_HAL_SYS_SIGDELSET(&blocked, CYG_HAL_SYS_SIGQUIT);
1254
    CYG_HAL_SYS_SIGDELSET(&blocked, CYG_HAL_SYS_SIGTERM);
1255
    CYG_HAL_SYS_SIGDELSET(&blocked, CYG_HAL_SYS_SIGCONT);
1256
    CYG_HAL_SYS_SIGDELSET(&blocked, CYG_HAL_SYS_SIGSTOP);
1257
    CYG_HAL_SYS_SIGDELSET(&blocked, CYG_HAL_SYS_SIGTSTP);
1258
 
1259
    if (0 != cyg_hal_sys_sigprocmask(CYG_HAL_SYS_SIG_SETMASK, &blocked, (cyg_hal_sys_sigset_t*) 0)) {
1260
        CYG_FAIL("Failed to initialize sigprocmask");
1261
    }
1262
 
1263
    // Now set up the VSR and ISR statics
1264
    synth_VSR = &synth_default_vsr;
1265
    for (i = 0; i < CYGNUM_HAL_ISR_COUNT; i++) {
1266
        synth_isr_handlers[i].isr       = &synth_default_isr;
1267
        synth_isr_handlers[i].data      = (CYG_ADDRWORD) 0;
1268
        synth_isr_handlers[i].obj       = (CYG_ADDRESS) 0;
1269
        synth_isr_handlers[i].pri       = CYGNUM_HAL_ISR_COUNT;
1270
    }
1271
 
1272
    // Install signal handlers for SIGIO and SIGALRM, the two signals
1273
    // that may cause the VSR to run. SA_NODEFER is important: it
1274
    // means that the current signal will not be blocked while the
1275
    // signal handler is running. Combined with a mask of 0, it means
1276
    // that the sigprocmask does not change when a signal handler is
1277
    // invoked, giving eCos the flexibility to switch to other threads
1278
    // instead of having the signal handler return immediately.
1279
    action.hal_mask     = 0;
1280
    action.hal_flags    = CYG_HAL_SYS_SA_NODEFER;
1281
    action.hal_bogus    = (void (*)(int)) 0;
1282
    action.hal_handler  = &synth_alrm_sighandler;
1283
    if (0 != cyg_hal_sys_sigaction(CYG_HAL_SYS_SIGALRM, &action, (struct cyg_hal_sys_sigaction*) 0)) {
1284
        CYG_FAIL("Failed to install signal handler for SIGALRM");
1285
    }
1286
    action.hal_handler  = &synth_io_sighandler;
1287
    if (0 != cyg_hal_sys_sigaction(CYG_HAL_SYS_SIGIO, &action, (struct cyg_hal_sys_sigaction*) 0)) {
1288
        CYG_FAIL("Failed to install signal handler for SIGIO");
1289
    }
1290
 
1291
    // Install handlers for the various exceptions. For now these also
1292
    // operate with unchanged sigprocmasks, allowing nested
1293
    // exceptions. It is not clear that this is entirely a good idea,
1294
    // but in practice these exceptions will usually be handled by gdb
1295
    // anyway.
1296
    action.hal_handler  = &synth_exception_sighandler;
1297
    if (0 != cyg_hal_sys_sigaction(CYG_HAL_SYS_SIGILL,  &action, (struct cyg_hal_sys_sigaction*) 0)) {
1298
        CYG_FAIL("Failed to install signal handler for SIGILL");
1299
    }
1300
    if (0 != cyg_hal_sys_sigaction(CYG_HAL_SYS_SIGBUS,  &action, (struct cyg_hal_sys_sigaction*) 0)) {
1301
        CYG_FAIL("Failed to install signal handler for SIGBUS");
1302
    }
1303
    if (0 != cyg_hal_sys_sigaction(CYG_HAL_SYS_SIGFPE,  &action, (struct cyg_hal_sys_sigaction*) 0)) {
1304
        CYG_FAIL("Failed to install signal handler for SIGFPE");
1305
    }
1306
    if (0 != cyg_hal_sys_sigaction(CYG_HAL_SYS_SIGSEGV,  &action, (struct cyg_hal_sys_sigaction*) 0)) {
1307
        CYG_FAIL("Failed to install signal handler for SIGSEGV");
1308
    }
1309
 
1310
    // Also cope with SIGCHLD and SIGPIPE. SIGCHLD indicates that the
1311
    // auxiliary has terminated, which is a bad thing. SIGPIPE
1312
    // indicates that a write to the auxiliary has terminated, but
1313
    // the error condition was caught at a different stage.
1314
    action.hal_handler = &synth_pipe_sighandler;
1315
    if (0 != cyg_hal_sys_sigaction(CYG_HAL_SYS_SIGPIPE,  &action, (struct cyg_hal_sys_sigaction*) 0)) {
1316
        CYG_FAIL("Failed to install signal handler for SIGPIPE");
1317
    }
1318
    action.hal_handler = &synth_chld_sighandler;
1319
    action.hal_flags  |= CYG_HAL_SYS_SA_NOCLDSTOP | CYG_HAL_SYS_SA_NOCLDWAIT;
1320
    if (0 != cyg_hal_sys_sigaction(CYG_HAL_SYS_SIGCHLD,  &action, (struct cyg_hal_sys_sigaction*) 0)) {
1321
        CYG_FAIL("Failed to install signal handler for SIGCHLD");
1322
    }
1323
 
1324
    // Start up the auxiliary process.
1325
    synth_start_auxiliary();
1326
 
1327
    // All done. At this stage interrupts are still disabled, no ISRs
1328
    // have been installed, and the clock is not yet ticking.
1329
    // Exceptions can come in and will be processed normally. SIGIO
1330
    // and SIGALRM could come in, but nothing has yet been done
1331
    // to make that happen.
1332
}
1333
 
1334
// Second-stage hardware init. This is called after all C++ static
1335
// constructors have been run, which should mean that all device
1336
// drivers have been initialized and will have performed appropriate
1337
// interactions with the I/O auxiliary. There should now be a
1338
// message exchange with the auxiliary to let it know that there will
1339
// not be any more devices, allowing it to remove unwanted frames,
1340
// run the user's mainrc.tcl script, and so on. Also this is the
1341
// time that the various toplevels get mapped on to the display.
1342
//
1343
// This request blocks until the auxiliary is ready. The return value
1344
// indicates whether or not any errors occurred on the auxiliary side,
1345
// and that those errors have not been suppressed using --keep-going
1346
 
1347
void
1348
synth_hardware_init2(void)
1349
{
1350
    if (synth_auxiliary_running) {
1351
        int result;
1352
        synth_auxiliary_xchgmsg(SYNTH_DEV_AUXILIARY, SYNTH_AUXREQ_CONSTRUCTORS_DONE,
1353
                               0, 0, (const unsigned char*) 0, 0,
1354
                               &result,
1355
                               (unsigned char*) 0, (int*) 0, 0);
1356
        if ( !result ) {
1357
            cyg_hal_sys_exit(1);
1358
        }
1359
    }
1360
}

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.