size_t last_branch_pos;
        union perf_event *event_buf;
        struct thread *thread;
+       struct thread *prev_packet_thread;
        struct branch_stack *last_branch;
        struct branch_stack *last_branch_rb;
        struct cs_etm_packet *prev_packet;
        tidq->trace_chan_id = trace_chan_id;
        tidq->thread = machine__findnew_thread(&etm->session->machines.host, -1,
                                               queue->tid);
+       tidq->prev_packet_thread = machine__idle_thread(&etm->session->machines.host);
 
        tidq->packet = zalloc(sizeof(struct cs_etm_packet));
        if (!tidq->packet)
                /*
                 * Swap PACKET with PREV_PACKET: PACKET becomes PREV_PACKET for
                 * the next incoming packet.
+                *
+                * Threads and exception levels are also tracked for both the
+                * previous and current packets. This is because the previous
+                * packet is used for the 'from' IP for branch samples, so the
+                * thread at that time must also be assigned to that sample.
+                * Across discontinuity packets the thread can change, so by
+                * tracking the thread for the previous packet the branch sample
+                * will have the correct info.
                 */
                tmp = tidq->packet;
                tidq->packet = tidq->prev_packet;
                tidq->prev_packet = tmp;
+               thread__put(tidq->prev_packet_thread);
+               tidq->prev_packet_thread = thread__get(tidq->thread);
        }
 }
 
                /* Free this traceid_queue from the array */
                tidq = etmq->traceid_queues[idx];
                thread__zput(tidq->thread);
+               thread__zput(tidq->prev_packet_thread);
                zfree(&tidq->event_buf);
                zfree(&tidq->last_branch);
                zfree(&tidq->last_branch_rb);
        sample.time = cs_etm__resolve_sample_time(etmq, tidq);
 
        sample.ip = ip;
-       sample.pid = thread__pid(tidq->thread);
-       sample.tid = thread__tid(tidq->thread);
+       sample.pid = thread__pid(tidq->prev_packet_thread);
+       sample.tid = thread__tid(tidq->prev_packet_thread);
        sample.addr = cs_etm__first_executed_instr(tidq->packet);
        sample.id = etmq->etm->branches_id;
        sample.stream_id = etmq->etm->branches_id;