simple.c 10.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/*
 * Simple trace backend
 *
 * Copyright IBM, Corp. 2010
 *
 * This work is licensed under the terms of the GNU GPL, version 2.  See
 * the COPYING file in the top-level directory.
 *
 */

Peter Maydell's avatar
Peter Maydell committed
11
#include "qemu/osdep.h"
12
#ifndef _WIN32
13
#include <pthread.h>
14
#endif
15
#include "qemu/timer.h"
16
#include "trace.h"
17
#include "trace/control.h"
18
#include "trace/simple.h"
19 20 21 22 23 24 25 26

/** Trace file header event ID */
#define HEADER_EVENT_ID (~(uint64_t)0) /* avoids conflicting with TraceEventIDs */

/** Trace file magic number */
#define HEADER_MAGIC 0xf2b177cb0aa429b4ULL

/** Trace file version number, bump if format changes */
27
#define HEADER_VERSION 3
28

29 30 31 32 33 34 35 36 37 38
/** Records were dropped event ID */
#define DROPPED_EVENT_ID (~(uint64_t)0 - 1)

/** Trace record is valid */
#define TRACE_RECORD_VALID ((uint64_t)1 << 63)

/*
 * Trace records are written out by a dedicated thread.  The thread waits for
 * records to become available, writes them out, and then waits again.
 */
39 40 41
static CompatGMutex trace_lock;
static CompatGCond trace_available_cond;
static CompatGCond trace_empty_cond;
42

43 44 45
static bool trace_available;
static bool trace_writeout_enabled;

46 47 48 49 50 51
enum {
    TRACE_BUF_LEN = 4096 * 64,
    TRACE_BUF_FLUSH_THRESHOLD = TRACE_BUF_LEN / 4,
};

uint8_t trace_buf[TRACE_BUF_LEN];
52
static volatile gint trace_idx;
53
static unsigned int writeout_idx;
54
static volatile gint dropped_events;
55
static uint32_t trace_pid;
56
static FILE *trace_fp;
57
static char *trace_file_name;
58

59 60 61 62 63
/* * Trace buffer entry */
typedef struct {
    uint64_t event; /*   TraceEventID */
    uint64_t timestamp_ns;
    uint32_t length;   /*    in bytes */
64
    uint32_t pid;
65
    uint64_t arguments[];
66 67 68 69 70 71
} TraceRecord;

typedef struct {
    uint64_t header_event_id; /* HEADER_EVENT_ID */
    uint64_t header_magic;    /* HEADER_MAGIC    */
    uint64_t header_version;  /* HEADER_VERSION  */
72
} TraceLogHeader;
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88


static void read_from_buffer(unsigned int idx, void *dataptr, size_t size);
static unsigned int write_to_buffer(unsigned int idx, void *dataptr, size_t size);

static void clear_buffer_range(unsigned int idx, size_t len)
{
    uint32_t num = 0;
    while (num < len) {
        if (idx >= TRACE_BUF_LEN) {
            idx = idx % TRACE_BUF_LEN;
        }
        trace_buf[idx++] = 0;
        num++;
    }
}
89
/**
90 91 92 93 94 95
 * Read a trace record from the trace buffer
 *
 * @idx         Trace buffer index
 * @record      Trace record to fill
 *
 * Returns false if the record is not valid.
96
 */
97
static bool get_trace_record(unsigned int idx, TraceRecord **recordptr)
98
{
99 100 101 102 103 104
    uint64_t event_flag = 0;
    TraceRecord record;
    /* read the event flag to see if its a valid record */
    read_from_buffer(idx, &record, sizeof(event_flag));

    if (!(record.event & TRACE_RECORD_VALID)) {
105
        return false;
106 107
    }

108 109 110
    smp_rmb(); /* read memory barrier before accessing record */
    /* read the record header to know record length */
    read_from_buffer(idx, &record, sizeof(TraceRecord));
111
    *recordptr = malloc(record.length); /* don't use g_malloc, can deadlock when traced */
112 113 114 115 116 117 118 119 120
    /* make a copy of record to avoid being overwritten */
    read_from_buffer(idx, *recordptr, record.length);
    smp_rmb(); /* memory barrier before clearing valid flag */
    (*recordptr)->event &= ~TRACE_RECORD_VALID;
    /* clear the trace buffer range for consumed record otherwise any byte
     * with its MSB set may be considered as a valid event id when the writer
     * thread crosses this range of buffer again.
     */
    clear_buffer_range(idx, record.length);
121
    return true;
122 123
}

124 125 126 127 128 129
/**
 * Kick writeout thread
 *
 * @wait        Whether to wait for writeout thread to complete
 */
static void flush_trace_file(bool wait)
130
{
131
    g_mutex_lock(&trace_lock);
132
    trace_available = true;
133
    g_cond_signal(&trace_available_cond);
134

135
    if (wait) {
136
        g_cond_wait(&trace_empty_cond, &trace_lock);
137
    }
138

139
    g_mutex_unlock(&trace_lock);
140 141
}

142
static void wait_for_trace_records_available(void)
143
{
144
    g_mutex_lock(&trace_lock);
145
    while (!(trace_available && trace_writeout_enabled)) {
146 147
        g_cond_signal(&trace_empty_cond);
        g_cond_wait(&trace_available_cond, &trace_lock);
148
    }
149
    trace_available = false;
150
    g_mutex_unlock(&trace_lock);
151 152
}

153
static gpointer writeout_thread(gpointer opaque)
154
{
155 156 157 158 159 160
    TraceRecord *recordptr;
    union {
        TraceRecord rec;
        uint8_t bytes[sizeof(TraceRecord) + sizeof(uint64_t)];
    } dropped;
    unsigned int idx = 0;
161
    int dropped_count;
162
    size_t unused __attribute__ ((unused));
163 164 165 166

    for (;;) {
        wait_for_trace_records_available();

167
        if (g_atomic_int_get(&dropped_events)) {
168 169
            dropped.rec.event = DROPPED_EVENT_ID,
            dropped.rec.timestamp_ns = get_clock();
170
            dropped.rec.length = sizeof(TraceRecord) + sizeof(uint64_t),
171
            dropped.rec.pid = trace_pid;
172
            do {
173
                dropped_count = g_atomic_int_get(&dropped_events);
174 175
            } while (!g_atomic_int_compare_and_exchange(&dropped_events,
                                                        dropped_count, 0));
176
            dropped.rec.arguments[0] = dropped_count;
177
            unused = fwrite(&dropped.rec, dropped.rec.length, 1, trace_fp);
178
        }
179

180 181 182
        while (get_trace_record(idx, &recordptr)) {
            unused = fwrite(recordptr, recordptr->length, 1, trace_fp);
            writeout_idx += recordptr->length;
183
            free(recordptr); /* don't use g_free, can deadlock when traced */
184
            idx = writeout_idx % TRACE_BUF_LEN;
185
        }
186

187
        fflush(trace_fp);
188
    }
189
    return NULL;
190 191
}

192
void trace_record_write_u64(TraceBufferRecord *rec, uint64_t val)
193
{
194
    rec->rec_off = write_to_buffer(rec->rec_off, &val, sizeof(uint64_t));
195 196
}

197
void trace_record_write_str(TraceBufferRecord *rec, const char *s, uint32_t slen)
198
{
199 200 201 202
    /* Write string length first */
    rec->rec_off = write_to_buffer(rec->rec_off, &slen, sizeof(slen));
    /* Write actual string now */
    rec->rec_off = write_to_buffer(rec->rec_off, (void*)s, slen);
203 204
}

205
int trace_record_start(TraceBufferRecord *rec, TraceEventID event, size_t datasize)
206
{
207 208
    unsigned int idx, rec_off, old_idx, new_idx;
    uint32_t rec_len = sizeof(TraceRecord) + datasize;
209
    uint64_t event_u64 = event;
210 211
    uint64_t timestamp_ns = get_clock();

212
    do {
213
        old_idx = g_atomic_int_get(&trace_idx);
214 215 216 217 218
        smp_rmb();
        new_idx = old_idx + rec_len;

        if (new_idx - writeout_idx > TRACE_BUF_LEN) {
            /* Trace Buffer Full, Event dropped ! */
219
            g_atomic_int_inc(&dropped_events);
220 221
            return -ENOSPC;
        }
222
    } while (!g_atomic_int_compare_and_exchange(&trace_idx, old_idx, new_idx));
223

224 225 226
    idx = old_idx % TRACE_BUF_LEN;

    rec_off = idx;
227
    rec_off = write_to_buffer(rec_off, &event_u64, sizeof(event_u64));
228 229
    rec_off = write_to_buffer(rec_off, &timestamp_ns, sizeof(timestamp_ns));
    rec_off = write_to_buffer(rec_off, &rec_len, sizeof(rec_len));
230
    rec_off = write_to_buffer(rec_off, &trace_pid, sizeof(trace_pid));
231 232 233 234

    rec->tbuf_idx = idx;
    rec->rec_off  = (idx + sizeof(TraceRecord)) % TRACE_BUF_LEN;
    return 0;
235 236
}

237
static void read_from_buffer(unsigned int idx, void *dataptr, size_t size)
238
{
239 240 241 242 243 244 245 246
    uint8_t *data_ptr = dataptr;
    uint32_t x = 0;
    while (x < size) {
        if (idx >= TRACE_BUF_LEN) {
            idx = idx % TRACE_BUF_LEN;
        }
        data_ptr[x++] = trace_buf[idx++];
    }
247 248
}

249
static unsigned int write_to_buffer(unsigned int idx, void *dataptr, size_t size)
250
{
251 252 253 254 255 256 257 258 259
    uint8_t *data_ptr = dataptr;
    uint32_t x = 0;
    while (x < size) {
        if (idx >= TRACE_BUF_LEN) {
            idx = idx % TRACE_BUF_LEN;
        }
        trace_buf[idx++] = data_ptr[x++];
    }
    return idx; /* most callers wants to know where to write next */
260 261
}

262
void trace_record_finish(TraceBufferRecord *rec)
263
{
264 265
    TraceRecord record;
    read_from_buffer(rec->tbuf_idx, &record, sizeof(TraceRecord));
266
    smp_wmb(); /* write barrier before marking as valid */
267 268
    record.event |= TRACE_RECORD_VALID;
    write_to_buffer(rec->tbuf_idx, &record, sizeof(TraceRecord));
269

270
    if (((unsigned int)g_atomic_int_get(&trace_idx) - writeout_idx)
271
        > TRACE_BUF_FLUSH_THRESHOLD) {
272 273
        flush_trace_file(false);
    }
274 275
}

276 277 278 279 280 281 282 283 284 285 286 287
void st_set_trace_file_enabled(bool enable)
{
    if (enable == !!trace_fp) {
        return; /* no change */
    }

    /* Halt trace writeout */
    flush_trace_file(true);
    trace_writeout_enabled = false;
    flush_trace_file(true);

    if (enable) {
288
        static const TraceLogHeader header = {
289 290 291 292
            .header_event_id = HEADER_EVENT_ID,
            .header_magic = HEADER_MAGIC,
            /* Older log readers will check for version at next location */
            .header_version = HEADER_VERSION,
293 294
        };

295
        trace_fp = fopen(trace_file_name, "wb");
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
        if (!trace_fp) {
            return;
        }

        if (fwrite(&header, sizeof header, 1, trace_fp) != 1) {
            fclose(trace_fp);
            trace_fp = NULL;
            return;
        }

        /* Resume trace writeout */
        trace_writeout_enabled = true;
        flush_trace_file(false);
    } else {
        fclose(trace_fp);
        trace_fp = NULL;
    }
}

315
/**
316 317 318 319
 * Set the name of a trace file
 *
 * @file        The trace file name or NULL for the default name-<pid> set at
 *              config time
320
 */
321
void st_set_trace_file(const char *file)
322
{
323 324
    st_set_trace_file_enabled(false);

325
    g_free(trace_file_name);
326 327

    if (!file) {
328 329
        /* Type cast needed for Windows where getpid() returns an int. */
        trace_file_name = g_strdup_printf(CONFIG_TRACE_FILE, (pid_t)getpid());
330
    } else {
331
        trace_file_name = g_strdup_printf("%s", file);
332 333 334 335 336 337 338 339 340
    }

    st_set_trace_file_enabled(true);
}

void st_print_trace_file_status(FILE *stream, int (*stream_printf)(FILE *stream, const char *fmt, ...))
{
    stream_printf(stream, "Trace file \"%s\" %s.\n",
                  trace_file_name, trace_fp ? "on" : "off");
341
}
342

343 344 345 346 347
void st_flush_trace_buffer(void)
{
    flush_trace_file(true);
}

348 349 350 351 352 353
/* Helper function to create a thread with signals blocked.  Use glib's
 * portable threads since QEMU abstractions cannot be used due to reentrancy in
 * the tracer.  Also note the signal masking on POSIX hosts so that the thread
 * does not steal signals when the rest of the program wants them blocked.
 */
static GThread *trace_thread_create(GThreadFunc fn)
354
{
355 356
    GThread *thread;
#ifndef _WIN32
357
    sigset_t set, oldset;
358

359 360
    sigfillset(&set);
    pthread_sigmask(SIG_SETMASK, &set, &oldset);
361
#endif
362 363 364

    thread = g_thread_new("trace-thread", fn, NULL);

365
#ifndef _WIN32
366
    pthread_sigmask(SIG_SETMASK, &oldset, NULL);
367
#endif
368

369 370 371
    return thread;
}

372
bool st_init(void)
373 374 375
{
    GThread *thread;

376 377
    trace_pid = getpid();

378 379
    thread = trace_thread_create(writeout_thread);
    if (!thread) {
380
        fprintf(stderr, "warning: unable to initialize simple trace backend\n");
381
        return false;
382
    }
383

384
    atexit(st_flush_trace_buffer);
385
    return true;
386
}