1 /* $FreeBSD$ */ 2 #include <sys/types.h> 3 #include <sys/stat.h> 4 #include <sys/ioctl.h> 5 #include <sys/mman.h> 6 #include <fcntl.h> 7 #include <stdlib.h> 8 #include <stdio.h> 9 #include <stdarg.h> 10 #include <string.h> 11 #include <unistd.h> 12 #include <errno.h> 13 #include <net/netmap_user.h> 14 #define LIBNETMAP_NOTHREADSAFE 15 #include "libnetmap.h" 16 17 static void 18 nmctx_default_error(struct nmctx *ctx, const char *errmsg) 19 { 20 fprintf(stderr, "%s\n", errmsg); 21 } 22 23 static void * 24 nmctx_default_malloc(struct nmctx *ctx, size_t sz) 25 { 26 (void)ctx; 27 return malloc(sz); 28 } 29 30 static void 31 nmctx_default_free(struct nmctx *ctx, void *p) 32 { 33 (void)ctx; 34 free(p); 35 } 36 37 static struct nmctx nmctx_global = { 38 .verbose = 1, 39 .error = nmctx_default_error, 40 .malloc = nmctx_default_malloc, 41 .free = nmctx_default_free, 42 .lock = NULL, 43 }; 44 45 static struct nmctx *nmctx_default = &nmctx_global; 46 47 struct nmctx * 48 nmctx_get(void) 49 { 50 return nmctx_default; 51 } 52 53 struct nmctx * 54 nmctx_set_default(struct nmctx *ctx) 55 { 56 struct nmctx *old = nmctx_default; 57 nmctx_default = ctx; 58 return old; 59 } 60 61 #define MAXERRMSG 1000 62 void 63 nmctx_ferror(struct nmctx *ctx, const char *fmt, ...) 64 { 65 char errmsg[MAXERRMSG]; 66 va_list ap; 67 int rv; 68 69 if (!ctx->verbose) 70 return; 71 72 va_start(ap, fmt); 73 rv = vsnprintf(errmsg, MAXERRMSG, fmt, ap); 74 va_end(ap); 75 76 if (rv > 0) { 77 if (rv < MAXERRMSG) { 78 ctx->error(ctx, errmsg); 79 } else { 80 ctx->error(ctx, "error message too long"); 81 } 82 } else { 83 ctx->error(ctx, "internal error"); 84 } 85 } 86 87 void * 88 nmctx_malloc(struct nmctx *ctx, size_t sz) 89 { 90 return ctx->malloc(ctx, sz); 91 } 92 93 void 94 nmctx_free(struct nmctx *ctx, void *p) 95 { 96 ctx->free(ctx, p); 97 } 98 99 void 100 nmctx_lock(struct nmctx *ctx) 101 { 102 if (ctx->lock != NULL) 103 ctx->lock(ctx, 1); 104 } 105 106 void 107 nmctx_unlock(struct nmctx *ctx) 108 { 109 if (ctx->lock != NULL) 110 ctx->lock(ctx, 0); 111 } 112