simple.c 12.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*
 * 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.
 *
 */

#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <time.h>
15
#ifndef _WIN32
16 17
#include <signal.h>
#include <pthread.h>
18
#endif
19
#include "qemu/timer.h"
20
#include "trace.h"
21
#include "trace/control.h"
22
#include "trace/simple.h"
23 24 25 26 27 28 29 30

/** 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 */
31
#define HEADER_VERSION 3
32

33 34 35 36 37 38 39 40 41 42
/** 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.
 */
43 44 45 46 47 48
#if GLIB_CHECK_VERSION(2, 32, 0)
static GMutex trace_lock;
#define lock_trace_lock() g_mutex_lock(&trace_lock)
#define unlock_trace_lock() g_mutex_unlock(&trace_lock)
#define get_trace_lock_mutex() (&trace_lock)
#else
49
static GStaticMutex trace_lock = G_STATIC_MUTEX_INIT;
50 51 52 53
#define lock_trace_lock() g_static_mutex_lock(&trace_lock)
#define unlock_trace_lock() g_static_mutex_unlock(&trace_lock)
#define get_trace_lock_mutex() g_static_mutex_get_mutex(&trace_lock)
#endif
54 55 56 57 58 59 60 61

/* g_cond_new() was deprecated in glib 2.31 but we still need to support it */
#if GLIB_CHECK_VERSION(2, 31, 0)
static GCond the_trace_available_cond;
static GCond the_trace_empty_cond;
static GCond *trace_available_cond = &the_trace_available_cond;
static GCond *trace_empty_cond = &the_trace_empty_cond;
#else
62 63
static GCond *trace_available_cond;
static GCond *trace_empty_cond;
64 65
#endif

66 67 68
static bool trace_available;
static bool trace_writeout_enabled;

69 70 71 72 73 74
enum {
    TRACE_BUF_LEN = 4096 * 64,
    TRACE_BUF_FLUSH_THRESHOLD = TRACE_BUF_LEN / 4,
};

uint8_t trace_buf[TRACE_BUF_LEN];
75
static volatile gint trace_idx;
76
static unsigned int writeout_idx;
77
static volatile gint dropped_events;
78
static uint32_t trace_pid;
79
static FILE *trace_fp;
80
static char *trace_file_name;
81

82 83 84 85 86
/* * Trace buffer entry */
typedef struct {
    uint64_t event; /*   TraceEventID */
    uint64_t timestamp_ns;
    uint32_t length;   /*    in bytes */
87
    uint32_t pid;
88
    uint64_t arguments[];
89 90 91 92 93 94
} TraceRecord;

typedef struct {
    uint64_t header_event_id; /* HEADER_EVENT_ID */
    uint64_t header_magic;    /* HEADER_MAGIC    */
    uint64_t header_version;  /* HEADER_VERSION  */
95
} TraceLogHeader;
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111


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++;
    }
}
112
/**
113 114 115 116 117 118
 * 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.
119
 */
120
static bool get_trace_record(unsigned int idx, TraceRecord **recordptr)
P
Prerna Saxena 已提交
121
{
122 123 124 125 126 127
    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)) {
128
        return false;
P
Prerna Saxena 已提交
129 130
    }

131 132 133 134 135 136 137 138 139 140 141 142 143
    smp_rmb(); /* read memory barrier before accessing record */
    /* read the record header to know record length */
    read_from_buffer(idx, &record, sizeof(TraceRecord));
    *recordptr = malloc(record.length); /* dont use g_malloc, can deadlock when traced */
    /* 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);
144
    return true;
P
Prerna Saxena 已提交
145 146
}

147 148 149 150 151 152
/**
 * Kick writeout thread
 *
 * @wait        Whether to wait for writeout thread to complete
 */
static void flush_trace_file(bool wait)
153
{
154
    lock_trace_lock();
155
    trace_available = true;
156
    g_cond_signal(trace_available_cond);
157

158
    if (wait) {
159
        g_cond_wait(trace_empty_cond, get_trace_lock_mutex());
160
    }
161

162
    unlock_trace_lock();
163 164
}

165
static void wait_for_trace_records_available(void)
166
{
167
    lock_trace_lock();
168
    while (!(trace_available && trace_writeout_enabled)) {
169
        g_cond_signal(trace_empty_cond);
170
        g_cond_wait(trace_available_cond, get_trace_lock_mutex());
171
    }
172
    trace_available = false;
173
    unlock_trace_lock();
174 175
}

176
static gpointer writeout_thread(gpointer opaque)
177
{
178 179 180 181 182 183
    TraceRecord *recordptr;
    union {
        TraceRecord rec;
        uint8_t bytes[sizeof(TraceRecord) + sizeof(uint64_t)];
    } dropped;
    unsigned int idx = 0;
184
    int dropped_count;
185
    size_t unused __attribute__ ((unused));
186 187 188 189

    for (;;) {
        wait_for_trace_records_available();

190
        if (g_atomic_int_get(&dropped_events)) {
191 192
            dropped.rec.event = DROPPED_EVENT_ID,
            dropped.rec.timestamp_ns = get_clock();
193
            dropped.rec.length = sizeof(TraceRecord) + sizeof(uint64_t),
194
            dropped.rec.pid = trace_pid;
195
            do {
196
                dropped_count = g_atomic_int_get(&dropped_events);
197 198
            } while (!g_atomic_int_compare_and_exchange(&dropped_events,
                                                        dropped_count, 0));
199
            dropped.rec.arguments[0] = dropped_count;
200
            unused = fwrite(&dropped.rec, dropped.rec.length, 1, trace_fp);
201
        }
202

203 204 205 206 207
        while (get_trace_record(idx, &recordptr)) {
            unused = fwrite(recordptr, recordptr->length, 1, trace_fp);
            writeout_idx += recordptr->length;
            free(recordptr); /* dont use g_free, can deadlock when traced */
            idx = writeout_idx % TRACE_BUF_LEN;
208
        }
209

210
        fflush(trace_fp);
211
    }
212
    return NULL;
213 214
}

215
void trace_record_write_u64(TraceBufferRecord *rec, uint64_t val)
216
{
217
    rec->rec_off = write_to_buffer(rec->rec_off, &val, sizeof(uint64_t));
218 219
}

220
void trace_record_write_str(TraceBufferRecord *rec, const char *s, uint32_t slen)
221
{
222 223 224 225
    /* 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);
226 227
}

228
int trace_record_start(TraceBufferRecord *rec, TraceEventID event, size_t datasize)
229
{
230 231
    unsigned int idx, rec_off, old_idx, new_idx;
    uint32_t rec_len = sizeof(TraceRecord) + datasize;
232
    uint64_t event_u64 = event;
233 234
    uint64_t timestamp_ns = get_clock();

235
    do {
236
        old_idx = g_atomic_int_get(&trace_idx);
237 238 239 240 241
        smp_rmb();
        new_idx = old_idx + rec_len;

        if (new_idx - writeout_idx > TRACE_BUF_LEN) {
            /* Trace Buffer Full, Event dropped ! */
242
            g_atomic_int_inc(&dropped_events);
243 244
            return -ENOSPC;
        }
245
    } while (!g_atomic_int_compare_and_exchange(&trace_idx, old_idx, new_idx));
246

247 248 249
    idx = old_idx % TRACE_BUF_LEN;

    rec_off = idx;
250
    rec_off = write_to_buffer(rec_off, &event_u64, sizeof(event_u64));
251 252
    rec_off = write_to_buffer(rec_off, &timestamp_ns, sizeof(timestamp_ns));
    rec_off = write_to_buffer(rec_off, &rec_len, sizeof(rec_len));
253
    rec_off = write_to_buffer(rec_off, &trace_pid, sizeof(trace_pid));
254 255 256 257

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

260
static void read_from_buffer(unsigned int idx, void *dataptr, size_t size)
261
{
262 263 264 265 266 267 268 269
    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++];
    }
270 271
}

272
static unsigned int write_to_buffer(unsigned int idx, void *dataptr, size_t size)
273
{
274 275 276 277 278 279 280 281 282
    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 */
283 284
}

285
void trace_record_finish(TraceBufferRecord *rec)
286
{
287 288
    TraceRecord record;
    read_from_buffer(rec->tbuf_idx, &record, sizeof(TraceRecord));
289
    smp_wmb(); /* write barrier before marking as valid */
290 291
    record.event |= TRACE_RECORD_VALID;
    write_to_buffer(rec->tbuf_idx, &record, sizeof(TraceRecord));
292

293
    if (((unsigned int)g_atomic_int_get(&trace_idx) - writeout_idx)
294
        > TRACE_BUF_FLUSH_THRESHOLD) {
295 296
        flush_trace_file(false);
    }
297 298
}

299 300 301 302 303 304 305 306 307 308 309 310
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) {
311
        static const TraceLogHeader header = {
312 313 314 315
            .header_event_id = HEADER_EVENT_ID,
            .header_magic = HEADER_MAGIC,
            /* Older log readers will check for version at next location */
            .header_version = HEADER_VERSION,
316 317
        };

318
        trace_fp = fopen(trace_file_name, "wb");
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
        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;
    }
}

338
/**
339 340 341 342
 * Set the name of a trace file
 *
 * @file        The trace file name or NULL for the default name-<pid> set at
 *              config time
343
 */
344
bool st_set_trace_file(const char *file)
345
{
346 347
    st_set_trace_file_enabled(false);

348
    g_free(trace_file_name);
349 350

    if (!file) {
351
        trace_file_name = g_strdup_printf(CONFIG_TRACE_FILE, getpid());
352
    } else {
353
        trace_file_name = g_strdup_printf("%s", file);
354 355 356 357 358 359 360 361 362 363
    }

    st_set_trace_file_enabled(true);
    return 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");
364
}
365

366 367 368 369 370 371
void st_flush_trace_buffer(void)
{
    flush_trace_file(true);
}

void trace_print_events(FILE *stream, fprintf_function stream_printf)
372 373 374
{
    unsigned int i;

375 376
    for (i = 0; i < trace_event_count(); i++) {
        TraceEvent *ev = trace_event_id(i);
377
        stream_printf(stream, "%s [Event ID %u] : state %u\n",
378
                      trace_event_get_name(ev), i, trace_event_get_state_dynamic(ev));
379 380 381
    }
}

382
void trace_event_set_state_dynamic_backend(TraceEvent *ev, bool state)
383
{
384
    ev->dstate = state;
385 386
}

387 388 389 390 391 392
/* 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)
393
{
394 395
    GThread *thread;
#ifndef _WIN32
396
    sigset_t set, oldset;
397

398 399
    sigfillset(&set);
    pthread_sigmask(SIG_SETMASK, &set, &oldset);
400
#endif
401 402 403 404

#if GLIB_CHECK_VERSION(2, 31, 0)
    thread = g_thread_new("trace-thread", fn, NULL);
#else
405
    thread = g_thread_create(fn, NULL, FALSE, NULL);
406 407
#endif

408
#ifndef _WIN32
409
    pthread_sigmask(SIG_SETMASK, &oldset, NULL);
410
#endif
411

412 413 414 415 416 417 418
    return thread;
}

bool trace_backend_init(const char *events, const char *file)
{
    GThread *thread;

419 420
    trace_pid = getpid();

421
#if !GLIB_CHECK_VERSION(2, 31, 0)
422 423
    trace_available_cond = g_cond_new();
    trace_empty_cond = g_cond_new();
424
#endif
425 426 427

    thread = trace_thread_create(writeout_thread);
    if (!thread) {
428
        fprintf(stderr, "warning: unable to initialize simple trace backend\n");
429
        return false;
430
    }
431

432 433 434
    atexit(st_flush_trace_buffer);
    trace_backend_init_events(events);
    st_set_trace_file(file);
435
    return true;
436
}