RaiseAsync.c 30.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
/* ---------------------------------------------------------------------------
 *
 * (c) The GHC Team, 1998-2006
 *
 * Asynchronous exceptions
 *
 * --------------------------------------------------------------------------*/

#include "PosixSource.h"
#include "Rts.h"
Simon Marlow's avatar
Simon Marlow committed
11
12

#include "sm/Storage.h"
13
14
15
#include "Threads.h"
#include "Trace.h"
#include "RaiseAsync.h"
16
#include "Schedule.h"
17
18
#include "Updates.h"
#include "STM.h"
Simon Marlow's avatar
Simon Marlow committed
19
#include "sm/Sanity.h"
20
#include "Profiling.h"
21
#include "Messages.h"
22
23
24
#if defined(mingw32_HOST_OS)
#include "win32/IOManager.h"
#endif
25
26
27
28
29

static void raiseAsync (Capability *cap,
			StgTSO *tso,
			StgClosure *exception, 
			rtsBool stop_at_atomically,
30
			StgUpdateFrame *stop_here);
31
32
33

static void removeFromQueues(Capability *cap, StgTSO *tso);

34
35
static void removeFromMVarBlockedQueue (StgTSO *tso);

36
37
static void blockedThrowTo (Capability *cap, 
                            StgTSO *target, MessageThrowTo *msg);
38

39
40
41
42
static void throwToSendMsg (Capability *cap USED_IF_THREADS,
                            Capability *target_cap USED_IF_THREADS, 
                            MessageThrowTo *msg USED_IF_THREADS);

43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/* -----------------------------------------------------------------------------
   throwToSingleThreaded

   This version of throwTo is safe to use if and only if one of the
   following holds:
   
     - !THREADED_RTS

     - all the other threads in the system are stopped (eg. during GC).

     - we surely own the target TSO (eg. we just took it from the
       run queue of the current capability, or we are running it).

   It doesn't cater for blocking the source thread until the exception
   has been raised.
   -------------------------------------------------------------------------- */

Simon Marlow's avatar
Simon Marlow committed
60
61
62
static void
throwToSingleThreaded__ (Capability *cap, StgTSO *tso, StgClosure *exception, 
                         rtsBool stop_at_atomically, StgUpdateFrame *stop_here)
63
{
64
65
    tso = deRefTSO(tso);

66
67
68
69
70
71
72
73
    // Thread already dead?
    if (tso->what_next == ThreadComplete || tso->what_next == ThreadKilled) {
	return;
    }

    // Remove it from any blocking queues
    removeFromQueues(cap,tso);

Simon Marlow's avatar
Simon Marlow committed
74
    raiseAsync(cap, tso, exception, stop_at_atomically, stop_here);
75
76
77
}

void
Simon Marlow's avatar
Simon Marlow committed
78
throwToSingleThreaded (Capability *cap, StgTSO *tso, StgClosure *exception)
79
{
Simon Marlow's avatar
Simon Marlow committed
80
81
    throwToSingleThreaded__(cap, tso, exception, rtsFalse, NULL);
}
82

Simon Marlow's avatar
Simon Marlow committed
83
84
85
86
87
88
void
throwToSingleThreaded_ (Capability *cap, StgTSO *tso, StgClosure *exception, 
                        rtsBool stop_at_atomically)
{
    throwToSingleThreaded__ (cap, tso, exception, stop_at_atomically, NULL);
}
89

Simon Marlow's avatar
Simon Marlow committed
90
91
92
93
void
suspendComputation (Capability *cap, StgTSO *tso, StgUpdateFrame *stop_here)
{
    throwToSingleThreaded__ (cap, tso, NULL, rtsFalse, stop_here);
94
95
96
97
98
99
100
101
102
103
104
}

/* -----------------------------------------------------------------------------
   throwTo

   This function may be used to throw an exception from one thread to
   another, during the course of normal execution.  This is a tricky
   task: the target thread might be running on another CPU, or it
   may be blocked and could be woken up at any point by another CPU.
   We have some delicate synchronisation to do.

105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
   The underlying scheme when multiple Capabilities are in use is
   message passing: when the target of a throwTo is on another
   Capability, we send a message (a MessageThrowTo closure) to that
   Capability.

   If the throwTo needs to block because the target TSO is masking
   exceptions (the TSO_BLOCKEX flag), then the message is placed on
   the blocked_exceptions queue attached to the target TSO.  When the
   target TSO enters the unmasked state again, it must check the
   queue.  The blocked_exceptions queue is not locked; only the
   Capability owning the TSO may modify it.

   To make things simpler for throwTo, we always create the message
   first before deciding what to do.  The message may get sent, or it
   may get attached to a TSO's blocked_exceptions queue, or the
   exception may get thrown immediately and the message dropped,
   depending on the current state of the target.

   Currently we send a message if the target belongs to another
   Capability, and it is

126
     - NotBlocked, BlockedOnMsgThrowTo,
127
       BlockedOnCCall_Interruptible
128
129
130
131
132
133
134
135
136

     - or it is masking exceptions (TSO_BLOCKEX)

   Currently, if the target is BlockedOnMVar, BlockedOnSTM, or
   BlockedOnBlackHole then we acquire ownership of the TSO by locking
   its parent container (e.g. the MVar) and then raise the exception.
   We might change these cases to be more message-passing-like in the
   future.
  
137
138
   Returns: 

139
   NULL               exception was raised, ok to continue
140

141
142
143
144
145
146
147
   MessageThrowTo *   exception was not raised; the source TSO
                      should now put itself in the state 
                      BlockedOnMsgThrowTo, and when it is ready
                      it should unlock the mssage using
                      unlockClosure(msg, &stg_MSG_THROWTO_info);
                      If it decides not to raise the exception after
                      all, it can revoke it safely with
148
                      unlockClosure(msg, &stg_MSG_NULL_info);
149
150
151

   -------------------------------------------------------------------------- */

152
MessageThrowTo *
153
throwTo (Capability *cap,	// the Capability we hold 
154
	 StgTSO *source,	// the TSO sending the exception (or NULL)
155
	 StgTSO *target,        // the TSO receiving the exception
156
157
158
159
160
161
162
	 StgClosure *exception) // the exception closure
{
    MessageThrowTo *msg;

    msg = (MessageThrowTo *) allocate(cap, sizeofW(MessageThrowTo));
    // message starts locked; the caller has to unlock it when it is
    // ready.
163
    SET_HDR(msg, &stg_WHITEHOLE_info, CCS_SYSTEM);
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
    msg->source      = source;
    msg->target      = target;
    msg->exception   = exception;

    switch (throwToMsg(cap, msg))
    {
    case THROWTO_SUCCESS:
        return NULL;
    case THROWTO_BLOCKED:
    default:
        return msg;
    }
}
    

nat
throwToMsg (Capability *cap, MessageThrowTo *msg)
181
182
{
    StgWord status;
183
    StgTSO *target = msg->target;
184
    Capability *target_cap;
185

186
187
188
189
190
191
192
    goto check_target;

retry:
    write_barrier();
    debugTrace(DEBUG_sched, "throwTo: retrying...");

check_target:
Simon Marlow's avatar
Simon Marlow committed
193
194
    ASSERT(target != END_TSO_QUEUE);

195
    // follow ThreadRelocated links in the target first
196
197
198
199
200
201
    target = deRefTSO(target);

    // Thread already dead?
    if (target->what_next == ThreadComplete 
	|| target->what_next == ThreadKilled) {
	return THROWTO_SUCCESS;
202
203
    }

204
205
206
207
    debugTraceCap(DEBUG_sched, cap,
                  "throwTo: from thread %lu to thread %lu",
                  (unsigned long)msg->source->id, 
                  (unsigned long)msg->target->id);
208
209

#ifdef DEBUG
210
    traceThreadStatus(DEBUG_sched, target);
211
212
#endif

213
214
215
216
    target_cap = target->cap;
    if (target->cap != cap) {
        throwToSendMsg(cap, target_cap, msg);
        return THROWTO_BLOCKED;
217
218
219
220
221
222
223
    }

    status = target->why_blocked;
    
    switch (status) {
    case NotBlocked:
    {
224
225
226
227
        if ((target->flags & TSO_BLOCKEX) == 0) {
            // It's on our run queue and not blocking exceptions
            raiseAsync(cap, target, msg->exception, rtsFalse, NULL);
            return THROWTO_SUCCESS;
228
        } else {
229
230
            blockedThrowTo(cap,target,msg);
            return THROWTO_BLOCKED;
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
        }
    }

    case BlockedOnMsgThrowTo:
    {
        const StgInfoTable *i;
        MessageThrowTo *m;

        m = target->block_info.throwto;

        // target is local to this cap, but has sent a throwto
        // message to another cap.
        //
        // The source message is locked.  We need to revoke the
        // target's message so that we can raise the exception, so
        // we attempt to lock it.

        // There's a possibility of a deadlock if two threads are both
        // trying to throwTo each other (or more generally, a cycle of
        // threads).  To break the symmetry we compare the addresses
        // of the MessageThrowTo objects, and the one for which m <
        // msg gets to spin, while the other can only try to lock
        // once, but must then back off and unlock both before trying
        // again.
        if (m < msg) {
            i = lockClosure((StgClosure *)m);
        } else {
            i = tryLockClosure((StgClosure *)m);
            if (i == NULL) {
//            debugBelch("collision\n");
                throwToSendMsg(cap, target->cap, msg);
                return THROWTO_BLOCKED;
            }
        }

266
267
268
269
270
        if (i == &stg_MSG_NULL_info) {
            // we know there's a MSG_TRY_WAKEUP on the way, so we
            // might as well just do it now.  The message will
            // be a no-op when it arrives.
            unlockClosure((StgClosure*)m, i);
271
            tryWakeupThread_(cap, target);
272
273
274
            goto retry;
        }

275
        if (i != &stg_MSG_THROWTO_info) {
276
            // if it's a MSG_NULL, this TSO has been woken up by another Cap
277
278
279
280
281
282
283
284
285
286
287
288
            unlockClosure((StgClosure*)m, i);
            goto retry;
        }

	if ((target->flags & TSO_BLOCKEX) &&
	    ((target->flags & TSO_INTERRUPTIBLE) == 0)) {
            unlockClosure((StgClosure*)m, i);
            blockedThrowTo(cap,target,msg);
            return THROWTO_BLOCKED;
        }

        // nobody else can wake up this TSO after we claim the message
289
        unlockClosure((StgClosure*)m, &stg_MSG_NULL_info);
290
291
292

        raiseAsync(cap, target, msg->exception, rtsFalse, NULL);
        return THROWTO_SUCCESS;
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
    }

    case BlockedOnMVar:
    {
	/*
	  To establish ownership of this TSO, we need to acquire a
	  lock on the MVar that it is blocked on.
	*/
	StgMVar *mvar;
	StgInfoTable *info USED_IF_THREADS;
	
	mvar = (StgMVar *)target->block_info.closure;

	// ASSUMPTION: tso->block_info must always point to a
	// closure.  In the threaded RTS it does.
308
309
310
311
312
313
314
        switch (get_itbl(mvar)->type) {
        case MVAR_CLEAN:
        case MVAR_DIRTY:
            break;
        default:
            goto retry;
        }
315
316
317
318

	info = lockClosure((StgClosure *)mvar);

	if (target->what_next == ThreadRelocated) {
319
	    target = target->_link;
320
321
322
323
324
325
326
327
328
329
330
	    unlockClosure((StgClosure *)mvar,info);
	    goto retry;
	}
	// we have the MVar, let's check whether the thread
	// is still blocked on the same MVar.
	if (target->why_blocked != BlockedOnMVar
	    || (StgMVar *)target->block_info.closure != mvar) {
	    unlockClosure((StgClosure *)mvar, info);
	    goto retry;
	}

331
332
333
334
335
336
        if (target->_link == END_TSO_QUEUE) {
            // the MVar operation has already completed.  There is a
            // MSG_TRY_WAKEUP on the way, but we can just wake up the
            // thread now anyway and ignore the message when it
            // arrives.
	    unlockClosure((StgClosure *)mvar, info);
337
            tryWakeupThread_(cap, target);
338
339
340
            goto retry;
        }

341
342
	if ((target->flags & TSO_BLOCKEX) &&
	    ((target->flags & TSO_INTERRUPTIBLE) == 0)) {
343
            blockedThrowTo(cap,target,msg);
344
	    unlockClosure((StgClosure *)mvar, info);
345
	    return THROWTO_BLOCKED;
346
	} else {
347
348
            // revoke the MVar operation
            removeFromMVarBlockedQueue(target);
349
	    raiseAsync(cap, target, msg->exception, rtsFalse, NULL);
350
	    unlockClosure((StgClosure *)mvar, info);
351
352
353
354
355
356
	    return THROWTO_SUCCESS;
	}
    }

    case BlockedOnBlackHole:
    {
357
358
359
360
361
362
363
364
365
366
367
368
369
370
	if (target->flags & TSO_BLOCKEX) {
            // BlockedOnBlackHole is not interruptible.
            blockedThrowTo(cap,target,msg);
	    return THROWTO_BLOCKED;
	} else {
            // Revoke the message by replacing it with IND. We're not
            // locking anything here, so we might still get a TRY_WAKEUP
            // message from the owner of the blackhole some time in the
            // future, but that doesn't matter.
            ASSERT(target->block_info.bh->header.info == &stg_MSG_BLACKHOLE_info);
            OVERWRITE_INFO(target->block_info.bh, &stg_IND_info);
            raiseAsync(cap, target, msg->exception, rtsFalse, NULL);
            return THROWTO_SUCCESS;
        }
371
372
373
    }

    case BlockedOnSTM:
374
375
376
377
	lockTSO(target);
	// Unblocking BlockedOnSTM threads requires the TSO to be
	// locked; see STM.c:unpark_tso().
	if (target->why_blocked != BlockedOnSTM) {
378
	    unlockTSO(target);
379
380
381
382
	    goto retry;
	}
	if ((target->flags & TSO_BLOCKEX) &&
	    ((target->flags & TSO_INTERRUPTIBLE) == 0)) {
383
            blockedThrowTo(cap,target,msg);
384
	    unlockTSO(target);
385
386
	    return THROWTO_BLOCKED;
	} else {
387
	    raiseAsync(cap, target, msg->exception, rtsFalse, NULL);
388
389
390
	    unlockTSO(target);
	    return THROWTO_SUCCESS;
	}
391

392
393
394
395
396
397
398
399
400
401
402
403
404
    case BlockedOnCCall_Interruptible:
#ifdef THREADED_RTS
    {
        Task *task = NULL;
        // walk suspended_ccalls to find the correct worker thread
        InCall *incall;
        for (incall = cap->suspended_ccalls; incall != NULL; incall = incall->next) {
            if (incall->suspended_tso == target) {
                task = incall->task;
                break;
            }
        }
        if (task != NULL) {
405
            blockedThrowTo(cap, target, msg);
Simon Marlow's avatar
Simon Marlow committed
406
407
            if (!((target->flags & TSO_BLOCKEX) &&
                  ((target->flags & TSO_INTERRUPTIBLE) == 0))) {
408
409
410
                interruptWorkerTask(task);
            }
            return THROWTO_BLOCKED;
411
412
413
414
415
416
        } else {
            debugTraceCap(DEBUG_sched, cap, "throwTo: could not find worker thread to kill");
        }
        // fall to next
    }
#endif
417
    case BlockedOnCCall:
418
	blockedThrowTo(cap,target,msg);
419
420
421
422
423
424
	return THROWTO_BLOCKED;

#ifndef THREADEDED_RTS
    case BlockedOnRead:
    case BlockedOnWrite:
    case BlockedOnDelay:
425
426
427
#if defined(mingw32_HOST_OS)
    case BlockedOnDoProc:
#endif
428
429
	if ((target->flags & TSO_BLOCKEX) &&
	    ((target->flags & TSO_INTERRUPTIBLE) == 0)) {
430
	    blockedThrowTo(cap,target,msg);
431
432
433
	    return THROWTO_BLOCKED;
	} else {
	    removeFromQueues(cap,target);
434
	    raiseAsync(cap, target, msg->exception, rtsFalse, NULL);
435
436
437
438
439
440
441
442
443
444
445
	    return THROWTO_SUCCESS;
	}
#endif

    default:
	barf("throwTo: unrecognised why_blocked value");
    }
    barf("throwTo");
}

static void
446
447
448
449
throwToSendMsg (Capability *cap STG_UNUSED,
                Capability *target_cap USED_IF_THREADS, 
                MessageThrowTo *msg USED_IF_THREADS)
            
450
{
451
#ifdef THREADED_RTS
452
    debugTraceCap(DEBUG_sched, cap, "throwTo: sending a throwto message to cap %lu", (unsigned long)target_cap->no);
453

454
    sendMessage(cap, target_cap, (Message*)msg);
455
456
#endif
}
457

458
459
460
461
462
// Block a throwTo message on the target TSO's blocked_exceptions
// queue.  The current Capability must own the target TSO in order to
// modify the blocked_exceptions queue.
static void
blockedThrowTo (Capability *cap, StgTSO *target, MessageThrowTo *msg)
463
{
464
465
466
467
468
    debugTraceCap(DEBUG_sched, cap, "throwTo: blocking on thread %lu",
                  (unsigned long)target->id);

    ASSERT(target->cap == cap);

469
    msg->link = target->blocked_exceptions;
470
471
    target->blocked_exceptions = msg;
    dirty_TSO(cap,target); // we modified the blocked_exceptions queue
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
}

/* -----------------------------------------------------------------------------
   Waking up threads blocked in throwTo

   There are two ways to do this: maybePerformBlockedException() will
   perform the throwTo() for the thread at the head of the queue
   immediately, and leave the other threads on the queue.
   maybePerformBlockedException() also checks the TSO_BLOCKEX flag
   before raising an exception.

   awakenBlockedExceptionQueue() will wake up all the threads in the
   queue, but not perform any throwTo() immediately.  This might be
   more appropriate when the target thread is the one actually running
   (see Exception.cmm).
487
488

   Returns: non-zero if an exception was raised, zero otherwise.
489
490
   -------------------------------------------------------------------------- */

491
int
492
493
maybePerformBlockedException (Capability *cap, StgTSO *tso)
{
494
495
    MessageThrowTo *msg;
    const StgInfoTable *i;
496
    
497
    if (tso->what_next == ThreadComplete || tso->what_next == ThreadFinished) {
498
        if (tso->blocked_exceptions != END_BLOCKED_EXCEPTIONS_QUEUE) {
499
500
501
502
503
504
505
            awakenBlockedExceptionQueue(cap,tso);
            return 1;
        } else {
            return 0;
        }
    }

506
    if (tso->blocked_exceptions != END_BLOCKED_EXCEPTIONS_QUEUE && 
Simon Marlow's avatar
Simon Marlow committed
507
        (tso->flags & TSO_BLOCKEX) != 0) {
508
        debugTraceCap(DEBUG_sched, cap, "throwTo: thread %lu has blocked exceptions but is inside block", (unsigned long)tso->id);
Simon Marlow's avatar
Simon Marlow committed
509
510
    }

511
    if (tso->blocked_exceptions != END_BLOCKED_EXCEPTIONS_QUEUE
512
513
514
515
516
	&& ((tso->flags & TSO_BLOCKEX) == 0
	    || ((tso->flags & TSO_INTERRUPTIBLE) && interruptible(tso)))) {

	// We unblock just the first thread on the queue, and perform
	// its throw immediately.
517
518
519
520
521
    loop:
        msg = tso->blocked_exceptions;
        if (msg == END_BLOCKED_EXCEPTIONS_QUEUE) return 0;
        i = lockClosure((StgClosure*)msg);
        tso->blocked_exceptions = (MessageThrowTo*)msg->link;
522
        if (i == &stg_MSG_NULL_info) {
523
524
525
526
            unlockClosure((StgClosure*)msg,i);
            goto loop;
        }

527
528
529
        throwToSingleThreaded(cap, msg->target, msg->exception);
        unlockClosure((StgClosure*)msg,&stg_MSG_NULL_info);
        tryWakeupThread(cap, msg->source);
530
        return 1;
531
    }
532
    return 0;
533
534
}

Simon Marlow's avatar
Simon Marlow committed
535
// awakenBlockedExceptionQueue(): Just wake up the whole queue of
536
// blocked exceptions.
Simon Marlow's avatar
Simon Marlow committed
537

538
539
540
void
awakenBlockedExceptionQueue (Capability *cap, StgTSO *tso)
{
541
542
543
544
545
546
    MessageThrowTo *msg;
    const StgInfoTable *i;

    for (msg = tso->blocked_exceptions; msg != END_BLOCKED_EXCEPTIONS_QUEUE;
         msg = (MessageThrowTo*)msg->link) {
        i = lockClosure((StgClosure *)msg);
547
548
549
550
551
        if (i != &stg_MSG_NULL_info) {
            unlockClosure((StgClosure *)msg,&stg_MSG_NULL_info);
            tryWakeupThread(cap, msg->source);
        } else {
            unlockClosure((StgClosure *)msg,i);
552
553
554
        }
    }
    tso->blocked_exceptions = END_BLOCKED_EXCEPTIONS_QUEUE;
555
556
557
558
559
560
561
}    

/* -----------------------------------------------------------------------------
   Remove a thread from blocking queues.

   This is for use when we raise an exception in another thread, which
   may be blocked.
562

563
564
   Precondition: we have exclusive access to the TSO, via the same set
   of conditions as throwToSingleThreaded() (c.f.).
565
566
   -------------------------------------------------------------------------- */

567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
static void
removeFromMVarBlockedQueue (StgTSO *tso)
{
    StgMVar *mvar = (StgMVar*)tso->block_info.closure;
    StgMVarTSOQueue *q = (StgMVarTSOQueue*)tso->_link;

    if (q == (StgMVarTSOQueue*)END_TSO_QUEUE) {
        // already removed from this MVar
        return;
    }

    // Assume the MVar is locked. (not assertable; sometimes it isn't
    // actually WHITEHOLE'd).

    // We want to remove the MVAR_TSO_QUEUE object from the queue.  It
    // isn't doubly-linked so we can't actually remove it; instead we
    // just overwrite it with an IND if possible and let the GC short
    // it out.  However, we have to be careful to maintain the deque
    // structure:

    if (mvar->head == q) {
        mvar->head = q->link;
        q->header.info = &stg_IND_info;
        if (mvar->tail == q) {
            mvar->tail = (StgMVarTSOQueue*)END_TSO_QUEUE;
        }
    }
    else if (mvar->tail == q) {
        // we can't replace it with an IND in this case, because then
        // we lose the tail pointer when the GC shorts out the IND.
        // So we use MSG_NULL as a kind of non-dupable indirection;
        // these are ignored by takeMVar/putMVar.
        q->header.info = &stg_MSG_NULL_info;
    }
    else {
        q->header.info = &stg_IND_info;
    }

    // revoke the MVar operation
    tso->_link = END_TSO_QUEUE;
}

609
610
611
612
613
614
static void
removeFromQueues(Capability *cap, StgTSO *tso)
{
  switch (tso->why_blocked) {

  case NotBlocked:
615
  case ThreadMigrating:
616
617
618
619
620
621
622
623
624
625
626
627
      return;

  case BlockedOnSTM:
    // Be careful: nothing to do here!  We tell the scheduler that the
    // thread is runnable and we leave it to the stack-walking code to
    // abort the transaction while unwinding the stack.  We should
    // perhaps have a debugging test to make sure that this really
    // happens and that the 'zombie' transaction does not get
    // committed.
    goto done;

  case BlockedOnMVar:
628
      removeFromMVarBlockedQueue(tso);
629
630
631
      goto done;

  case BlockedOnBlackHole:
632
      // nothing to do
633
634
      goto done;

635
636
637
638
639
640
641
642
643
  case BlockedOnMsgThrowTo:
  {
      MessageThrowTo *m = tso->block_info.throwto;
      // The message is locked by us, unless we got here via
      // deleteAllThreads(), in which case we own all the
      // capabilities.
      // ASSERT(m->header.info == &stg_WHITEHOLE_info);

      // unlock and revoke it at the same time
644
      unlockClosure((StgClosure*)m,&stg_MSG_NULL_info);
645
646
      break;
  }
647
648
649
650
651
652
653

#if !defined(THREADED_RTS)
  case BlockedOnRead:
  case BlockedOnWrite:
#if defined(mingw32_HOST_OS)
  case BlockedOnDoProc:
#endif
654
      removeThreadFromDeQueue(cap, &blocked_queue_hd, &blocked_queue_tl, tso);
655
656
657
658
659
660
661
662
663
#if defined(mingw32_HOST_OS)
      /* (Cooperatively) signal that the worker thread should abort
       * the request.
       */
      abandonWorkRequest(tso->block_info.async_result->reqID);
#endif
      goto done;

  case BlockedOnDelay:
664
        removeThreadFromQueue(cap, &sleeping_queue, tso);
665
666
667
668
	goto done;
#endif

  default:
669
      barf("removeFromQueues: %d", tso->why_blocked);
670
671
672
  }

 done:
673
674
  tso->why_blocked = NotBlocked;
  appendToRunQueue(cap, tso);
675
676
677
678
679
680
681
682
683
}

/* -----------------------------------------------------------------------------
 * raiseAsync()
 *
 * The following function implements the magic for raising an
 * asynchronous exception in an existing thread.
 *
 * We first remove the thread from any queue on which it might be
684
685
 * blocked.  The possible blockages are MVARs, BLOCKING_QUEUESs, and
 * TSO blocked_exception queues.
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
 *
 * We strip the stack down to the innermost CATCH_FRAME, building
 * thunks in the heap for all the active computations, so they can 
 * be restarted if necessary.  When we reach a CATCH_FRAME, we build
 * an application of the handler to the exception, and push it on
 * the top of the stack.
 * 
 * How exactly do we save all the active computations?  We create an
 * AP_STACK for every UpdateFrame on the stack.  Entering one of these
 * AP_STACKs pushes everything from the corresponding update frame
 * upwards onto the stack.  (Actually, it pushes everything up to the
 * next update frame plus a pointer to the next AP_STACK object.
 * Entering the next AP_STACK object pushes more onto the stack until we
 * reach the last AP_STACK object - at which point the stack should look
 * exactly as it did when we killed the TSO and we can continue
 * execution by entering the closure on top of the stack.
 *
 * We can also kill a thread entirely - this happens if either (a) the 
 * exception passed to raiseAsync is NULL, or (b) there's no
 * CATCH_FRAME on the stack.  In either case, we strip the entire
 * stack and replace the thread with a zombie.
 *
 * ToDo: in THREADED_RTS mode, this function is only safe if either
 * (a) we hold all the Capabilities (eg. in GC, or if there is only
 * one Capability), or (b) we own the Capability that the TSO is
 * currently blocked on or on the run queue of.
 *
 * -------------------------------------------------------------------------- */

static void
raiseAsync(Capability *cap, StgTSO *tso, StgClosure *exception, 
717
	   rtsBool stop_at_atomically, StgUpdateFrame *stop_here)
718
719
720
{
    StgRetInfoTable *info;
    StgPtr sp, frame;
721
    StgClosure *updatee;
722
723
    nat i;

724
725
    debugTraceCap(DEBUG_sched, cap,
                  "raising exception in thread %ld.", (long)tso->id);
726
    
727
728
729
#if defined(PROFILING)
    /* 
     * Debugging tool: on raising an  exception, show where we are.
730
     * See also Exception.cmm:stg_raisezh.
731
732
733
734
735
736
737
     * This wasn't done for asynchronous exceptions originally; see #1450 
     */
    if (RtsFlags.ProfFlags.showCCSOnException)
    {
        fprintCCS_stderr(tso->prof.CCCS);
    }
#endif
738
739
740
741
742
    // ASSUMES: the thread is not already complete or dead, or
    // ThreadRelocated.  Upper layers should deal with that.
    ASSERT(tso->what_next != ThreadComplete && 
           tso->what_next != ThreadKilled && 
           tso->what_next != ThreadRelocated);
743

744
745
746
747
    // only if we own this TSO (except that deleteThread() calls this 
    ASSERT(tso->cap == cap);

    // wake it up
748
    if (tso->why_blocked != NotBlocked) {
749
750
751
752
        tso->why_blocked = NotBlocked;
        appendToRunQueue(cap,tso);
    }        

753
    // mark it dirty; we're about to change its stack.
754
    dirty_TSO(cap, tso);
755
756
757

    sp = tso->sp;
    
758
759
760
761
762
763
    if (stop_here != NULL) {
        updatee = stop_here->updatee;
    } else {
        updatee = NULL;
    }

764
765
766
767
768
769
770
771
772
773
774
    // The stack freezing code assumes there's a closure pointer on
    // the top of the stack, so we have to arrange that this is the case...
    //
    if (sp[0] == (W_)&stg_enter_info) {
	sp++;
    } else {
	sp--;
	sp[0] = (W_)&stg_dummy_ret_closure;
    }

    frame = sp + 1;
775
    while (stop_here == NULL || frame < (StgPtr)stop_here) {
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808

	// 1. Let the top of the stack be the "current closure"
	//
	// 2. Walk up the stack until we find either an UPDATE_FRAME or a
	// CATCH_FRAME.
	//
	// 3. If it's an UPDATE_FRAME, then make an AP_STACK containing the
	// current closure applied to the chunk of stack up to (but not
	// including) the update frame.  This closure becomes the "current
	// closure".  Go back to step 2.
	//
	// 4. If it's a CATCH_FRAME, then leave the exception handler on
	// top of the stack applied to the exception.
	// 
	// 5. If it's a STOP_FRAME, then kill the thread.
        // 
        // NB: if we pass an ATOMICALLY_FRAME then abort the associated 
        // transaction
       
	info = get_ret_itbl((StgClosure *)frame);

	switch (info->i.type) {

	case UPDATE_FRAME:
	{
	    StgAP_STACK * ap;
	    nat words;
	    
	    // First build an AP_STACK consisting of the stack chunk above the
	    // current update frame, with the top word on the stack as the
	    // fun field.
	    //
	    words = frame - sp - 1;
809
	    ap = (StgAP_STACK *)allocate(cap,AP_STACK_sizeW(words));
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
	    
	    ap->size = words;
	    ap->fun  = (StgClosure *)sp[0];
	    sp++;
	    for(i=0; i < (nat)words; ++i) {
		ap->payload[i] = (StgClosure *)*sp++;
	    }
	    
	    SET_HDR(ap,&stg_AP_STACK_info,
		    ((StgClosure *)frame)->header.prof.ccs /* ToDo */); 
	    TICK_ALLOC_UP_THK(words+1,0);
	    
	    //IF_DEBUG(scheduler,
	    //	     debugBelch("sched: Updating ");
	    //	     printPtr((P_)((StgUpdateFrame *)frame)->updatee); 
	    //	     debugBelch(" with ");
	    //	     printObj((StgClosure *)ap);
	    //	);

829
830
831
832
833
834
835
836
837
838
839
            if (((StgUpdateFrame *)frame)->updatee == updatee) {
                // If this update frame points to the same closure as
                // the update frame further down the stack
                // (stop_here), then don't perform the update.  We
                // want to keep the blackhole in this case, so we can
                // detect and report the loop (#2783).
                ap = (StgAP_STACK*)updatee;
            } else {
                // Perform the update
                // TODO: this may waste some work, if the thunk has
                // already been updated by another thread.
840
841
                updateThunk(cap, tso, 
                            ((StgUpdateFrame *)frame)->updatee, (StgClosure *)ap);
842
            }
843

844
845
846
847
848
849
850
	    sp += sizeofW(StgUpdateFrame) - 1;
	    sp[0] = (W_)ap; // push onto stack
	    frame = sp + 1;
	    continue; //no need to bump frame
	}

	case STOP_FRAME:
851
	{
852
853
854
855
	    // We've stripped the entire stack, the thread is now dead.
	    tso->what_next = ThreadKilled;
	    tso->sp = frame + sizeofW(StgStopFrame);
	    return;
856
	}
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871

	case CATCH_FRAME:
	    // If we find a CATCH_FRAME, and we've got an exception to raise,
	    // then build the THUNK raise(exception), and leave it on
	    // top of the CATCH_FRAME ready to enter.
	    //
	{
	    StgCatchFrame *cf = (StgCatchFrame *)frame;
	    StgThunk *raise;
	    
	    if (exception == NULL) break;

	    // we've got an exception to raise, so let's pass it to the
	    // handler in this frame.
	    //
872
	    raise = (StgThunk *)allocate(cap,sizeofW(StgThunk)+1);
873
874
875
876
877
878
879
880
881
882
883
884
	    TICK_ALLOC_SE_THK(1,0);
	    SET_HDR(raise,&stg_raise_info,cf->header.prof.ccs);
	    raise->payload[0] = exception;
	    
	    // throw away the stack from Sp up to the CATCH_FRAME.
	    //
	    sp = frame - 1;
	    
	    /* Ensure that async excpetions are blocked now, so we don't get
	     * a surprise exception before we get around to executing the
	     * handler.
	     */
885
886
887
888
889
890
            tso->flags |= TSO_BLOCKEX;
            if ((cf->exceptions_blocked & TSO_INTERRUPTIBLE) == 0) {
                tso->flags &= ~TSO_INTERRUPTIBLE;
            } else {
                tso->flags |= TSO_INTERRUPTIBLE;
            }
891
892
893
894
895
896
897
898
899
900
901
902
903
904

	    /* Put the newly-built THUNK on top of the stack, ready to execute
	     * when the thread restarts.
	     */
	    sp[0] = (W_)raise;
	    sp[-1] = (W_)&stg_enter_info;
	    tso->sp = sp-1;
	    tso->what_next = ThreadRunGHC;
	    IF_DEBUG(sanity, checkTSO(tso));
	    return;
	}
	    
	case ATOMICALLY_FRAME:
	    if (stop_at_atomically) {
905
		ASSERT(tso->trec->enclosing_trec == NO_TREC);
906
		stmCondemnTransaction(cap, tso -> trec);
907
908
909
910
911
912
913
914
915
916
917
		tso->sp = frame - 2;
                // The ATOMICALLY_FRAME expects to be returned a
                // result from the transaction, which it stores in the
                // stack frame.  Hence we arrange to return a dummy
                // result, so that the GC doesn't get upset (#3578).
                // Perhaps a better way would be to have a different
                // ATOMICALLY_FRAME instance for condemned
                // transactions, but I don't fully understand the
                // interaction with STM invariants.
                tso->sp[1] = (W_)&stg_NO_TREC_closure;
                tso->sp[0] = (W_)&stg_gc_unpt_r1_info;
918
919
920
921
922
923
		tso->what_next = ThreadRunGHC;
		return;
	    }
	    // Not stop_at_atomically... fall through and abort the
	    // transaction.
	    
924
	case CATCH_STM_FRAME:
925
926
927
928
929
930
931
932
	case CATCH_RETRY_FRAME:
	    // IF we find an ATOMICALLY_FRAME then we abort the
	    // current transaction and propagate the exception.  In
	    // this case (unlike ordinary exceptions) we do not care
	    // whether the transaction is valid or not because its
	    // possible validity cannot have caused the exception
	    // and will not be visible after the abort.

933
		{
934
            StgTRecHeader *trec = tso -> trec;
935
            StgTRecHeader *outer = trec -> enclosing_trec;
936
937
	    debugTraceCap(DEBUG_stm, cap,
                          "found atomically block delivering async exception");
938
            stmAbortTransaction(cap, trec);
tharris@microsoft.com's avatar
tharris@microsoft.com committed
939
	    stmFreeAbortedTRec(cap, trec);
940
941
            tso -> trec = outer;
	    break;
942
	    };
943
944
945
946
947
948
949
950
951
952
953
954
955
956
	    
	default:
	    break;
	}

	// move on to the next stack frame
	frame += stack_frame_sizeW((StgClosure *)frame);
    }

    // if we got here, then we stopped at stop_here
    ASSERT(stop_here != NULL);
}