Index: head/cddl/contrib/opensolaris/cmd/lockstat/lockstat.c =================================================================== --- head/cddl/contrib/opensolaris/cmd/lockstat/lockstat.c (revision 351360) +++ head/cddl/contrib/opensolaris/cmd/lockstat/lockstat.c (revision 351361) @@ -1,1997 +1,2001 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef illumos #define GETOPT_EOF EOF #else #include #include #define mergesort(a, b, c, d) lsmergesort(a, b, c, d) #define GETOPT_EOF (-1) typedef uintptr_t pc_t; #endif #define LOCKSTAT_OPTSTR "x:bths:n:d:i:l:f:e:ckwWgCHEATID:RpPo:V" #define LS_MAX_STACK_DEPTH 50 #define LS_MAX_EVENTS 64 typedef struct lsrec { struct lsrec *ls_next; /* next in hash chain */ #ifdef illumos uintptr_t ls_lock; /* lock address */ #else char *ls_lock; /* lock name */ #endif uintptr_t ls_caller; /* caller address */ uint32_t ls_count; /* cumulative event count */ uint32_t ls_event; /* type of event */ uintptr_t ls_refcnt; /* cumulative reference count */ uint64_t ls_time; /* cumulative event duration */ uint32_t ls_hist[64]; /* log2(duration) histogram */ uintptr_t ls_stack[LS_MAX_STACK_DEPTH]; } lsrec_t; typedef struct lsdata { struct lsrec *lsd_next; /* next available */ int lsd_count; /* number of records */ } lsdata_t; /* * Definitions for the types of experiments which can be run. They are * listed in increasing order of memory cost and processing time cost. * The numerical value of each type is the number of bytes needed per record. */ #define LS_BASIC offsetof(lsrec_t, ls_time) #define LS_TIME offsetof(lsrec_t, ls_hist[0]) #define LS_HIST offsetof(lsrec_t, ls_stack[0]) #define LS_STACK(depth) offsetof(lsrec_t, ls_stack[depth]) static void report_stats(FILE *, lsrec_t **, size_t, uint64_t, uint64_t); static void report_trace(FILE *, lsrec_t **); extern int symtab_init(void); extern char *addr_to_sym(uintptr_t, uintptr_t *, size_t *); extern uintptr_t sym_to_addr(char *name); extern size_t sym_size(char *name); extern char *strtok_r(char *, const char *, char **); #define DEFAULT_NRECS 10000 #define DEFAULT_HZ 97 #define MAX_HZ 1000 #define MIN_AGGSIZE (16 * 1024) #define MAX_AGGSIZE (32 * 1024 * 1024) static int g_stkdepth; static int g_topn = INT_MAX; static hrtime_t g_elapsed; static int g_rates = 0; static int g_pflag = 0; static int g_Pflag = 0; static int g_wflag = 0; static int g_Wflag = 0; static int g_cflag = 0; static int g_kflag = 0; static int g_gflag = 0; static int g_Vflag = 0; static int g_tracing = 0; static size_t g_recsize; static size_t g_nrecs; static int g_nrecs_used; static uchar_t g_enabled[LS_MAX_EVENTS]; static hrtime_t g_min_duration[LS_MAX_EVENTS]; static dtrace_hdl_t *g_dtp; static char *g_predicate; static char *g_ipredicate; static char *g_prog; static int g_proglen; static int g_dropped; typedef struct ls_event_info { char ev_type; char ev_lhdr[20]; char ev_desc[80]; char ev_units[10]; char ev_name[DTRACE_NAMELEN]; char *ev_predicate; char *ev_acquire; } ls_event_info_t; static ls_event_info_t g_event_info[LS_MAX_EVENTS] = { { 'C', "Lock", "Adaptive mutex spin", "nsec", "lockstat:::adaptive-spin" }, { 'C', "Lock", "Adaptive mutex block", "nsec", "lockstat:::adaptive-block" }, { 'C', "Lock", "Spin lock spin", "nsec", "lockstat:::spin-spin" }, { 'C', "Lock", "Thread lock spin", "nsec", "lockstat:::thread-spin" }, { 'C', "Lock", "R/W writer blocked by writer", "nsec", "lockstat:::rw-block", "arg2 == 0 && arg3 == 1" }, { 'C', "Lock", "R/W writer blocked by readers", "nsec", "lockstat:::rw-block", "arg2 == 0 && arg3 == 0 && arg4" }, { 'C', "Lock", "R/W reader blocked by writer", "nsec", - "lockstat:::rw-block", "arg2 != 0 && arg3 == 1" }, + "lockstat:::rw-block", "arg2 == 1 && arg3 == 1" }, { 'C', "Lock", "R/W reader blocked by write wanted", "nsec", - "lockstat:::rw-block", "arg2 != 0 && arg3 == 0 && arg4" }, + "lockstat:::rw-block", "arg2 == 1 && arg3 == 0 && arg4" }, { 'C', "Lock", "R/W writer spin on writer", "nsec", "lockstat:::rw-spin", "arg2 == 0 && arg3 == 1" }, { 'C', "Lock", "R/W writer spin on readers", "nsec", "lockstat:::rw-spin", "arg2 == 0 && arg3 == 0 && arg4" }, { 'C', "Lock", "R/W reader spin on writer", "nsec", - "lockstat:::rw-spin", "arg2 != 0 && arg3 == 1" }, + "lockstat:::rw-spin", "arg2 == 1 && arg3 == 1" }, { 'C', "Lock", "R/W reader spin on write wanted", "nsec", - "lockstat:::rw-spin", "arg2 != 0 && arg3 == 0 && arg4" }, + "lockstat:::rw-spin", "arg2 == 1 && arg3 == 0 && arg4" }, { 'C', "Lock", "SX exclusive block", "nsec", "lockstat:::sx-block", "arg2 == 0" }, { 'C', "Lock", "SX shared block", "nsec", - "lockstat:::sx-block", "arg2 != 0" }, + "lockstat:::sx-block", "arg2 == 1" }, { 'C', "Lock", "SX exclusive spin", "nsec", "lockstat:::sx-spin", "arg2 == 0" }, { 'C', "Lock", "SX shared spin", "nsec", - "lockstat:::sx-spin", "arg2 != 0" }, - { 'C', "Lock", "Unknown event (type 16)", "units" }, - { 'C', "Lock", "Unknown event (type 17)", "units" }, - { 'C', "Lock", "Unknown event (type 18)", "units" }, - { 'C', "Lock", "Unknown event (type 19)", "units" }, + "lockstat:::sx-spin", "arg2 == 1" }, + { 'C', "Lock", "lockmgr writer blocked by writer", "nsec", + "lockstat:::lockmgr-block", "arg2 == 0 && arg3 == 1" }, + { 'C', "Lock", "lockmgr writer blocked by readers", "nsec", + "lockstat:::lockmgr-block", "arg2 == 0 && arg3 == 0 && arg4" }, + { 'C', "Lock", "lockmgr reader blocked by writer", "nsec", + "lockstat:::lockmgr-block", "arg2 == 1 && arg3 == 1" }, + { 'C', "Lock", "lockmgr reader blocked by write wanted", "nsec", + "lockstat:::lockmgr-block", "arg2 == 1 && arg3 == 0 && arg4" }, { 'C', "Lock", "Unknown event (type 20)", "units" }, { 'C', "Lock", "Unknown event (type 21)", "units" }, { 'C', "Lock", "Unknown event (type 22)", "units" }, { 'C', "Lock", "Unknown event (type 23)", "units" }, { 'C', "Lock", "Unknown event (type 24)", "units" }, { 'C', "Lock", "Unknown event (type 25)", "units" }, { 'C', "Lock", "Unknown event (type 26)", "units" }, { 'C', "Lock", "Unknown event (type 27)", "units" }, { 'C', "Lock", "Unknown event (type 28)", "units" }, { 'C', "Lock", "Unknown event (type 29)", "units" }, { 'C', "Lock", "Unknown event (type 30)", "units" }, { 'C', "Lock", "Unknown event (type 31)", "units" }, { 'H', "Lock", "Adaptive mutex hold", "nsec", "lockstat:::adaptive-release", NULL, "lockstat:::adaptive-acquire" }, { 'H', "Lock", "Spin lock hold", "nsec", "lockstat:::spin-release", NULL, "lockstat:::spin-acquire" }, { 'H', "Lock", "R/W writer hold", "nsec", "lockstat:::rw-release", "arg1 == 0", "lockstat:::rw-acquire" }, { 'H', "Lock", "R/W reader hold", "nsec", "lockstat:::rw-release", "arg1 == 1", "lockstat:::rw-acquire" }, { 'H', "Lock", "SX shared hold", "nsec", "lockstat:::sx-release", "arg1 == 1", "lockstat:::sx-acquire" }, { 'H', "Lock", "SX exclusive hold", "nsec", "lockstat:::sx-release", "arg1 == 0", "lockstat:::sx-acquire" }, { 'H', "Lock", "Unknown event (type 38)", "units" }, { 'H', "Lock", "Unknown event (type 39)", "units" }, { 'H', "Lock", "Unknown event (type 40)", "units" }, { 'H', "Lock", "Unknown event (type 41)", "units" }, { 'H', "Lock", "Unknown event (type 42)", "units" }, { 'H', "Lock", "Unknown event (type 43)", "units" }, { 'H', "Lock", "Unknown event (type 44)", "units" }, { 'H', "Lock", "Unknown event (type 45)", "units" }, { 'H', "Lock", "Unknown event (type 46)", "units" }, { 'H', "Lock", "Unknown event (type 47)", "units" }, { 'H', "Lock", "Unknown event (type 48)", "units" }, { 'H', "Lock", "Unknown event (type 49)", "units" }, { 'H', "Lock", "Unknown event (type 50)", "units" }, { 'H', "Lock", "Unknown event (type 51)", "units" }, { 'H', "Lock", "Unknown event (type 52)", "units" }, { 'H', "Lock", "Unknown event (type 53)", "units" }, { 'H', "Lock", "Unknown event (type 54)", "units" }, { 'H', "Lock", "Unknown event (type 55)", "units" }, #ifdef illumos { 'I', "CPU+PIL", "Profiling interrupt", "nsec", #else { 'I', "CPU+Pri_Class", "Profiling interrupt", "nsec", #endif "profile:::profile-97", NULL }, { 'I', "Lock", "Unknown event (type 57)", "units" }, { 'I', "Lock", "Unknown event (type 58)", "units" }, { 'I', "Lock", "Unknown event (type 59)", "units" }, { 'E', "Lock", "Recursive lock entry detected", "(N/A)", "lockstat:::rw-release", NULL, "lockstat:::rw-acquire" }, { 'E', "Lock", "Lockstat enter failure", "(N/A)" }, { 'E', "Lock", "Lockstat exit failure", "nsec" }, { 'E', "Lock", "Lockstat record failure", "(N/A)" }, }; #ifndef illumos static char *g_pri_class[] = { "", "Intr", "RealT", "TShar", "Idle" }; #endif static void fail(int do_perror, const char *message, ...) { va_list args; int save_errno = errno; va_start(args, message); (void) fprintf(stderr, "lockstat: "); (void) vfprintf(stderr, message, args); va_end(args); if (do_perror) (void) fprintf(stderr, ": %s", strerror(save_errno)); (void) fprintf(stderr, "\n"); exit(2); } static void dfail(const char *message, ...) { va_list args; va_start(args, message); (void) fprintf(stderr, "lockstat: "); (void) vfprintf(stderr, message, args); va_end(args); (void) fprintf(stderr, ": %s\n", dtrace_errmsg(g_dtp, dtrace_errno(g_dtp))); exit(2); } static void show_events(char event_type, char *desc) { int i, first = -1, last; for (i = 0; i < LS_MAX_EVENTS; i++) { ls_event_info_t *evp = &g_event_info[i]; if (evp->ev_type != event_type || strncmp(evp->ev_desc, "Unknown event", 13) == 0) continue; if (first == -1) first = i; last = i; } (void) fprintf(stderr, "\n%s events (lockstat -%c or lockstat -e %d-%d):\n\n", desc, event_type, first, last); for (i = first; i <= last; i++) (void) fprintf(stderr, "%4d = %s\n", i, g_event_info[i].ev_desc); } static void usage(void) { (void) fprintf(stderr, "Usage: lockstat [options] command [args]\n" "\nGeneral options:\n\n" " -V print the corresponding D program\n" "\nEvent selection options:\n\n" " -C watch contention events [on by default]\n" " -E watch error events [off by default]\n" " -H watch hold events [off by default]\n" " -I watch interrupt events [off by default]\n" " -A watch all lock events [equivalent to -CH]\n" " -e event_list only watch the specified events (shown below);\n" " is a comma-separated list of\n" " events or ranges of events, e.g. 1,4-7,35\n" " -i rate interrupt rate for -I [default: %d Hz]\n" "\nData gathering options:\n\n" " -b basic statistics (lock, caller, event count)\n" " -t timing for all events [default]\n" " -h histograms for event times\n" " -s depth stack traces deep\n" " -x opt[=val] enable or modify DTrace options\n" "\nData filtering options:\n\n" " -n nrecords maximum number of data records [default: %d]\n" " -l lock[,size] only watch , which can be specified as a\n" " symbolic name or hex address; defaults\n" " to the ELF symbol size if available, 1 if not\n" " -f func[,size] only watch events generated by \n" " -d duration only watch events longer than \n" " -T trace (rather than sample) events\n" "\nData reporting options:\n\n" #ifdef illumos " -c coalesce lock data for arrays like pse_mutex[]\n" #endif " -k coalesce PCs within functions\n" " -g show total events generated by function\n" " -w wherever: don't distinguish events by caller\n" " -W whichever: don't distinguish events by lock\n" " -R display rates rather than counts\n" " -p parsable output format (awk(1)-friendly)\n" " -P sort lock data by (count * avg_time) product\n" " -D n only display top events of each type\n" " -o filename send output to \n", DEFAULT_HZ, DEFAULT_NRECS); show_events('C', "Contention"); show_events('H', "Hold-time"); show_events('I', "Interrupt"); show_events('E', "Error"); (void) fprintf(stderr, "\n"); exit(1); } static int lockcmp(lsrec_t *a, lsrec_t *b) { int i; if (a->ls_event < b->ls_event) return (-1); if (a->ls_event > b->ls_event) return (1); for (i = g_stkdepth - 1; i >= 0; i--) { if (a->ls_stack[i] < b->ls_stack[i]) return (-1); if (a->ls_stack[i] > b->ls_stack[i]) return (1); } if (a->ls_caller < b->ls_caller) return (-1); if (a->ls_caller > b->ls_caller) return (1); #ifdef illumos if (a->ls_lock < b->ls_lock) return (-1); if (a->ls_lock > b->ls_lock) return (1); return (0); #else return (strcmp(a->ls_lock, b->ls_lock)); #endif } static int countcmp(lsrec_t *a, lsrec_t *b) { if (a->ls_event < b->ls_event) return (-1); if (a->ls_event > b->ls_event) return (1); return (b->ls_count - a->ls_count); } static int timecmp(lsrec_t *a, lsrec_t *b) { if (a->ls_event < b->ls_event) return (-1); if (a->ls_event > b->ls_event) return (1); if (a->ls_time < b->ls_time) return (1); if (a->ls_time > b->ls_time) return (-1); return (0); } static int lockcmp_anywhere(lsrec_t *a, lsrec_t *b) { if (a->ls_event < b->ls_event) return (-1); if (a->ls_event > b->ls_event) return (1); #ifdef illumos if (a->ls_lock < b->ls_lock) return (-1); if (a->ls_lock > b->ls_lock) return (1); return (0); #else return (strcmp(a->ls_lock, b->ls_lock)); #endif } static int lock_and_count_cmp_anywhere(lsrec_t *a, lsrec_t *b) { #ifndef illumos int cmp; #endif if (a->ls_event < b->ls_event) return (-1); if (a->ls_event > b->ls_event) return (1); #ifdef illumos if (a->ls_lock < b->ls_lock) return (-1); if (a->ls_lock > b->ls_lock) return (1); #else cmp = strcmp(a->ls_lock, b->ls_lock); if (cmp != 0) return (cmp); #endif return (b->ls_count - a->ls_count); } static int sitecmp_anylock(lsrec_t *a, lsrec_t *b) { int i; if (a->ls_event < b->ls_event) return (-1); if (a->ls_event > b->ls_event) return (1); for (i = g_stkdepth - 1; i >= 0; i--) { if (a->ls_stack[i] < b->ls_stack[i]) return (-1); if (a->ls_stack[i] > b->ls_stack[i]) return (1); } if (a->ls_caller < b->ls_caller) return (-1); if (a->ls_caller > b->ls_caller) return (1); return (0); } static int site_and_count_cmp_anylock(lsrec_t *a, lsrec_t *b) { int i; if (a->ls_event < b->ls_event) return (-1); if (a->ls_event > b->ls_event) return (1); for (i = g_stkdepth - 1; i >= 0; i--) { if (a->ls_stack[i] < b->ls_stack[i]) return (-1); if (a->ls_stack[i] > b->ls_stack[i]) return (1); } if (a->ls_caller < b->ls_caller) return (-1); if (a->ls_caller > b->ls_caller) return (1); return (b->ls_count - a->ls_count); } static void lsmergesort(int (*cmp)(lsrec_t *, lsrec_t *), lsrec_t **a, lsrec_t **b, int n) { int m = n / 2; int i, j; if (m > 1) lsmergesort(cmp, a, b, m); if (n - m > 1) lsmergesort(cmp, a + m, b + m, n - m); for (i = m; i > 0; i--) b[i - 1] = a[i - 1]; for (j = m - 1; j < n - 1; j++) b[n + m - j - 2] = a[j + 1]; while (i < j) *a++ = cmp(b[i], b[j]) < 0 ? b[i++] : b[j--]; *a = b[i]; } static void coalesce(int (*cmp)(lsrec_t *, lsrec_t *), lsrec_t **lock, int n) { int i, j; lsrec_t *target, *current; target = lock[0]; for (i = 1; i < n; i++) { current = lock[i]; if (cmp(current, target) != 0) { target = current; continue; } current->ls_event = LS_MAX_EVENTS; target->ls_count += current->ls_count; target->ls_refcnt += current->ls_refcnt; if (g_recsize < LS_TIME) continue; target->ls_time += current->ls_time; if (g_recsize < LS_HIST) continue; for (j = 0; j < 64; j++) target->ls_hist[j] += current->ls_hist[j]; } } static void coalesce_symbol(uintptr_t *addrp) { uintptr_t symoff; size_t symsize; if (addr_to_sym(*addrp, &symoff, &symsize) != NULL && symoff < symsize) *addrp -= symoff; } static void predicate_add(char **pred, char *what, char *cmp, uintptr_t value) { char *new; int len, newlen; if (what == NULL) return; if (*pred == NULL) { *pred = malloc(1); *pred[0] = '\0'; } len = strlen(*pred); newlen = len + strlen(what) + 32 + strlen("( && )"); new = malloc(newlen); if (*pred[0] != '\0') { if (cmp != NULL) { (void) sprintf(new, "(%s) && (%s %s 0x%p)", *pred, what, cmp, (void *)value); } else { (void) sprintf(new, "(%s) && (%s)", *pred, what); } } else { if (cmp != NULL) { (void) sprintf(new, "%s %s 0x%p", what, cmp, (void *)value); } else { (void) sprintf(new, "%s", what); } } free(*pred); *pred = new; } static void predicate_destroy(char **pred) { free(*pred); *pred = NULL; } static void filter_add(char **filt, char *what, uintptr_t base, uintptr_t size) { char buf[256], *c = buf, *new; int len, newlen; if (*filt == NULL) { *filt = malloc(1); *filt[0] = '\0'; } #ifdef illumos (void) sprintf(c, "%s(%s >= 0x%p && %s < 0x%p)", *filt[0] != '\0' ? " || " : "", what, (void *)base, what, (void *)(base + size)); #else (void) sprintf(c, "%s(%s >= %p && %s < %p)", *filt[0] != '\0' ? " || " : "", what, (void *)base, what, (void *)(base + size)); #endif newlen = (len = strlen(*filt) + 1) + strlen(c); new = malloc(newlen); bcopy(*filt, new, len); (void) strcat(new, c); free(*filt); *filt = new; } static void filter_destroy(char **filt) { free(*filt); *filt = NULL; } static void dprog_add(const char *fmt, ...) { va_list args; int size, offs; char c; va_start(args, fmt); size = vsnprintf(&c, 1, fmt, args) + 1; va_end(args); if (g_proglen == 0) { offs = 0; } else { offs = g_proglen - 1; } g_proglen = offs + size; if ((g_prog = realloc(g_prog, g_proglen)) == NULL) fail(1, "failed to reallocate program text"); va_start(args, fmt); (void) vsnprintf(&g_prog[offs], size, fmt, args); va_end(args); } /* * This function may read like an open sewer, but keep in mind that programs * that generate other programs are rarely pretty. If one has the unenviable * task of maintaining or -- worse -- extending this code, use the -V option * to examine the D program as generated by this function. */ static void dprog_addevent(int event) { ls_event_info_t *info = &g_event_info[event]; char *pred = NULL; char stack[20]; const char *arg0, *caller; char *arg1 = "arg1"; char buf[80]; hrtime_t dur; int depth; if (info->ev_name[0] == '\0') return; if (info->ev_type == 'I') { /* * For interrupt events, arg0 (normally the lock pointer) is * the CPU address plus the current pil, and arg1 (normally * the number of nanoseconds) is the number of nanoseconds * late -- and it's stored in arg2. */ #ifdef illumos arg0 = "(uintptr_t)curthread->t_cpu + \n" "\t curthread->t_cpu->cpu_profile_pil"; #else arg0 = "(uintptr_t)(curthread->td_oncpu << 16) + \n" "\t 0x01000000 + curthread->td_pri_class"; #endif caller = "(uintptr_t)arg0"; arg1 = "arg2"; } else { #ifdef illumos arg0 = "(uintptr_t)arg0"; #else arg0 = "stringof(args[0]->lock_object.lo_name)"; #endif caller = "caller"; } if (g_recsize > LS_HIST) { for (depth = 0; g_recsize > LS_STACK(depth); depth++) continue; if (g_tracing) { (void) sprintf(stack, "\tstack(%d);\n", depth); } else { (void) sprintf(stack, ", stack(%d)", depth); } } else { (void) sprintf(stack, ""); } if (info->ev_acquire != NULL) { /* * If this is a hold event, we need to generate an additional * clause for the acquire; the clause for the release will be * generated with the aggregating statement, below. */ dprog_add("%s\n", info->ev_acquire); predicate_add(&pred, info->ev_predicate, NULL, 0); predicate_add(&pred, g_predicate, NULL, 0); if (pred != NULL) dprog_add("/%s/\n", pred); dprog_add("{\n"); (void) sprintf(buf, "self->ev%d[(uintptr_t)arg0]", event); if (info->ev_type == 'H') { dprog_add("\t%s = timestamp;\n", buf); } else { /* * If this isn't a hold event, it's the recursive * error event. For this, we simply bump the * thread-local, per-lock count. */ dprog_add("\t%s++;\n", buf); } dprog_add("}\n\n"); predicate_destroy(&pred); pred = NULL; if (info->ev_type == 'E') { /* * If this is the recursive lock error event, we need * to generate an additional clause to decrement the * thread-local, per-lock count. This assures that we * only execute the aggregating clause if we have * recursive entry. */ dprog_add("%s\n", info->ev_name); dprog_add("/%s/\n{\n\t%s--;\n}\n\n", buf, buf); } predicate_add(&pred, buf, NULL, 0); if (info->ev_type == 'H') { (void) sprintf(buf, "timestamp -\n\t " "self->ev%d[(uintptr_t)arg0]", event); } arg1 = buf; } else { predicate_add(&pred, info->ev_predicate, NULL, 0); if (info->ev_type != 'I') predicate_add(&pred, g_predicate, NULL, 0); else predicate_add(&pred, g_ipredicate, NULL, 0); } if ((dur = g_min_duration[event]) != 0) predicate_add(&pred, arg1, ">=", dur); dprog_add("%s\n", info->ev_name); if (pred != NULL) dprog_add("/%s/\n", pred); predicate_destroy(&pred); dprog_add("{\n"); if (g_tracing) { dprog_add("\ttrace(%dULL);\n", event); dprog_add("\ttrace(%s);\n", arg0); dprog_add("\ttrace(%s);\n", caller); dprog_add(stack); } else { /* * The ordering here is important: when we process the * aggregate, we count on the fact that @avg appears before * @hist in program order to assure that @avg is assigned the * first aggregation variable ID and @hist assigned the * second; see the comment in process_aggregate() for details. */ dprog_add("\t@avg[%dULL, %s, %s%s] = avg(%s);\n", event, arg0, caller, stack, arg1); if (g_recsize >= LS_HIST) { dprog_add("\t@hist[%dULL, %s, %s%s] = quantize" "(%s);\n", event, arg0, caller, stack, arg1); } } if (info->ev_acquire != NULL) dprog_add("\tself->ev%d[arg0] = 0;\n", event); dprog_add("}\n\n"); } static void dprog_compile() { dtrace_prog_t *prog; dtrace_proginfo_t info; if (g_Vflag) { (void) fprintf(stderr, "lockstat: vvvv D program vvvv\n"); (void) fputs(g_prog, stderr); (void) fprintf(stderr, "lockstat: ^^^^ D program ^^^^\n"); } if ((prog = dtrace_program_strcompile(g_dtp, g_prog, DTRACE_PROBESPEC_NAME, 0, 0, NULL)) == NULL) dfail("failed to compile program"); if (dtrace_program_exec(g_dtp, prog, &info) == -1) dfail("failed to enable probes"); if (dtrace_go(g_dtp) != 0) dfail("couldn't start tracing"); } static void #ifdef illumos status_fire(void) #else status_fire(int i) #endif {} static void status_init(void) { dtrace_optval_t val, status, agg; struct sigaction act; struct itimerspec ts; struct sigevent ev; timer_t tid; if (dtrace_getopt(g_dtp, "statusrate", &status) == -1) dfail("failed to get 'statusrate'"); if (dtrace_getopt(g_dtp, "aggrate", &agg) == -1) dfail("failed to get 'statusrate'"); /* * We would want to awaken at a rate that is the GCD of the statusrate * and the aggrate -- but that seems a bit absurd. Instead, we'll * simply awaken at a rate that is the more frequent of the two, which * assures that we're never later than the interval implied by the * more frequent rate. */ val = status < agg ? status : agg; (void) sigemptyset(&act.sa_mask); act.sa_flags = 0; act.sa_handler = status_fire; (void) sigaction(SIGUSR1, &act, NULL); ev.sigev_notify = SIGEV_SIGNAL; ev.sigev_signo = SIGUSR1; if (timer_create(CLOCK_REALTIME, &ev, &tid) == -1) dfail("cannot create CLOCK_REALTIME timer"); ts.it_value.tv_sec = val / NANOSEC; ts.it_value.tv_nsec = val % NANOSEC; ts.it_interval = ts.it_value; if (timer_settime(tid, TIMER_RELTIME, &ts, NULL) == -1) dfail("cannot set time on CLOCK_REALTIME timer"); } static void status_check(void) { if (!g_tracing && dtrace_aggregate_snap(g_dtp) != 0) dfail("failed to snap aggregate"); if (dtrace_status(g_dtp) == -1) dfail("dtrace_status()"); } static void lsrec_fill(lsrec_t *lsrec, const dtrace_recdesc_t *rec, int nrecs, caddr_t data) { bzero(lsrec, g_recsize); lsrec->ls_count = 1; if ((g_recsize > LS_HIST && nrecs < 4) || (nrecs < 3)) fail(0, "truncated DTrace record"); if (rec->dtrd_size != sizeof (uint64_t)) fail(0, "bad event size in first record"); /* LINTED - alignment */ lsrec->ls_event = (uint32_t)*((uint64_t *)(data + rec->dtrd_offset)); rec++; #ifdef illumos if (rec->dtrd_size != sizeof (uintptr_t)) fail(0, "bad lock address size in second record"); /* LINTED - alignment */ lsrec->ls_lock = *((uintptr_t *)(data + rec->dtrd_offset)); rec++; #else lsrec->ls_lock = strdup((const char *)(data + rec->dtrd_offset)); rec++; #endif if (rec->dtrd_size != sizeof (uintptr_t)) fail(0, "bad caller size in third record"); /* LINTED - alignment */ lsrec->ls_caller = *((uintptr_t *)(data + rec->dtrd_offset)); rec++; if (g_recsize > LS_HIST) { int frames, i; pc_t *stack; frames = rec->dtrd_size / sizeof (pc_t); /* LINTED - alignment */ stack = (pc_t *)(data + rec->dtrd_offset); for (i = 1; i < frames; i++) lsrec->ls_stack[i - 1] = stack[i]; } } /*ARGSUSED*/ static int count_aggregate(const dtrace_aggdata_t *agg, void *arg) { *((size_t *)arg) += 1; return (DTRACE_AGGWALK_NEXT); } static int process_aggregate(const dtrace_aggdata_t *agg, void *arg) { const dtrace_aggdesc_t *aggdesc = agg->dtada_desc; caddr_t data = agg->dtada_data; lsdata_t *lsdata = arg; lsrec_t *lsrec = lsdata->lsd_next; const dtrace_recdesc_t *rec; uint64_t *avg, *quantized; int i, j; assert(lsdata->lsd_count < g_nrecs); /* * Aggregation variable IDs are guaranteed to be generated in program * order, and they are guaranteed to start from DTRACE_AGGVARIDNONE * plus one. As "avg" appears before "hist" in program order, we know * that "avg" will be allocated the first aggregation variable ID, and * "hist" will be allocated the second aggregation variable ID -- and * we therefore use the aggregation variable ID to differentiate the * cases. */ if (aggdesc->dtagd_varid > DTRACE_AGGVARIDNONE + 1) { /* * If this is the histogram entry. We'll copy the quantized * data into lc_hist, and jump over the rest. */ rec = &aggdesc->dtagd_rec[aggdesc->dtagd_nrecs - 1]; if (aggdesc->dtagd_varid != DTRACE_AGGVARIDNONE + 2) fail(0, "bad variable ID in aggregation record"); if (rec->dtrd_size != DTRACE_QUANTIZE_NBUCKETS * sizeof (uint64_t)) fail(0, "bad quantize size in aggregation record"); /* LINTED - alignment */ quantized = (uint64_t *)(data + rec->dtrd_offset); for (i = DTRACE_QUANTIZE_ZEROBUCKET, j = 0; i < DTRACE_QUANTIZE_NBUCKETS; i++, j++) lsrec->ls_hist[j] = quantized[i]; goto out; } lsrec_fill(lsrec, &aggdesc->dtagd_rec[1], aggdesc->dtagd_nrecs - 1, data); rec = &aggdesc->dtagd_rec[aggdesc->dtagd_nrecs - 1]; if (rec->dtrd_size != 2 * sizeof (uint64_t)) fail(0, "bad avg size in aggregation record"); /* LINTED - alignment */ avg = (uint64_t *)(data + rec->dtrd_offset); lsrec->ls_count = (uint32_t)avg[0]; lsrec->ls_time = (uintptr_t)avg[1]; if (g_recsize >= LS_HIST) return (DTRACE_AGGWALK_NEXT); out: lsdata->lsd_next = (lsrec_t *)((uintptr_t)lsrec + g_recsize); lsdata->lsd_count++; return (DTRACE_AGGWALK_NEXT); } static int process_trace(const dtrace_probedata_t *pdata, void *arg) { lsdata_t *lsdata = arg; lsrec_t *lsrec = lsdata->lsd_next; dtrace_eprobedesc_t *edesc = pdata->dtpda_edesc; caddr_t data = pdata->dtpda_data; if (lsdata->lsd_count >= g_nrecs) return (DTRACE_CONSUME_NEXT); lsrec_fill(lsrec, edesc->dtepd_rec, edesc->dtepd_nrecs, data); lsdata->lsd_next = (lsrec_t *)((uintptr_t)lsrec + g_recsize); lsdata->lsd_count++; return (DTRACE_CONSUME_NEXT); } static int process_data(FILE *out, char *data) { lsdata_t lsdata; /* LINTED - alignment */ lsdata.lsd_next = (lsrec_t *)data; lsdata.lsd_count = 0; if (g_tracing) { if (dtrace_consume(g_dtp, out, process_trace, NULL, &lsdata) != 0) dfail("failed to consume buffer"); return (lsdata.lsd_count); } if (dtrace_aggregate_walk_keyvarsorted(g_dtp, process_aggregate, &lsdata) != 0) dfail("failed to walk aggregate"); return (lsdata.lsd_count); } /*ARGSUSED*/ static int drophandler(const dtrace_dropdata_t *data, void *arg) { g_dropped++; (void) fprintf(stderr, "lockstat: warning: %s", data->dtdda_msg); return (DTRACE_HANDLE_OK); } int main(int argc, char **argv) { char *data_buf; lsrec_t *lsp, **current, **first, **sort_buf, **merge_buf; FILE *out = stdout; int c; pid_t child; int status; int i, j; hrtime_t duration; char *addrp, *offp, *sizep, *evp, *lastp, *p; uintptr_t addr; size_t size, off; int events_specified = 0; int exec_errno = 0; uint32_t event; char *filt = NULL, *ifilt = NULL; static uint64_t ev_count[LS_MAX_EVENTS + 1]; static uint64_t ev_time[LS_MAX_EVENTS + 1]; dtrace_optval_t aggsize; char aggstr[10]; long ncpus; int dynvar = 0; int err; if ((g_dtp = dtrace_open(DTRACE_VERSION, 0, &err)) == NULL) { fail(0, "cannot open dtrace library: %s", dtrace_errmsg(NULL, err)); } if (dtrace_handle_drop(g_dtp, &drophandler, NULL) == -1) dfail("couldn't establish drop handler"); if (symtab_init() == -1) fail(1, "can't load kernel symbols"); g_nrecs = DEFAULT_NRECS; while ((c = getopt(argc, argv, LOCKSTAT_OPTSTR)) != GETOPT_EOF) { switch (c) { case 'b': g_recsize = LS_BASIC; break; case 't': g_recsize = LS_TIME; break; case 'h': g_recsize = LS_HIST; break; case 's': if (!isdigit(optarg[0])) usage(); g_stkdepth = atoi(optarg); if (g_stkdepth > LS_MAX_STACK_DEPTH) fail(0, "max stack depth is %d", LS_MAX_STACK_DEPTH); g_recsize = LS_STACK(g_stkdepth); break; case 'n': if (!isdigit(optarg[0])) usage(); g_nrecs = atoi(optarg); break; case 'd': if (!isdigit(optarg[0])) usage(); duration = atoll(optarg); /* * XXX -- durations really should be per event * since the units are different, but it's hard * to express this nicely in the interface. * Not clear yet what the cleanest solution is. */ for (i = 0; i < LS_MAX_EVENTS; i++) if (g_event_info[i].ev_type != 'E') g_min_duration[i] = duration; break; case 'i': if (!isdigit(optarg[0])) usage(); i = atoi(optarg); if (i <= 0) usage(); if (i > MAX_HZ) fail(0, "max interrupt rate is %d Hz", MAX_HZ); for (j = 0; j < LS_MAX_EVENTS; j++) if (strcmp(g_event_info[j].ev_desc, "Profiling interrupt") == 0) break; (void) sprintf(g_event_info[j].ev_name, "profile:::profile-%d", i); break; case 'l': case 'f': addrp = strtok(optarg, ","); sizep = strtok(NULL, ","); addrp = strtok(optarg, ",+"); offp = strtok(NULL, ","); size = sizep ? strtoul(sizep, NULL, 0) : 1; off = offp ? strtoul(offp, NULL, 0) : 0; if (addrp[0] == '0') { addr = strtoul(addrp, NULL, 16) + off; } else { addr = sym_to_addr(addrp) + off; if (sizep == NULL) size = sym_size(addrp) - off; if (addr - off == 0) fail(0, "symbol '%s' not found", addrp); if (size == 0) size = 1; } if (c == 'l') { filter_add(&filt, "arg0", addr, size); } else { filter_add(&filt, "caller", addr, size); filter_add(&ifilt, "arg0", addr, size); } break; case 'e': evp = strtok_r(optarg, ",", &lastp); while (evp) { int ev1, ev2; char *evp2; (void) strtok(evp, "-"); evp2 = strtok(NULL, "-"); ev1 = atoi(evp); ev2 = evp2 ? atoi(evp2) : ev1; if ((uint_t)ev1 >= LS_MAX_EVENTS || (uint_t)ev2 >= LS_MAX_EVENTS || ev1 > ev2) fail(0, "-e events out of range"); for (i = ev1; i <= ev2; i++) g_enabled[i] = 1; evp = strtok_r(NULL, ",", &lastp); } events_specified = 1; break; #ifdef illumos case 'c': g_cflag = 1; break; #endif case 'k': g_kflag = 1; break; case 'w': g_wflag = 1; break; case 'W': g_Wflag = 1; break; case 'g': g_gflag = 1; break; case 'C': case 'E': case 'H': case 'I': for (i = 0; i < LS_MAX_EVENTS; i++) if (g_event_info[i].ev_type == c) g_enabled[i] = 1; events_specified = 1; break; case 'A': for (i = 0; i < LS_MAX_EVENTS; i++) if (strchr("CH", g_event_info[i].ev_type)) g_enabled[i] = 1; events_specified = 1; break; case 'T': g_tracing = 1; break; case 'D': if (!isdigit(optarg[0])) usage(); g_topn = atoi(optarg); break; case 'R': g_rates = 1; break; case 'p': g_pflag = 1; break; case 'P': g_Pflag = 1; break; case 'o': if ((out = fopen(optarg, "w")) == NULL) fail(1, "error opening file"); break; case 'V': g_Vflag = 1; break; default: if (strchr(LOCKSTAT_OPTSTR, c) == NULL) usage(); } } if (filt != NULL) { predicate_add(&g_predicate, filt, NULL, 0); filter_destroy(&filt); } if (ifilt != NULL) { predicate_add(&g_ipredicate, ifilt, NULL, 0); filter_destroy(&ifilt); } if (g_recsize == 0) { if (g_gflag) { g_stkdepth = LS_MAX_STACK_DEPTH; g_recsize = LS_STACK(g_stkdepth); } else { g_recsize = LS_TIME; } } if (g_gflag && g_recsize <= LS_STACK(0)) fail(0, "'-g' requires at least '-s 1' data gathering"); /* * Make sure the alignment is reasonable */ g_recsize = -(-g_recsize & -sizeof (uint64_t)); for (i = 0; i < LS_MAX_EVENTS; i++) { /* * If no events were specified, enable -C. */ if (!events_specified && g_event_info[i].ev_type == 'C') g_enabled[i] = 1; } for (i = 0; i < LS_MAX_EVENTS; i++) { if (!g_enabled[i]) continue; if (g_event_info[i].ev_acquire != NULL) { /* * If we've enabled a hold event, we must explicitly * allocate dynamic variable space. */ dynvar = 1; } dprog_addevent(i); } /* * Make sure there are remaining arguments to specify a child command * to execute. */ if (argc <= optind) usage(); if ((ncpus = sysconf(_SC_NPROCESSORS_ONLN)) == -1) dfail("couldn't determine number of online CPUs"); /* * By default, we set our data buffer size to be the number of records * multiplied by the size of the record, doubled to account for some * DTrace slop and divided by the number of CPUs. We silently clamp * the aggregation size at both a minimum and a maximum to prevent * absurdly low or high values. */ if ((aggsize = (g_nrecs * g_recsize * 2) / ncpus) < MIN_AGGSIZE) aggsize = MIN_AGGSIZE; if (aggsize > MAX_AGGSIZE) aggsize = MAX_AGGSIZE; (void) sprintf(aggstr, "%lld", (long long)aggsize); if (!g_tracing) { if (dtrace_setopt(g_dtp, "bufsize", "4k") == -1) dfail("failed to set 'bufsize'"); if (dtrace_setopt(g_dtp, "aggsize", aggstr) == -1) dfail("failed to set 'aggsize'"); if (dynvar) { /* * If we're using dynamic variables, we set our * dynamic variable size to be one megabyte per CPU, * with a hard-limit of 32 megabytes. This may still * be too small in some cases, but it can be tuned * manually via -x if need be. */ (void) sprintf(aggstr, "%ldm", ncpus < 32 ? ncpus : 32); if (dtrace_setopt(g_dtp, "dynvarsize", aggstr) == -1) dfail("failed to set 'dynvarsize'"); } } else { if (dtrace_setopt(g_dtp, "bufsize", aggstr) == -1) dfail("failed to set 'bufsize'"); } if (dtrace_setopt(g_dtp, "statusrate", "10sec") == -1) dfail("failed to set 'statusrate'"); optind = 1; while ((c = getopt(argc, argv, LOCKSTAT_OPTSTR)) != GETOPT_EOF) { switch (c) { case 'x': if ((p = strchr(optarg, '=')) != NULL) *p++ = '\0'; if (dtrace_setopt(g_dtp, optarg, p) != 0) dfail("failed to set -x %s", optarg); break; } } argc -= optind; argv += optind; dprog_compile(); status_init(); g_elapsed = -gethrtime(); /* * Spawn the specified command and wait for it to complete. */ child = fork(); if (child == -1) fail(1, "cannot fork"); if (child == 0) { (void) dtrace_close(g_dtp); (void) execvp(argv[0], &argv[0]); exec_errno = errno; exit(127); } #ifdef illumos while (waitpid(child, &status, WEXITED) != child) #else while (waitpid(child, &status, 0) != child) #endif status_check(); g_elapsed += gethrtime(); if (WIFEXITED(status)) { if (WEXITSTATUS(status) != 0) { if (exec_errno != 0) { errno = exec_errno; fail(1, "could not execute %s", argv[0]); } (void) fprintf(stderr, "lockstat: warning: %s exited with code %d\n", argv[0], WEXITSTATUS(status)); } } else { (void) fprintf(stderr, "lockstat: warning: %s died on signal %d\n", argv[0], WTERMSIG(status)); } if (dtrace_stop(g_dtp) == -1) dfail("failed to stop dtrace"); /* * Before we read out the results, we need to allocate our buffer. * If we're tracing, then we'll just use the precalculated size. If * we're not, then we'll take a snapshot of the aggregate, and walk * it to count the number of records. */ if (!g_tracing) { if (dtrace_aggregate_snap(g_dtp) != 0) dfail("failed to snap aggregate"); g_nrecs = 0; if (dtrace_aggregate_walk(g_dtp, count_aggregate, &g_nrecs) != 0) dfail("failed to walk aggregate"); } #ifdef illumos if ((data_buf = memalign(sizeof (uint64_t), (g_nrecs + 1) * g_recsize)) == NULL) #else if (posix_memalign((void **)&data_buf, sizeof (uint64_t), (g_nrecs + 1) * g_recsize) ) #endif fail(1, "Memory allocation failed"); /* * Read out the DTrace data. */ g_nrecs_used = process_data(out, data_buf); if (g_nrecs_used > g_nrecs || g_dropped) (void) fprintf(stderr, "lockstat: warning: " "ran out of data records (use -n for more)\n"); /* LINTED - alignment */ for (i = 0, lsp = (lsrec_t *)data_buf; i < g_nrecs_used; i++, /* LINTED - alignment */ lsp = (lsrec_t *)((char *)lsp + g_recsize)) { ev_count[lsp->ls_event] += lsp->ls_count; ev_time[lsp->ls_event] += lsp->ls_time; } /* * If -g was specified, convert stacks into individual records. */ if (g_gflag) { lsrec_t *newlsp, *oldlsp; #ifdef illumos newlsp = memalign(sizeof (uint64_t), g_nrecs_used * LS_TIME * (g_stkdepth + 1)); #else posix_memalign((void **)&newlsp, sizeof (uint64_t), g_nrecs_used * LS_TIME * (g_stkdepth + 1)); #endif if (newlsp == NULL) fail(1, "Cannot allocate space for -g processing"); lsp = newlsp; /* LINTED - alignment */ for (i = 0, oldlsp = (lsrec_t *)data_buf; i < g_nrecs_used; i++, /* LINTED - alignment */ oldlsp = (lsrec_t *)((char *)oldlsp + g_recsize)) { int fr; int caller_in_stack = 0; if (oldlsp->ls_count == 0) continue; for (fr = 0; fr < g_stkdepth; fr++) { if (oldlsp->ls_stack[fr] == 0) break; if (oldlsp->ls_stack[fr] == oldlsp->ls_caller) caller_in_stack = 1; bcopy(oldlsp, lsp, LS_TIME); lsp->ls_caller = oldlsp->ls_stack[fr]; #ifndef illumos lsp->ls_lock = strdup(oldlsp->ls_lock); #endif /* LINTED - alignment */ lsp = (lsrec_t *)((char *)lsp + LS_TIME); } if (!caller_in_stack) { bcopy(oldlsp, lsp, LS_TIME); /* LINTED - alignment */ lsp = (lsrec_t *)((char *)lsp + LS_TIME); } #ifndef illumos free(oldlsp->ls_lock); #endif } g_nrecs = g_nrecs_used = ((uintptr_t)lsp - (uintptr_t)newlsp) / LS_TIME; g_recsize = LS_TIME; g_stkdepth = 0; free(data_buf); data_buf = (char *)newlsp; } if ((sort_buf = calloc(2 * (g_nrecs + 1), sizeof (void *))) == NULL) fail(1, "Sort buffer allocation failed"); merge_buf = sort_buf + (g_nrecs + 1); /* * Build the sort buffer, discarding zero-count records along the way. */ /* LINTED - alignment */ for (i = 0, lsp = (lsrec_t *)data_buf; i < g_nrecs_used; i++, /* LINTED - alignment */ lsp = (lsrec_t *)((char *)lsp + g_recsize)) { if (lsp->ls_count == 0) lsp->ls_event = LS_MAX_EVENTS; sort_buf[i] = lsp; } if (g_nrecs_used == 0) exit(0); /* * Add a sentinel after the last record */ sort_buf[i] = lsp; lsp->ls_event = LS_MAX_EVENTS; if (g_tracing) { report_trace(out, sort_buf); return (0); } /* * Application of -g may have resulted in multiple records * with the same signature; coalesce them. */ if (g_gflag) { mergesort(lockcmp, sort_buf, merge_buf, g_nrecs_used); coalesce(lockcmp, sort_buf, g_nrecs_used); } /* * Coalesce locks within the same symbol if -c option specified. * Coalesce PCs within the same function if -k option specified. */ if (g_cflag || g_kflag) { for (i = 0; i < g_nrecs_used; i++) { int fr; lsp = sort_buf[i]; #ifdef illumos if (g_cflag) coalesce_symbol(&lsp->ls_lock); #endif if (g_kflag) { for (fr = 0; fr < g_stkdepth; fr++) coalesce_symbol(&lsp->ls_stack[fr]); coalesce_symbol(&lsp->ls_caller); } } mergesort(lockcmp, sort_buf, merge_buf, g_nrecs_used); coalesce(lockcmp, sort_buf, g_nrecs_used); } /* * Coalesce callers if -w option specified */ if (g_wflag) { mergesort(lock_and_count_cmp_anywhere, sort_buf, merge_buf, g_nrecs_used); coalesce(lockcmp_anywhere, sort_buf, g_nrecs_used); } /* * Coalesce locks if -W option specified */ if (g_Wflag) { mergesort(site_and_count_cmp_anylock, sort_buf, merge_buf, g_nrecs_used); coalesce(sitecmp_anylock, sort_buf, g_nrecs_used); } /* * Sort data by contention count (ls_count) or total time (ls_time), * depending on g_Pflag. Override g_Pflag if time wasn't measured. */ if (g_recsize < LS_TIME) g_Pflag = 0; if (g_Pflag) mergesort(timecmp, sort_buf, merge_buf, g_nrecs_used); else mergesort(countcmp, sort_buf, merge_buf, g_nrecs_used); /* * Display data by event type */ first = &sort_buf[0]; while ((event = (*first)->ls_event) < LS_MAX_EVENTS) { current = first; while ((lsp = *current)->ls_event == event) current++; report_stats(out, first, current - first, ev_count[event], ev_time[event]); first = current; } #ifndef illumos /* * Free lock name buffers */ for (i = 0, lsp = (lsrec_t *)data_buf; i < g_nrecs_used; i++, lsp = (lsrec_t *)((char *)lsp + g_recsize)) free(lsp->ls_lock); #endif return (0); } static char * format_symbol(char *buf, uintptr_t addr, int show_size) { uintptr_t symoff; char *symname; size_t symsize; symname = addr_to_sym(addr, &symoff, &symsize); if (show_size && symoff == 0) (void) sprintf(buf, "%s[%ld]", symname, (long)symsize); else if (symoff == 0) (void) sprintf(buf, "%s", symname); else if (symoff < 16 && bcmp(symname, "cpu[", 4) == 0) /* CPU+PIL */ #ifdef illumos (void) sprintf(buf, "%s+%ld", symname, (long)symoff); #else (void) sprintf(buf, "%s+%s", symname, g_pri_class[(int)symoff]); #endif else if (symoff <= symsize || (symoff < 256 && addr != symoff)) (void) sprintf(buf, "%s+0x%llx", symname, (unsigned long long)symoff); else (void) sprintf(buf, "0x%llx", (unsigned long long)addr); return (buf); } static void report_stats(FILE *out, lsrec_t **sort_buf, size_t nrecs, uint64_t total_count, uint64_t total_time) { uint32_t event = sort_buf[0]->ls_event; lsrec_t *lsp; double ptotal = 0.0; double percent; int i, j, fr; int displayed; int first_bin, last_bin, max_bin_count, total_bin_count; int rectype; char buf[256]; char lhdr[80], chdr[80]; rectype = g_recsize; if (g_topn == 0) { (void) fprintf(out, "%20llu %s\n", g_rates == 0 ? total_count : ((unsigned long long)total_count * NANOSEC) / g_elapsed, g_event_info[event].ev_desc); return; } (void) sprintf(lhdr, "%s%s", g_Wflag ? "Hottest " : "", g_event_info[event].ev_lhdr); (void) sprintf(chdr, "%s%s", g_wflag ? "Hottest " : "", "Caller"); if (!g_pflag) (void) fprintf(out, "\n%s: %.0f events in %.3f seconds (%.0f events/sec)\n\n", g_event_info[event].ev_desc, (double)total_count, (double)g_elapsed / NANOSEC, (double)total_count * NANOSEC / g_elapsed); if (!g_pflag && rectype < LS_HIST) { (void) sprintf(buf, "%s", g_event_info[event].ev_units); (void) fprintf(out, "%5s %4s %4s %4s %8s %-22s %-24s\n", g_rates ? "ops/s" : "Count", g_gflag ? "genr" : "indv", "cuml", "rcnt", rectype >= LS_TIME ? buf : "", lhdr, chdr); (void) fprintf(out, "---------------------------------" "----------------------------------------------\n"); } displayed = 0; for (i = 0; i < nrecs; i++) { lsp = sort_buf[i]; if (displayed++ >= g_topn) break; if (g_pflag) { int j; (void) fprintf(out, "%u %u", lsp->ls_event, lsp->ls_count); #ifdef illumos (void) fprintf(out, " %s", format_symbol(buf, lsp->ls_lock, g_cflag)); #else (void) fprintf(out, " %s", lsp->ls_lock); #endif (void) fprintf(out, " %s", format_symbol(buf, lsp->ls_caller, 0)); (void) fprintf(out, " %f", (double)lsp->ls_refcnt / lsp->ls_count); if (rectype >= LS_TIME) (void) fprintf(out, " %llu", (unsigned long long)lsp->ls_time); if (rectype >= LS_HIST) { for (j = 0; j < 64; j++) (void) fprintf(out, " %u", lsp->ls_hist[j]); } for (j = 0; j < LS_MAX_STACK_DEPTH; j++) { if (rectype <= LS_STACK(j) || lsp->ls_stack[j] == 0) break; (void) fprintf(out, " %s", format_symbol(buf, lsp->ls_stack[j], 0)); } (void) fprintf(out, "\n"); continue; } if (rectype >= LS_HIST) { (void) fprintf(out, "---------------------------------" "----------------------------------------------\n"); (void) sprintf(buf, "%s", g_event_info[event].ev_units); (void) fprintf(out, "%5s %4s %4s %4s %8s %-22s %-24s\n", g_rates ? "ops/s" : "Count", g_gflag ? "genr" : "indv", "cuml", "rcnt", buf, lhdr, chdr); } if (g_Pflag && total_time != 0) percent = (lsp->ls_time * 100.00) / total_time; else percent = (lsp->ls_count * 100.00) / total_count; ptotal += percent; if (rectype >= LS_TIME) (void) sprintf(buf, "%llu", (unsigned long long)(lsp->ls_time / lsp->ls_count)); else buf[0] = '\0'; (void) fprintf(out, "%5llu ", g_rates == 0 ? lsp->ls_count : ((uint64_t)lsp->ls_count * NANOSEC) / g_elapsed); (void) fprintf(out, "%3.0f%% ", percent); if (g_gflag) (void) fprintf(out, "---- "); else (void) fprintf(out, "%3.0f%% ", ptotal); (void) fprintf(out, "%4.2f %8s ", (double)lsp->ls_refcnt / lsp->ls_count, buf); #ifdef illumos (void) fprintf(out, "%-22s ", format_symbol(buf, lsp->ls_lock, g_cflag)); #else (void) fprintf(out, "%-22s ", lsp->ls_lock); #endif (void) fprintf(out, "%-24s\n", format_symbol(buf, lsp->ls_caller, 0)); if (rectype < LS_HIST) continue; (void) fprintf(out, "\n"); (void) fprintf(out, "%10s %31s %-9s %-24s\n", g_event_info[event].ev_units, "------ Time Distribution ------", g_rates ? "ops/s" : "count", rectype > LS_STACK(0) ? "Stack" : ""); first_bin = 0; while (lsp->ls_hist[first_bin] == 0) first_bin++; last_bin = 63; while (lsp->ls_hist[last_bin] == 0) last_bin--; max_bin_count = 0; total_bin_count = 0; for (j = first_bin; j <= last_bin; j++) { total_bin_count += lsp->ls_hist[j]; if (lsp->ls_hist[j] > max_bin_count) max_bin_count = lsp->ls_hist[j]; } /* * If we went a few frames below the caller, ignore them */ for (fr = 3; fr > 0; fr--) if (lsp->ls_stack[fr] == lsp->ls_caller) break; for (j = first_bin; j <= last_bin; j++) { uint_t depth = (lsp->ls_hist[j] * 30) / total_bin_count; (void) fprintf(out, "%10llu |%s%s %-9u ", 1ULL << j, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" + 30 - depth, " " + depth, g_rates == 0 ? lsp->ls_hist[j] : (uint_t)(((uint64_t)lsp->ls_hist[j] * NANOSEC) / g_elapsed)); if (rectype <= LS_STACK(fr) || lsp->ls_stack[fr] == 0) { (void) fprintf(out, "\n"); continue; } (void) fprintf(out, "%-24s\n", format_symbol(buf, lsp->ls_stack[fr], 0)); fr++; } while (rectype > LS_STACK(fr) && lsp->ls_stack[fr] != 0) { (void) fprintf(out, "%15s %-36s %-24s\n", "", "", format_symbol(buf, lsp->ls_stack[fr], 0)); fr++; } } if (!g_pflag) (void) fprintf(out, "---------------------------------" "----------------------------------------------\n"); (void) fflush(out); } static void report_trace(FILE *out, lsrec_t **sort_buf) { lsrec_t *lsp; int i, fr; int rectype; char buf[256], buf2[256]; rectype = g_recsize; if (!g_pflag) { (void) fprintf(out, "%5s %7s %11s %-24s %-24s\n", "Event", "Time", "Owner", "Lock", "Caller"); (void) fprintf(out, "---------------------------------" "----------------------------------------------\n"); } for (i = 0; i < g_nrecs_used; i++) { lsp = sort_buf[i]; if (lsp->ls_event >= LS_MAX_EVENTS || lsp->ls_count == 0) continue; (void) fprintf(out, "%2d %10llu %11p %-24s %-24s\n", lsp->ls_event, (unsigned long long)lsp->ls_time, (void *)lsp->ls_next, #ifdef illumos format_symbol(buf, lsp->ls_lock, 0), #else lsp->ls_lock, #endif format_symbol(buf2, lsp->ls_caller, 0)); if (rectype <= LS_STACK(0)) continue; /* * If we went a few frames below the caller, ignore them */ for (fr = 3; fr > 0; fr--) if (lsp->ls_stack[fr] == lsp->ls_caller) break; while (rectype > LS_STACK(fr) && lsp->ls_stack[fr] != 0) { (void) fprintf(out, "%53s %-24s\n", "", format_symbol(buf, lsp->ls_stack[fr], 0)); fr++; } (void) fprintf(out, "\n"); } (void) fflush(out); } Index: head/share/man/man4/dtrace_lockstat.4 =================================================================== --- head/share/man/man4/dtrace_lockstat.4 (revision 351360) +++ head/share/man/man4/dtrace_lockstat.4 (revision 351361) @@ -1,300 +1,294 @@ .\" Copyright (c) 2017 George V. Neville-Neil .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $FreeBSD$ .\" -.Dd March 2, 2018 +.Dd August 20, 2019 .Dt DTRACE_LOCKSTAT 4 .Os .Sh NAME .Nm dtrace_lockstat .Nd a DTrace provider for tracing CPU scheduling events .Sh SYNOPSIS .Fn lockstat:::adaptive-acquire "struct mtx *" .Fn lockstat:::adaptive-release "struct mtx *" .Fn lockstat:::adaptive-spin "struct mtx *" "uint64_t" .Fn lockstat:::adaptive-block "struct mtx *" "uint64_t" .Fn lockstat:::spin-acquire "struct mtx *" .Fn lockstat:::spin-release "struct mtx *" .Fn lockstat:::spin-spin "struct mtx *" "uint64_t" .Fn lockstat:::rw-acquire "struct rwlock *" "int" .Fn lockstat:::rw-release "struct rwlock *" "int" .Fn lockstat:::rw-block "struct rwlock *" "uint64_t" "int" "int" "int" .Fn lockstat:::rw-spin "struct rwlock *" "uint64_t" .Fn lockstat:::rw-upgrade "struct rwlock *" .Fn lockstat:::rw-downgrade "struct rwlock *" .Fn lockstat:::sx-acquire "struct sx *" "int" .Fn lockstat:::sx-release "struct sx *" "int" .Fn lockstat:::sx-block "struct sx *" "uint64_t" "int" "int" "int" .Fn lockstat:::sx-spin "struct sx *" "uint64_t" .Fn lockstat:::sx-upgrade "struct sx *" .Fn lockstat:::sx-downgrade "struct sx *" +.Fn lockstat:::lockmgr-acquire "struct lock *" "int" +.Fn lockstat:::lockmgr-release "struct lock *" "int" +.Fn lockstat:::lockmgr-disown "struct lock *" "int" +.Fn lockstat:::lockmgr-block "struct lock *" "uint64_t" "int" "int" "int" +.Fn lockstat:::lockmgr-upgrade "struct lock *" +.Fn lockstat:::lockmgr-downgrade "struct lock *" .Fn lockstat:::thread-spin "struct mtx *" "uint64" .Sh DESCRIPTION The DTrace .Nm lockstat provider allows the tracing of events related to locking on .Fx . .Pp The .Nm provider contains DTrace probes for inspecting kernel lock state transitions. Probes exist for the +.Xr lockmgr 9 , .Xr mutex 9 , .Xr rwlock 9 , and .Xr sx 9 lock types. The .Xr lockstat 1 utility can be used to collect and display data collected from the .Nm provider. Each type of lock has .Fn acquire and .Fn release probes which expose the lock structure being operated upon, as well as probes which fire when a thread contends with other threads for ownership of a lock. .Pp The .Fn lockstat:::adaptive-acquire and .Fn lockstat:::adaptive-release probes fire when an .Dv MTX_DEF .Xr mutex 9 is acquired and released, respectively. The only argument is a pointer to the lock structure which describes the lock being acquired or released. .Pp The .Fn lockstat:::adaptive-spin probe fires when a thread spins while waiting for a .Dv MTX_DEF .Xr mutex 9 to be released by another thread. The first argument is a pointer to the lock structure that describes the lock and the second argument is the amount of time, in nanoseconds, that the mutex spent spinning. The .Fn lockstat:::adaptive-block probe fires when a thread takes itself off the CPU while trying to acquire an .Dv MTX_DEF .Xr mutex 9 that is owned by another thread. The first argument is a pointer to the lock structure that describes the lock and the second argument is the length of time, in nanoseconds, that the waiting thread was blocked. The .Fn lockstat:::adaptive-block and .Fn lockstat:::adaptive-spin probes fire only after the lock has been successfully acquired, and in particular, after the .Fn lockstat:::adaptive-acquire probe fires. .Pp The .Fn lockstat:::spin-acquire and .Fn lockstat:::spin-release probes fire when a .Dv MTX_SPIN .Xr mutex 9 is acquired or released, respectively. The only argument is a pointer to the lock structure which describes the lock being acquired or released. .Pp The .Fn lockstat:::spin-spin probe fires when a thread spins while waiting for a .Dv MTX_SPIN .Xr mutex 9 to be released by another thread. The first argument is a pointer to the lock structure that describes the lock and the second argument is the length of the time spent spinning, in nanoseconds. The .Fn lockstat:::spin-spin probe fires only after the lock has been successfully acquired, and in particular, after the .Fn lockstat:::spin-acquire probe fires. .Pp The .Fn lockstat:::rw-acquire and .Fn lockstat:::rw-release probes fire when a .Xr rwlock 9 is acquired or released, respectively. The first argument is a pointer to the structure which describes the lock being acquired. The second argument is .Dv 0 if the lock is being acquired or released as a writer, and .Dv 1 if it is being acquired or released as a reader. -.Pp The -.Fn lockstat:::rw-block -probe fires when a thread removes itself from the CPU while -waiting to acquire a -.Xr rwlock 9 . -The -.Fn lockstat:::rw-spin -probe fires when a thread spins while waiting to acquire a -.Xr rwlock 9 . -Both probes take the same set of arguments. -The first argument is a pointer to the lock structure that describes -the lock. -The second argument is the length of time, in nanoseconds, -that the waiting thread was off the CPU or spinning for the lock. -The third argument is -.Dv 0 -if the thread is attempting to acquire the lock as a writer, and -.Dv 1 -if the thread is attempting to acquire the lock as a reader. -The fourth argument is -.Dv 0 -if the thread is waiting for a writer to release the lock, and -.Dv 1 -if the thread is waiting for a reader to release the lock. -The fifth argument is the number of readers that held the lock when -the thread first attempted to acquire the lock. -This argument will be -.Dv 0 -if the fourth argument is -.Dv 0 . -.Pp -The -.Fn lockstat:::rw-upgrade -probe fires when a thread successfully upgrades a held -.Xr rwlock 9 -read lock to a write lock. -The -.Fn lockstat:::rw-downgrade -probe fires when a thread downgrades a held -.Xr rwlock 9 -write lock to a read lock. -The only argument is a pointer to the structure which describes -the lock being acquired. -.Pp -The .Fn lockstat:::sx-acquire and -.Fn lockstat:::sx-release -probes fire when a +.Fn lockstat:::sx-release , +and +.Fn lockstat:::lockmgr-acquire +and +.Fn lockstat:::lockmgr-release +probes fire upon the corresponding events for .Xr sx 9 -is acquired or released, respectively. +and +.Xr lockmgr 9 +locks, respectively. +The +.Fn lockstat:::lockmgr-disown +probe fires when a +.Xr lockmgr 9 +exclusive lock is disowned. +In this state, the lock remains exclusively held, but may be +released by a different thread. +The +.Fn lockstat:::lockmgr-release +probe does not fire when releasing a disowned lock. The first argument is a pointer to the structure which describes -the lock being acquired. +the lock being disowned. The second argument is -.Dv 0 -if the shared lock is being acquired or released, and -.Dv 1 -if the exclusive lock is being acquired or released. +.Dv 0 , +for compatibility with +.Fn lockstat:::lockmgr-release . .Pp The -.Fn lockstat:::sx-block -probe fires when a thread takes itself off the CPU while -waiting to acquire a -.Xr sx 9 . +.Fn lockstat:::rw-block , +.Fn lockstat:::sx-block , +and +.Fn lockstat:::lockmgr-block +probes fire when a thread removes itself from the CPU while +waiting to acquire a lock of the corresponding type. The +.Fn lockstat:::rw-spin +and .Fn lockstat:::sx-spin -probe fires when a thread spins while waiting to acquire a -.Xr sx 9 . -Both probes take the same set of arguments. +probes fire when a thread spins while waiting to acquire a lock +of the corresponding type. +All probes take the same set of arguments. The first argument is a pointer to the lock structure that describes the lock. The second argument is the length of time, in nanoseconds, that the waiting thread was off the CPU or spinning for the lock. The third argument is .Dv 0 if the thread is attempting to acquire the lock as a writer, and .Dv 1 if the thread is attempting to acquire the lock as a reader. The fourth argument is .Dv 0 -if the thread is waiting for a writer to release the lock, and +if the thread is waiting for a reader to release the lock, and .Dv 1 -if the thread is waiting for a reader to release the lock. +if the thread is waiting for a writer to release the lock. The fifth argument is the number of readers that held the lock when the thread first attempted to acquire the lock. This argument will be .Dv 0 if the fourth argument is -.Dv 0 . +.Dv 1 . .Pp The +.Fn lockstat:::lockmgr-upgrade , +.Fn lockstat:::rw-upgrade , +and .Fn lockstat:::sx-upgrade -probe fires when a thread successfully upgrades a held +probes fire when a thread successfully upgrades a held +.Xr lockmgr 9 , +.Xr rwlock 9 , +or .Xr sx 9 -shared lock to an exclusive lock. +shared/reader lock to an exclusive/writer lock. The only argument is a pointer to the structure which describes the lock being acquired. The +.Fn lockstat:::lockmgr-downgrade , +.Fn lockstat:::rw-downgrade , +and .Fn lockstat:::sx-downgrade -probe fires when a thread downgrades a held +probes fire when a thread downgrades a held +.Xr lockmgr 9 , +.Xr rwlock 9 , +or .Xr sx 9 -exclusive lock to a shared lock. +exclusive/writer lock to a shared/reader lock. .Pp The .Fn lockstat:::thread-spin probe fires when a thread spins on a thread lock, which is a specialized .Dv MTX_SPIN .Xr mutex 9 . The first argument is a pointer to the structure that describes the lock and the second argument is the length of time, in nanoseconds, that the thread was spinning. .Sh SEE ALSO .Xr dtrace 1 , .Xr lockstat 1 , .Xr locking 9 , .Xr mutex 9 , .Xr rwlock 9 , .Xr SDT 9 , .Xr sx 9 .Sh HISTORY The .Nm provider first appeared in Solaris. The .Fx implementation of the .Nm provider first appeared in .Fx 9 . .Sh AUTHORS This manual page was written by -.An George V. Neville-Neil Aq Mt gnn@FreeBSD.org . +.An George V. Neville-Neil Aq Mt gnn@FreeBSD.org +and +.An -nosplit +.An Mark Johnston Aq Mt markj@FreeBSD.org . .Sh BUGS Probes for -.Xr lockmgr 9 -and .Xr rmlock 9 locks have not yet been added. Index: head/sys/kern/kern_lock.c =================================================================== --- head/sys/kern/kern_lock.c (revision 351360) +++ head/sys/kern/kern_lock.c (revision 351361) @@ -1,1686 +1,1721 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2008 Attilio Rao * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice(s), this list of conditions and the following disclaimer as * the first lines of this file unmodified other than the possible * addition of one or more copyright notices. * 2. Redistributions in binary form must reproduce the above copyright * notice(s), this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ #include "opt_ddb.h" #include "opt_hwpmc_hooks.h" #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include +#include #include #include #include #ifdef DEBUG_LOCKS #include #endif #include #include #include #ifdef DDB #include #endif #ifdef HWPMC_HOOKS #include PMC_SOFT_DECLARE( , , lock, failed); #endif CTASSERT(((LK_ADAPTIVE | LK_NOSHARE) & LO_CLASSFLAGS) == (LK_ADAPTIVE | LK_NOSHARE)); CTASSERT(LK_UNLOCKED == (LK_UNLOCKED & ~(LK_ALL_WAITERS | LK_EXCLUSIVE_SPINNERS))); #define SQ_EXCLUSIVE_QUEUE 0 #define SQ_SHARED_QUEUE 1 #ifndef INVARIANTS #define _lockmgr_assert(lk, what, file, line) #endif #define TD_SLOCKS_INC(td) ((td)->td_lk_slocks++) #define TD_SLOCKS_DEC(td) ((td)->td_lk_slocks--) #ifndef DEBUG_LOCKS #define STACK_PRINT(lk) #define STACK_SAVE(lk) #define STACK_ZERO(lk) #else #define STACK_PRINT(lk) stack_print_ddb(&(lk)->lk_stack) #define STACK_SAVE(lk) stack_save(&(lk)->lk_stack) #define STACK_ZERO(lk) stack_zero(&(lk)->lk_stack) #endif #define LOCK_LOG2(lk, string, arg1, arg2) \ if (LOCK_LOG_TEST(&(lk)->lock_object, 0)) \ CTR2(KTR_LOCK, (string), (arg1), (arg2)) #define LOCK_LOG3(lk, string, arg1, arg2, arg3) \ if (LOCK_LOG_TEST(&(lk)->lock_object, 0)) \ CTR3(KTR_LOCK, (string), (arg1), (arg2), (arg3)) #define GIANT_DECLARE \ int _i = 0; \ WITNESS_SAVE_DECL(Giant) #define GIANT_RESTORE() do { \ if (__predict_false(_i > 0)) { \ while (_i--) \ mtx_lock(&Giant); \ WITNESS_RESTORE(&Giant.lock_object, Giant); \ } \ } while (0) #define GIANT_SAVE() do { \ if (__predict_false(mtx_owned(&Giant))) { \ WITNESS_SAVE(&Giant.lock_object, Giant); \ while (mtx_owned(&Giant)) { \ _i++; \ mtx_unlock(&Giant); \ } \ } \ } while (0) static bool __always_inline LK_CAN_SHARE(uintptr_t x, int flags, bool fp) { if ((x & (LK_SHARE | LK_EXCLUSIVE_WAITERS | LK_EXCLUSIVE_SPINNERS)) == LK_SHARE) return (true); if (fp || (!(x & LK_SHARE))) return (false); if ((curthread->td_lk_slocks != 0 && !(flags & LK_NODDLKTREAT)) || (curthread->td_pflags & TDP_DEADLKTREAT)) return (true); return (false); } #define LK_TRYOP(x) \ ((x) & LK_NOWAIT) #define LK_CAN_WITNESS(x) \ (((x) & LK_NOWITNESS) == 0 && !LK_TRYOP(x)) #define LK_TRYWIT(x) \ (LK_TRYOP(x) ? LOP_TRYLOCK : 0) #define LK_CAN_ADAPT(lk, f) \ (((lk)->lock_object.lo_flags & LK_ADAPTIVE) != 0 && \ ((f) & LK_SLEEPFAIL) == 0) #define lockmgr_disowned(lk) \ (((lk)->lk_lock & ~(LK_FLAGMASK & ~LK_SHARE)) == LK_KERNPROC) #define lockmgr_xlocked_v(v) \ (((v) & ~(LK_FLAGMASK & ~LK_SHARE)) == (uintptr_t)curthread) #define lockmgr_xlocked(lk) lockmgr_xlocked_v((lk)->lk_lock) static void assert_lockmgr(const struct lock_object *lock, int how); #ifdef DDB static void db_show_lockmgr(const struct lock_object *lock); #endif static void lock_lockmgr(struct lock_object *lock, uintptr_t how); #ifdef KDTRACE_HOOKS static int owner_lockmgr(const struct lock_object *lock, struct thread **owner); #endif static uintptr_t unlock_lockmgr(struct lock_object *lock); struct lock_class lock_class_lockmgr = { .lc_name = "lockmgr", .lc_flags = LC_RECURSABLE | LC_SLEEPABLE | LC_SLEEPLOCK | LC_UPGRADABLE, .lc_assert = assert_lockmgr, #ifdef DDB .lc_ddb_show = db_show_lockmgr, #endif .lc_lock = lock_lockmgr, .lc_unlock = unlock_lockmgr, #ifdef KDTRACE_HOOKS .lc_owner = owner_lockmgr, #endif }; struct lockmgr_wait { const char *iwmesg; int ipri; int itimo; }; static bool __always_inline lockmgr_slock_try(struct lock *lk, uintptr_t *xp, int flags, bool fp); static bool __always_inline lockmgr_sunlock_try(struct lock *lk, uintptr_t *xp); static void lockmgr_exit(u_int flags, struct lock_object *ilk, int wakeup_swapper) { struct lock_class *class; if (flags & LK_INTERLOCK) { class = LOCK_CLASS(ilk); class->lc_unlock(ilk); } if (__predict_false(wakeup_swapper)) kick_proc0(); } static void lockmgr_note_shared_acquire(struct lock *lk, int contested, uint64_t waittime, const char *file, int line, int flags) { - lock_profile_obtain_lock_success(&lk->lock_object, contested, waittime, - file, line); + LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(lockmgr__acquire, lk, contested, + waittime, file, line, LOCKSTAT_READER); LOCK_LOG_LOCK("SLOCK", &lk->lock_object, 0, 0, file, line); WITNESS_LOCK(&lk->lock_object, LK_TRYWIT(flags), file, line); TD_LOCKS_INC(curthread); TD_SLOCKS_INC(curthread); STACK_SAVE(lk); } static void lockmgr_note_shared_release(struct lock *lk, const char *file, int line) { - lock_profile_release_lock(&lk->lock_object); + LOCKSTAT_PROFILE_RELEASE_RWLOCK(lockmgr__release, lk, LOCKSTAT_READER); WITNESS_UNLOCK(&lk->lock_object, 0, file, line); LOCK_LOG_LOCK("SUNLOCK", &lk->lock_object, 0, 0, file, line); TD_LOCKS_DEC(curthread); TD_SLOCKS_DEC(curthread); } static void lockmgr_note_exclusive_acquire(struct lock *lk, int contested, uint64_t waittime, const char *file, int line, int flags) { - lock_profile_obtain_lock_success(&lk->lock_object, contested, waittime, - file, line); + LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(lockmgr__acquire, lk, contested, + waittime, file, line, LOCKSTAT_WRITER); LOCK_LOG_LOCK("XLOCK", &lk->lock_object, 0, lk->lk_recurse, file, line); WITNESS_LOCK(&lk->lock_object, LOP_EXCLUSIVE | LK_TRYWIT(flags), file, line); TD_LOCKS_INC(curthread); STACK_SAVE(lk); } static void lockmgr_note_exclusive_release(struct lock *lk, const char *file, int line) { - lock_profile_release_lock(&lk->lock_object); + LOCKSTAT_PROFILE_RELEASE_RWLOCK(lockmgr__release, lk, LOCKSTAT_WRITER); LOCK_LOG_LOCK("XUNLOCK", &lk->lock_object, 0, lk->lk_recurse, file, line); WITNESS_UNLOCK(&lk->lock_object, LOP_EXCLUSIVE, file, line); TD_LOCKS_DEC(curthread); } static __inline struct thread * lockmgr_xholder(const struct lock *lk) { uintptr_t x; x = lk->lk_lock; return ((x & LK_SHARE) ? NULL : (struct thread *)LK_HOLDER(x)); } /* * It assumes sleepq_lock held and returns with this one unheld. * It also assumes the generic interlock is sane and previously checked. * If LK_INTERLOCK is specified the interlock is not reacquired after the * sleep. */ static __inline int sleeplk(struct lock *lk, u_int flags, struct lock_object *ilk, const char *wmesg, int pri, int timo, int queue) { GIANT_DECLARE; struct lock_class *class; int catch, error; class = (flags & LK_INTERLOCK) ? LOCK_CLASS(ilk) : NULL; catch = pri & PCATCH; pri &= PRIMASK; error = 0; LOCK_LOG3(lk, "%s: %p blocking on the %s sleepqueue", __func__, lk, (queue == SQ_EXCLUSIVE_QUEUE) ? "exclusive" : "shared"); if (flags & LK_INTERLOCK) class->lc_unlock(ilk); if (queue == SQ_EXCLUSIVE_QUEUE && (flags & LK_SLEEPFAIL) != 0) lk->lk_exslpfail++; GIANT_SAVE(); sleepq_add(&lk->lock_object, NULL, wmesg, SLEEPQ_LK | (catch ? SLEEPQ_INTERRUPTIBLE : 0), queue); if ((flags & LK_TIMELOCK) && timo) sleepq_set_timeout(&lk->lock_object, timo); /* * Decisional switch for real sleeping. */ if ((flags & LK_TIMELOCK) && timo && catch) error = sleepq_timedwait_sig(&lk->lock_object, pri); else if ((flags & LK_TIMELOCK) && timo) error = sleepq_timedwait(&lk->lock_object, pri); else if (catch) error = sleepq_wait_sig(&lk->lock_object, pri); else sleepq_wait(&lk->lock_object, pri); GIANT_RESTORE(); if ((flags & LK_SLEEPFAIL) && error == 0) error = ENOLCK; return (error); } static __inline int wakeupshlk(struct lock *lk, const char *file, int line) { uintptr_t v, x, orig_x; u_int realexslp; int queue, wakeup_swapper; wakeup_swapper = 0; for (;;) { x = lk->lk_lock; if (lockmgr_sunlock_try(lk, &x)) break; /* * We should have a sharer with waiters, so enter the hard * path in order to handle wakeups correctly. */ sleepq_lock(&lk->lock_object); orig_x = lk->lk_lock; retry_sleepq: x = orig_x & (LK_ALL_WAITERS | LK_EXCLUSIVE_SPINNERS); v = LK_UNLOCKED; /* * If the lock has exclusive waiters, give them preference in * order to avoid deadlock with shared runners up. * If interruptible sleeps left the exclusive queue empty * avoid a starvation for the threads sleeping on the shared * queue by giving them precedence and cleaning up the * exclusive waiters bit anyway. * Please note that lk_exslpfail count may be lying about * the real number of waiters with the LK_SLEEPFAIL flag on * because they may be used in conjunction with interruptible * sleeps so lk_exslpfail might be considered an 'upper limit' * bound, including the edge cases. */ realexslp = sleepq_sleepcnt(&lk->lock_object, SQ_EXCLUSIVE_QUEUE); if ((x & LK_EXCLUSIVE_WAITERS) != 0 && realexslp != 0) { if (lk->lk_exslpfail < realexslp) { lk->lk_exslpfail = 0; queue = SQ_EXCLUSIVE_QUEUE; v |= (x & LK_SHARED_WAITERS); } else { lk->lk_exslpfail = 0; LOCK_LOG2(lk, "%s: %p has only LK_SLEEPFAIL sleepers", __func__, lk); LOCK_LOG2(lk, "%s: %p waking up threads on the exclusive queue", __func__, lk); wakeup_swapper = sleepq_broadcast(&lk->lock_object, SLEEPQ_LK, 0, SQ_EXCLUSIVE_QUEUE); queue = SQ_SHARED_QUEUE; } } else { /* * Exclusive waiters sleeping with LK_SLEEPFAIL on * and using interruptible sleeps/timeout may have * left spourious lk_exslpfail counts on, so clean * it up anyway. */ lk->lk_exslpfail = 0; queue = SQ_SHARED_QUEUE; } if (lockmgr_sunlock_try(lk, &orig_x)) { sleepq_release(&lk->lock_object); break; } x |= LK_SHARERS_LOCK(1); if (!atomic_fcmpset_rel_ptr(&lk->lk_lock, &x, v)) { orig_x = x; goto retry_sleepq; } LOCK_LOG3(lk, "%s: %p waking up threads on the %s queue", __func__, lk, queue == SQ_SHARED_QUEUE ? "shared" : "exclusive"); wakeup_swapper |= sleepq_broadcast(&lk->lock_object, SLEEPQ_LK, 0, queue); sleepq_release(&lk->lock_object); break; } lockmgr_note_shared_release(lk, file, line); return (wakeup_swapper); } static void assert_lockmgr(const struct lock_object *lock, int what) { panic("lockmgr locks do not support assertions"); } static void lock_lockmgr(struct lock_object *lock, uintptr_t how) { panic("lockmgr locks do not support sleep interlocking"); } static uintptr_t unlock_lockmgr(struct lock_object *lock) { panic("lockmgr locks do not support sleep interlocking"); } #ifdef KDTRACE_HOOKS static int owner_lockmgr(const struct lock_object *lock, struct thread **owner) { panic("lockmgr locks do not support owner inquiring"); } #endif void lockinit(struct lock *lk, int pri, const char *wmesg, int timo, int flags) { int iflags; MPASS((flags & ~LK_INIT_MASK) == 0); ASSERT_ATOMIC_LOAD_PTR(lk->lk_lock, ("%s: lockmgr not aligned for %s: %p", __func__, wmesg, &lk->lk_lock)); iflags = LO_SLEEPABLE | LO_UPGRADABLE; if (flags & LK_CANRECURSE) iflags |= LO_RECURSABLE; if ((flags & LK_NODUP) == 0) iflags |= LO_DUPOK; if (flags & LK_NOPROFILE) iflags |= LO_NOPROFILE; if ((flags & LK_NOWITNESS) == 0) iflags |= LO_WITNESS; if (flags & LK_QUIET) iflags |= LO_QUIET; if (flags & LK_IS_VNODE) iflags |= LO_IS_VNODE; if (flags & LK_NEW) iflags |= LO_NEW; iflags |= flags & (LK_ADAPTIVE | LK_NOSHARE); lock_init(&lk->lock_object, &lock_class_lockmgr, wmesg, NULL, iflags); lk->lk_lock = LK_UNLOCKED; lk->lk_recurse = 0; lk->lk_exslpfail = 0; lk->lk_timo = timo; lk->lk_pri = pri; STACK_ZERO(lk); } /* * XXX: Gross hacks to manipulate external lock flags after * initialization. Used for certain vnode and buf locks. */ void lockallowshare(struct lock *lk) { lockmgr_assert(lk, KA_XLOCKED); lk->lock_object.lo_flags &= ~LK_NOSHARE; } void lockdisableshare(struct lock *lk) { lockmgr_assert(lk, KA_XLOCKED); lk->lock_object.lo_flags |= LK_NOSHARE; } void lockallowrecurse(struct lock *lk) { lockmgr_assert(lk, KA_XLOCKED); lk->lock_object.lo_flags |= LO_RECURSABLE; } void lockdisablerecurse(struct lock *lk) { lockmgr_assert(lk, KA_XLOCKED); lk->lock_object.lo_flags &= ~LO_RECURSABLE; } void lockdestroy(struct lock *lk) { KASSERT(lk->lk_lock == LK_UNLOCKED, ("lockmgr still held")); KASSERT(lk->lk_recurse == 0, ("lockmgr still recursed")); KASSERT(lk->lk_exslpfail == 0, ("lockmgr still exclusive waiters")); lock_destroy(&lk->lock_object); } static bool __always_inline lockmgr_slock_try(struct lock *lk, uintptr_t *xp, int flags, bool fp) { /* * If no other thread has an exclusive lock, or * no exclusive waiter is present, bump the count of * sharers. Since we have to preserve the state of * waiters, if we fail to acquire the shared lock * loop back and retry. */ *xp = lk->lk_lock; while (LK_CAN_SHARE(*xp, flags, fp)) { if (atomic_fcmpset_acq_ptr(&lk->lk_lock, xp, *xp + LK_ONE_SHARER)) { return (true); } } return (false); } static bool __always_inline lockmgr_sunlock_try(struct lock *lk, uintptr_t *xp) { for (;;) { if (LK_SHARERS(*xp) > 1 || !(*xp & LK_ALL_WAITERS)) { if (atomic_fcmpset_rel_ptr(&lk->lk_lock, xp, *xp - LK_ONE_SHARER)) return (true); continue; } break; } return (false); } static __noinline int lockmgr_slock_hard(struct lock *lk, u_int flags, struct lock_object *ilk, const char *file, int line, struct lockmgr_wait *lwa) { uintptr_t tid, x; int error = 0; const char *iwmesg; int ipri, itimo; +#ifdef KDTRACE_HOOKS + uint64_t sleep_time = 0; +#endif #ifdef LOCK_PROFILING uint64_t waittime = 0; int contested = 0; #endif if (__predict_false(panicstr != NULL)) goto out; tid = (uintptr_t)curthread; if (LK_CAN_WITNESS(flags)) WITNESS_CHECKORDER(&lk->lock_object, LOP_NEWORDER, file, line, flags & LK_INTERLOCK ? ilk : NULL); for (;;) { if (lockmgr_slock_try(lk, &x, flags, false)) break; #ifdef HWPMC_HOOKS PMC_SOFT_CALL( , , lock, failed); #endif lock_profile_obtain_lock_failed(&lk->lock_object, &contested, &waittime); /* * If the lock is already held by curthread in * exclusive way avoid a deadlock. */ if (LK_HOLDER(x) == tid) { LOCK_LOG2(lk, "%s: %p already held in exclusive mode", __func__, lk); error = EDEADLK; break; } /* * If the lock is expected to not sleep just give up * and return. */ if (LK_TRYOP(flags)) { LOCK_LOG2(lk, "%s: %p fails the try operation", __func__, lk); error = EBUSY; break; } /* * Acquire the sleepqueue chain lock because we * probabilly will need to manipulate waiters flags. */ sleepq_lock(&lk->lock_object); x = lk->lk_lock; retry_sleepq: /* * if the lock can be acquired in shared mode, try * again. */ if (LK_CAN_SHARE(x, flags, false)) { sleepq_release(&lk->lock_object); continue; } /* * Try to set the LK_SHARED_WAITERS flag. If we fail, * loop back and retry. */ if ((x & LK_SHARED_WAITERS) == 0) { if (!atomic_fcmpset_acq_ptr(&lk->lk_lock, &x, x | LK_SHARED_WAITERS)) { goto retry_sleepq; } LOCK_LOG2(lk, "%s: %p set shared waiters flag", __func__, lk); } if (lwa == NULL) { iwmesg = lk->lock_object.lo_name; ipri = lk->lk_pri; itimo = lk->lk_timo; } else { iwmesg = lwa->iwmesg; ipri = lwa->ipri; itimo = lwa->itimo; } /* * As far as we have been unable to acquire the * shared lock and the shared waiters flag is set, * we will sleep. */ +#ifdef KDTRACE_HOOKS + sleep_time -= lockstat_nsecs(&lk->lock_object); +#endif error = sleeplk(lk, flags, ilk, iwmesg, ipri, itimo, SQ_SHARED_QUEUE); +#ifdef KDTRACE_HOOKS + sleep_time += lockstat_nsecs(&lk->lock_object); +#endif flags &= ~LK_INTERLOCK; if (error) { LOCK_LOG3(lk, "%s: interrupted sleep for %p with %d", __func__, lk, error); break; } LOCK_LOG2(lk, "%s: %p resuming from the sleep queue", __func__, lk); } if (error == 0) { +#ifdef KDTRACE_HOOKS + if (sleep_time != 0) + LOCKSTAT_RECORD4(lockmgr__block, lk, sleep_time, + LOCKSTAT_READER, (x & LK_SHARE) == 0, + (x & LK_SHARE) == 0 ? 0 : LK_SHARERS(x)); +#endif #ifdef LOCK_PROFILING lockmgr_note_shared_acquire(lk, contested, waittime, file, line, flags); #else lockmgr_note_shared_acquire(lk, 0, 0, file, line, flags); #endif } out: lockmgr_exit(flags, ilk, 0); return (error); } static __noinline int lockmgr_xlock_hard(struct lock *lk, u_int flags, struct lock_object *ilk, const char *file, int line, struct lockmgr_wait *lwa) { struct lock_class *class; uintptr_t tid, x, v; int error = 0; const char *iwmesg; int ipri, itimo; +#ifdef KDTRACE_HOOKS + uint64_t sleep_time = 0; +#endif #ifdef LOCK_PROFILING uint64_t waittime = 0; int contested = 0; #endif if (__predict_false(panicstr != NULL)) goto out; tid = (uintptr_t)curthread; if (LK_CAN_WITNESS(flags)) WITNESS_CHECKORDER(&lk->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file, line, flags & LK_INTERLOCK ? ilk : NULL); /* * If curthread already holds the lock and this one is * allowed to recurse, simply recurse on it. */ if (lockmgr_xlocked(lk)) { if ((flags & LK_CANRECURSE) == 0 && (lk->lock_object.lo_flags & LO_RECURSABLE) == 0) { /* * If the lock is expected to not panic just * give up and return. */ if (LK_TRYOP(flags)) { LOCK_LOG2(lk, "%s: %p fails the try operation", __func__, lk); error = EBUSY; goto out; } if (flags & LK_INTERLOCK) { class = LOCK_CLASS(ilk); class->lc_unlock(ilk); } panic("%s: recursing on non recursive lockmgr %p " "@ %s:%d\n", __func__, lk, file, line); } lk->lk_recurse++; LOCK_LOG2(lk, "%s: %p recursing", __func__, lk); LOCK_LOG_LOCK("XLOCK", &lk->lock_object, 0, lk->lk_recurse, file, line); WITNESS_LOCK(&lk->lock_object, LOP_EXCLUSIVE | LK_TRYWIT(flags), file, line); TD_LOCKS_INC(curthread); goto out; } for (;;) { if (lk->lk_lock == LK_UNLOCKED && atomic_cmpset_acq_ptr(&lk->lk_lock, LK_UNLOCKED, tid)) break; #ifdef HWPMC_HOOKS PMC_SOFT_CALL( , , lock, failed); #endif lock_profile_obtain_lock_failed(&lk->lock_object, &contested, &waittime); /* * If the lock is expected to not sleep just give up * and return. */ if (LK_TRYOP(flags)) { LOCK_LOG2(lk, "%s: %p fails the try operation", __func__, lk); error = EBUSY; break; } /* * Acquire the sleepqueue chain lock because we * probabilly will need to manipulate waiters flags. */ sleepq_lock(&lk->lock_object); x = lk->lk_lock; retry_sleepq: /* * if the lock has been released while we spun on * the sleepqueue chain lock just try again. */ if (x == LK_UNLOCKED) { sleepq_release(&lk->lock_object); continue; } /* * The lock can be in the state where there is a * pending queue of waiters, but still no owner. * This happens when the lock is contested and an * owner is going to claim the lock. * If curthread is the one successfully acquiring it * claim lock ownership and return, preserving waiters * flags. */ v = x & (LK_ALL_WAITERS | LK_EXCLUSIVE_SPINNERS); if ((x & ~v) == LK_UNLOCKED) { v &= ~LK_EXCLUSIVE_SPINNERS; if (atomic_fcmpset_acq_ptr(&lk->lk_lock, &x, tid | v)) { sleepq_release(&lk->lock_object); LOCK_LOG2(lk, "%s: %p claimed by a new writer", __func__, lk); break; } goto retry_sleepq; } /* * Try to set the LK_EXCLUSIVE_WAITERS flag. If we * fail, loop back and retry. */ if ((x & LK_EXCLUSIVE_WAITERS) == 0) { if (!atomic_fcmpset_ptr(&lk->lk_lock, &x, x | LK_EXCLUSIVE_WAITERS)) { goto retry_sleepq; } LOCK_LOG2(lk, "%s: %p set excl waiters flag", __func__, lk); } if (lwa == NULL) { iwmesg = lk->lock_object.lo_name; ipri = lk->lk_pri; itimo = lk->lk_timo; } else { iwmesg = lwa->iwmesg; ipri = lwa->ipri; itimo = lwa->itimo; } /* * As far as we have been unable to acquire the * exclusive lock and the exclusive waiters flag * is set, we will sleep. */ +#ifdef KDTRACE_HOOKS + sleep_time -= lockstat_nsecs(&lk->lock_object); +#endif error = sleeplk(lk, flags, ilk, iwmesg, ipri, itimo, SQ_EXCLUSIVE_QUEUE); +#ifdef KDTRACE_HOOKS + sleep_time += lockstat_nsecs(&lk->lock_object); +#endif flags &= ~LK_INTERLOCK; if (error) { LOCK_LOG3(lk, "%s: interrupted sleep for %p with %d", __func__, lk, error); break; } LOCK_LOG2(lk, "%s: %p resuming from the sleep queue", __func__, lk); } if (error == 0) { +#ifdef KDTRACE_HOOKS + if (sleep_time != 0) + LOCKSTAT_RECORD4(lockmgr__block, lk, sleep_time, + LOCKSTAT_WRITER, (x & LK_SHARE) == 0, + (x & LK_SHARE) == 0 ? 0 : LK_SHARERS(x)); +#endif #ifdef LOCK_PROFILING lockmgr_note_exclusive_acquire(lk, contested, waittime, file, line, flags); #else lockmgr_note_exclusive_acquire(lk, 0, 0, file, line, flags); #endif } out: lockmgr_exit(flags, ilk, 0); return (error); } static __noinline int lockmgr_upgrade(struct lock *lk, u_int flags, struct lock_object *ilk, const char *file, int line, struct lockmgr_wait *lwa) { uintptr_t tid, x, v; int error = 0; int wakeup_swapper = 0; int op; if (__predict_false(panicstr != NULL)) goto out; tid = (uintptr_t)curthread; _lockmgr_assert(lk, KA_SLOCKED, file, line); v = lk->lk_lock; x = v & LK_ALL_WAITERS; v &= LK_EXCLUSIVE_SPINNERS; /* * Try to switch from one shared lock to an exclusive one. * We need to preserve waiters flags during the operation. */ if (atomic_cmpset_ptr(&lk->lk_lock, LK_SHARERS_LOCK(1) | x | v, tid | x)) { LOCK_LOG_LOCK("XUPGRADE", &lk->lock_object, 0, 0, file, line); WITNESS_UPGRADE(&lk->lock_object, LOP_EXCLUSIVE | LK_TRYWIT(flags), file, line); + LOCKSTAT_RECORD0(lockmgr__upgrade, lk); TD_SLOCKS_DEC(curthread); goto out; } op = flags & LK_TYPE_MASK; /* * In LK_TRYUPGRADE mode, do not drop the lock, * returning EBUSY instead. */ if (op == LK_TRYUPGRADE) { LOCK_LOG2(lk, "%s: %p failed the nowait upgrade", __func__, lk); error = EBUSY; goto out; } /* * We have been unable to succeed in upgrading, so just * give up the shared lock. */ wakeup_swapper |= wakeupshlk(lk, file, line); error = lockmgr_xlock_hard(lk, flags, ilk, file, line, lwa); flags &= ~LK_INTERLOCK; out: lockmgr_exit(flags, ilk, wakeup_swapper); return (error); } int lockmgr_lock_fast_path(struct lock *lk, u_int flags, struct lock_object *ilk, const char *file, int line) { struct lock_class *class; uintptr_t x, tid; u_int op; bool locked; if (__predict_false(panicstr != NULL)) return (0); op = flags & LK_TYPE_MASK; locked = false; switch (op) { case LK_SHARED: if (LK_CAN_WITNESS(flags)) WITNESS_CHECKORDER(&lk->lock_object, LOP_NEWORDER, file, line, flags & LK_INTERLOCK ? ilk : NULL); if (__predict_false(lk->lock_object.lo_flags & LK_NOSHARE)) break; if (lockmgr_slock_try(lk, &x, flags, true)) { lockmgr_note_shared_acquire(lk, 0, 0, file, line, flags); locked = true; } else { return (lockmgr_slock_hard(lk, flags, ilk, file, line, NULL)); } break; case LK_EXCLUSIVE: if (LK_CAN_WITNESS(flags)) WITNESS_CHECKORDER(&lk->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file, line, flags & LK_INTERLOCK ? ilk : NULL); tid = (uintptr_t)curthread; if (lk->lk_lock == LK_UNLOCKED && atomic_cmpset_acq_ptr(&lk->lk_lock, LK_UNLOCKED, tid)) { lockmgr_note_exclusive_acquire(lk, 0, 0, file, line, flags); locked = true; } else { return (lockmgr_xlock_hard(lk, flags, ilk, file, line, NULL)); } break; case LK_UPGRADE: case LK_TRYUPGRADE: return (lockmgr_upgrade(lk, flags, ilk, file, line, NULL)); default: break; } if (__predict_true(locked)) { if (__predict_false(flags & LK_INTERLOCK)) { class = LOCK_CLASS(ilk); class->lc_unlock(ilk); } return (0); } else { return (__lockmgr_args(lk, flags, ilk, LK_WMESG_DEFAULT, LK_PRIO_DEFAULT, LK_TIMO_DEFAULT, file, line)); } } static __noinline int lockmgr_sunlock_hard(struct lock *lk, uintptr_t x, u_int flags, struct lock_object *ilk, const char *file, int line) { int wakeup_swapper = 0; if (__predict_false(panicstr != NULL)) goto out; wakeup_swapper = wakeupshlk(lk, file, line); out: lockmgr_exit(flags, ilk, wakeup_swapper); return (0); } static __noinline int lockmgr_xunlock_hard(struct lock *lk, uintptr_t x, u_int flags, struct lock_object *ilk, const char *file, int line) { uintptr_t tid, v; int wakeup_swapper = 0; u_int realexslp; int queue; if (__predict_false(panicstr != NULL)) goto out; tid = (uintptr_t)curthread; /* * As first option, treact the lock as if it has not * any waiter. * Fix-up the tid var if the lock has been disowned. */ if (LK_HOLDER(x) == LK_KERNPROC) tid = LK_KERNPROC; else { WITNESS_UNLOCK(&lk->lock_object, LOP_EXCLUSIVE, file, line); TD_LOCKS_DEC(curthread); } LOCK_LOG_LOCK("XUNLOCK", &lk->lock_object, 0, lk->lk_recurse, file, line); /* * The lock is held in exclusive mode. * If the lock is recursed also, then unrecurse it. */ if (lockmgr_xlocked_v(x) && lockmgr_recursed(lk)) { LOCK_LOG2(lk, "%s: %p unrecursing", __func__, lk); lk->lk_recurse--; goto out; } if (tid != LK_KERNPROC) - lock_profile_release_lock(&lk->lock_object); + LOCKSTAT_PROFILE_RELEASE_RWLOCK(lockmgr__release, lk, + LOCKSTAT_WRITER); if (x == tid && atomic_cmpset_rel_ptr(&lk->lk_lock, tid, LK_UNLOCKED)) goto out; sleepq_lock(&lk->lock_object); x = lk->lk_lock; v = LK_UNLOCKED; /* * If the lock has exclusive waiters, give them * preference in order to avoid deadlock with * shared runners up. * If interruptible sleeps left the exclusive queue * empty avoid a starvation for the threads sleeping * on the shared queue by giving them precedence * and cleaning up the exclusive waiters bit anyway. * Please note that lk_exslpfail count may be lying * about the real number of waiters with the * LK_SLEEPFAIL flag on because they may be used in * conjunction with interruptible sleeps so * lk_exslpfail might be considered an 'upper limit' * bound, including the edge cases. */ MPASS((x & LK_EXCLUSIVE_SPINNERS) == 0); realexslp = sleepq_sleepcnt(&lk->lock_object, SQ_EXCLUSIVE_QUEUE); if ((x & LK_EXCLUSIVE_WAITERS) != 0 && realexslp != 0) { if (lk->lk_exslpfail < realexslp) { lk->lk_exslpfail = 0; queue = SQ_EXCLUSIVE_QUEUE; v |= (x & LK_SHARED_WAITERS); } else { lk->lk_exslpfail = 0; LOCK_LOG2(lk, "%s: %p has only LK_SLEEPFAIL sleepers", __func__, lk); LOCK_LOG2(lk, "%s: %p waking up threads on the exclusive queue", __func__, lk); wakeup_swapper = sleepq_broadcast(&lk->lock_object, SLEEPQ_LK, 0, SQ_EXCLUSIVE_QUEUE); queue = SQ_SHARED_QUEUE; } } else { /* * Exclusive waiters sleeping with LK_SLEEPFAIL * on and using interruptible sleeps/timeout * may have left spourious lk_exslpfail counts * on, so clean it up anyway. */ lk->lk_exslpfail = 0; queue = SQ_SHARED_QUEUE; } LOCK_LOG3(lk, "%s: %p waking up threads on the %s queue", __func__, lk, queue == SQ_SHARED_QUEUE ? "shared" : "exclusive"); atomic_store_rel_ptr(&lk->lk_lock, v); wakeup_swapper |= sleepq_broadcast(&lk->lock_object, SLEEPQ_LK, 0, queue); sleepq_release(&lk->lock_object); out: lockmgr_exit(flags, ilk, wakeup_swapper); return (0); } int lockmgr_unlock_fast_path(struct lock *lk, u_int flags, struct lock_object *ilk) { struct lock_class *class; uintptr_t x, tid; const char *file; int line; if (__predict_false(panicstr != NULL)) return (0); file = __FILE__; line = __LINE__; _lockmgr_assert(lk, KA_LOCKED, file, line); x = lk->lk_lock; if (__predict_true(x & LK_SHARE) != 0) { if (lockmgr_sunlock_try(lk, &x)) { lockmgr_note_shared_release(lk, file, line); } else { return (lockmgr_sunlock_hard(lk, x, flags, ilk, file, line)); } } else { tid = (uintptr_t)curthread; if (!lockmgr_recursed(lk) && atomic_cmpset_rel_ptr(&lk->lk_lock, tid, LK_UNLOCKED)) { lockmgr_note_exclusive_release(lk, file, line); } else { return (lockmgr_xunlock_hard(lk, x, flags, ilk, file, line)); } } if (__predict_false(flags & LK_INTERLOCK)) { class = LOCK_CLASS(ilk); class->lc_unlock(ilk); } return (0); } int __lockmgr_args(struct lock *lk, u_int flags, struct lock_object *ilk, const char *wmesg, int pri, int timo, const char *file, int line) { GIANT_DECLARE; struct lockmgr_wait lwa; struct lock_class *class; const char *iwmesg; uintptr_t tid, v, x; u_int op, realexslp; int error, ipri, itimo, queue, wakeup_swapper; #ifdef LOCK_PROFILING uint64_t waittime = 0; int contested = 0; #endif if (panicstr != NULL) return (0); error = 0; tid = (uintptr_t)curthread; op = (flags & LK_TYPE_MASK); iwmesg = (wmesg == LK_WMESG_DEFAULT) ? lk->lock_object.lo_name : wmesg; ipri = (pri == LK_PRIO_DEFAULT) ? lk->lk_pri : pri; itimo = (timo == LK_TIMO_DEFAULT) ? lk->lk_timo : timo; lwa.iwmesg = iwmesg; lwa.ipri = ipri; lwa.itimo = itimo; MPASS((flags & ~LK_TOTAL_MASK) == 0); KASSERT((op & (op - 1)) == 0, ("%s: Invalid requested operation @ %s:%d", __func__, file, line)); KASSERT((flags & (LK_NOWAIT | LK_SLEEPFAIL)) == 0 || (op != LK_DOWNGRADE && op != LK_RELEASE), ("%s: Invalid flags in regard of the operation desired @ %s:%d", __func__, file, line)); KASSERT((flags & LK_INTERLOCK) == 0 || ilk != NULL, ("%s: LK_INTERLOCK passed without valid interlock @ %s:%d", __func__, file, line)); KASSERT(kdb_active != 0 || !TD_IS_IDLETHREAD(curthread), ("%s: idle thread %p on lockmgr %s @ %s:%d", __func__, curthread, lk->lock_object.lo_name, file, line)); class = (flags & LK_INTERLOCK) ? LOCK_CLASS(ilk) : NULL; if (lk->lock_object.lo_flags & LK_NOSHARE) { switch (op) { case LK_SHARED: op = LK_EXCLUSIVE; break; case LK_UPGRADE: case LK_TRYUPGRADE: case LK_DOWNGRADE: _lockmgr_assert(lk, KA_XLOCKED | KA_NOTRECURSED, file, line); if (flags & LK_INTERLOCK) class->lc_unlock(ilk); return (0); } } wakeup_swapper = 0; switch (op) { case LK_SHARED: return (lockmgr_slock_hard(lk, flags, ilk, file, line, &lwa)); break; case LK_UPGRADE: case LK_TRYUPGRADE: return (lockmgr_upgrade(lk, flags, ilk, file, line, &lwa)); break; case LK_EXCLUSIVE: return (lockmgr_xlock_hard(lk, flags, ilk, file, line, &lwa)); break; case LK_DOWNGRADE: _lockmgr_assert(lk, KA_XLOCKED, file, line); - LOCK_LOG_LOCK("XDOWNGRADE", &lk->lock_object, 0, 0, file, line); WITNESS_DOWNGRADE(&lk->lock_object, 0, file, line); /* * Panic if the lock is recursed. */ if (lockmgr_xlocked(lk) && lockmgr_recursed(lk)) { if (flags & LK_INTERLOCK) class->lc_unlock(ilk); panic("%s: downgrade a recursed lockmgr %s @ %s:%d\n", __func__, iwmesg, file, line); } TD_SLOCKS_INC(curthread); /* * In order to preserve waiters flags, just spin. */ for (;;) { x = lk->lk_lock; MPASS((x & LK_EXCLUSIVE_SPINNERS) == 0); x &= LK_ALL_WAITERS; if (atomic_cmpset_rel_ptr(&lk->lk_lock, tid | x, LK_SHARERS_LOCK(1) | x)) break; cpu_spinwait(); } + LOCK_LOG_LOCK("XDOWNGRADE", &lk->lock_object, 0, 0, file, line); + LOCKSTAT_RECORD0(lockmgr__downgrade, lk); break; case LK_RELEASE: _lockmgr_assert(lk, KA_LOCKED, file, line); x = lk->lk_lock; if (__predict_true(x & LK_SHARE) != 0) { return (lockmgr_sunlock_hard(lk, x, flags, ilk, file, line)); } else { return (lockmgr_xunlock_hard(lk, x, flags, ilk, file, line)); } break; case LK_DRAIN: if (LK_CAN_WITNESS(flags)) WITNESS_CHECKORDER(&lk->lock_object, LOP_NEWORDER | LOP_EXCLUSIVE, file, line, flags & LK_INTERLOCK ? ilk : NULL); /* * Trying to drain a lock we already own will result in a * deadlock. */ if (lockmgr_xlocked(lk)) { if (flags & LK_INTERLOCK) class->lc_unlock(ilk); panic("%s: draining %s with the lock held @ %s:%d\n", __func__, iwmesg, file, line); } for (;;) { if (lk->lk_lock == LK_UNLOCKED && atomic_cmpset_acq_ptr(&lk->lk_lock, LK_UNLOCKED, tid)) break; #ifdef HWPMC_HOOKS PMC_SOFT_CALL( , , lock, failed); #endif lock_profile_obtain_lock_failed(&lk->lock_object, &contested, &waittime); /* * If the lock is expected to not sleep just give up * and return. */ if (LK_TRYOP(flags)) { LOCK_LOG2(lk, "%s: %p fails the try operation", __func__, lk); error = EBUSY; break; } /* * Acquire the sleepqueue chain lock because we * probabilly will need to manipulate waiters flags. */ sleepq_lock(&lk->lock_object); x = lk->lk_lock; /* * if the lock has been released while we spun on * the sleepqueue chain lock just try again. */ if (x == LK_UNLOCKED) { sleepq_release(&lk->lock_object); continue; } v = x & (LK_ALL_WAITERS | LK_EXCLUSIVE_SPINNERS); if ((x & ~v) == LK_UNLOCKED) { v = (x & ~LK_EXCLUSIVE_SPINNERS); /* * If interruptible sleeps left the exclusive * queue empty avoid a starvation for the * threads sleeping on the shared queue by * giving them precedence and cleaning up the * exclusive waiters bit anyway. * Please note that lk_exslpfail count may be * lying about the real number of waiters with * the LK_SLEEPFAIL flag on because they may * be used in conjunction with interruptible * sleeps so lk_exslpfail might be considered * an 'upper limit' bound, including the edge * cases. */ if (v & LK_EXCLUSIVE_WAITERS) { queue = SQ_EXCLUSIVE_QUEUE; v &= ~LK_EXCLUSIVE_WAITERS; } else { /* * Exclusive waiters sleeping with * LK_SLEEPFAIL on and using * interruptible sleeps/timeout may * have left spourious lk_exslpfail * counts on, so clean it up anyway. */ MPASS(v & LK_SHARED_WAITERS); lk->lk_exslpfail = 0; queue = SQ_SHARED_QUEUE; v &= ~LK_SHARED_WAITERS; } if (queue == SQ_EXCLUSIVE_QUEUE) { realexslp = sleepq_sleepcnt(&lk->lock_object, SQ_EXCLUSIVE_QUEUE); if (lk->lk_exslpfail >= realexslp) { lk->lk_exslpfail = 0; queue = SQ_SHARED_QUEUE; v &= ~LK_SHARED_WAITERS; if (realexslp != 0) { LOCK_LOG2(lk, "%s: %p has only LK_SLEEPFAIL sleepers", __func__, lk); LOCK_LOG2(lk, "%s: %p waking up threads on the exclusive queue", __func__, lk); wakeup_swapper = sleepq_broadcast( &lk->lock_object, SLEEPQ_LK, 0, SQ_EXCLUSIVE_QUEUE); } } else lk->lk_exslpfail = 0; } if (!atomic_cmpset_ptr(&lk->lk_lock, x, v)) { sleepq_release(&lk->lock_object); continue; } LOCK_LOG3(lk, "%s: %p waking up all threads on the %s queue", __func__, lk, queue == SQ_SHARED_QUEUE ? "shared" : "exclusive"); wakeup_swapper |= sleepq_broadcast( &lk->lock_object, SLEEPQ_LK, 0, queue); /* * If shared waiters have been woken up we need * to wait for one of them to acquire the lock * before to set the exclusive waiters in * order to avoid a deadlock. */ if (queue == SQ_SHARED_QUEUE) { for (v = lk->lk_lock; (v & LK_SHARE) && !LK_SHARERS(v); v = lk->lk_lock) cpu_spinwait(); } } /* * Try to set the LK_EXCLUSIVE_WAITERS flag. If we * fail, loop back and retry. */ if ((x & LK_EXCLUSIVE_WAITERS) == 0) { if (!atomic_cmpset_ptr(&lk->lk_lock, x, x | LK_EXCLUSIVE_WAITERS)) { sleepq_release(&lk->lock_object); continue; } LOCK_LOG2(lk, "%s: %p set drain waiters flag", __func__, lk); } /* * As far as we have been unable to acquire the * exclusive lock and the exclusive waiters flag * is set, we will sleep. */ if (flags & LK_INTERLOCK) { class->lc_unlock(ilk); flags &= ~LK_INTERLOCK; } GIANT_SAVE(); sleepq_add(&lk->lock_object, NULL, iwmesg, SLEEPQ_LK, SQ_EXCLUSIVE_QUEUE); sleepq_wait(&lk->lock_object, ipri & PRIMASK); GIANT_RESTORE(); LOCK_LOG2(lk, "%s: %p resuming from the sleep queue", __func__, lk); } if (error == 0) { lock_profile_obtain_lock_success(&lk->lock_object, contested, waittime, file, line); LOCK_LOG_LOCK("DRAIN", &lk->lock_object, 0, lk->lk_recurse, file, line); WITNESS_LOCK(&lk->lock_object, LOP_EXCLUSIVE | LK_TRYWIT(flags), file, line); TD_LOCKS_INC(curthread); STACK_SAVE(lk); } break; default: if (flags & LK_INTERLOCK) class->lc_unlock(ilk); panic("%s: unknown lockmgr request 0x%x\n", __func__, op); } if (flags & LK_INTERLOCK) class->lc_unlock(ilk); if (wakeup_swapper) kick_proc0(); return (error); } void _lockmgr_disown(struct lock *lk, const char *file, int line) { uintptr_t tid, x; if (SCHEDULER_STOPPED()) return; tid = (uintptr_t)curthread; _lockmgr_assert(lk, KA_XLOCKED, file, line); /* * Panic if the lock is recursed. */ if (lockmgr_xlocked(lk) && lockmgr_recursed(lk)) panic("%s: disown a recursed lockmgr @ %s:%d\n", __func__, file, line); /* * If the owner is already LK_KERNPROC just skip the whole operation. */ if (LK_HOLDER(lk->lk_lock) != tid) return; lock_profile_release_lock(&lk->lock_object); + LOCKSTAT_RECORD1(lockmgr__disown, lk, LOCKSTAT_WRITER); LOCK_LOG_LOCK("XDISOWN", &lk->lock_object, 0, 0, file, line); WITNESS_UNLOCK(&lk->lock_object, LOP_EXCLUSIVE, file, line); TD_LOCKS_DEC(curthread); STACK_SAVE(lk); /* * In order to preserve waiters flags, just spin. */ for (;;) { x = lk->lk_lock; MPASS((x & LK_EXCLUSIVE_SPINNERS) == 0); x &= LK_ALL_WAITERS; if (atomic_cmpset_rel_ptr(&lk->lk_lock, tid | x, LK_KERNPROC | x)) return; cpu_spinwait(); } } void lockmgr_printinfo(const struct lock *lk) { struct thread *td; uintptr_t x; if (lk->lk_lock == LK_UNLOCKED) printf("lock type %s: UNLOCKED\n", lk->lock_object.lo_name); else if (lk->lk_lock & LK_SHARE) printf("lock type %s: SHARED (count %ju)\n", lk->lock_object.lo_name, (uintmax_t)LK_SHARERS(lk->lk_lock)); else { td = lockmgr_xholder(lk); if (td == (struct thread *)LK_KERNPROC) printf("lock type %s: EXCL by KERNPROC\n", lk->lock_object.lo_name); else printf("lock type %s: EXCL by thread %p " "(pid %d, %s, tid %d)\n", lk->lock_object.lo_name, td, td->td_proc->p_pid, td->td_proc->p_comm, td->td_tid); } x = lk->lk_lock; if (x & LK_EXCLUSIVE_WAITERS) printf(" with exclusive waiters pending\n"); if (x & LK_SHARED_WAITERS) printf(" with shared waiters pending\n"); if (x & LK_EXCLUSIVE_SPINNERS) printf(" with exclusive spinners pending\n"); STACK_PRINT(lk); } int lockstatus(const struct lock *lk) { uintptr_t v, x; int ret; ret = LK_SHARED; x = lk->lk_lock; v = LK_HOLDER(x); if ((x & LK_SHARE) == 0) { if (v == (uintptr_t)curthread || v == LK_KERNPROC) ret = LK_EXCLUSIVE; else ret = LK_EXCLOTHER; } else if (x == LK_UNLOCKED) ret = 0; return (ret); } #ifdef INVARIANT_SUPPORT FEATURE(invariant_support, "Support for modules compiled with INVARIANTS option"); #ifndef INVARIANTS #undef _lockmgr_assert #endif void _lockmgr_assert(const struct lock *lk, int what, const char *file, int line) { int slocked = 0; if (panicstr != NULL) return; switch (what) { case KA_SLOCKED: case KA_SLOCKED | KA_NOTRECURSED: case KA_SLOCKED | KA_RECURSED: slocked = 1; case KA_LOCKED: case KA_LOCKED | KA_NOTRECURSED: case KA_LOCKED | KA_RECURSED: #ifdef WITNESS /* * We cannot trust WITNESS if the lock is held in exclusive * mode and a call to lockmgr_disown() happened. * Workaround this skipping the check if the lock is held in * exclusive mode even for the KA_LOCKED case. */ if (slocked || (lk->lk_lock & LK_SHARE)) { witness_assert(&lk->lock_object, what, file, line); break; } #endif if (lk->lk_lock == LK_UNLOCKED || ((lk->lk_lock & LK_SHARE) == 0 && (slocked || (!lockmgr_xlocked(lk) && !lockmgr_disowned(lk))))) panic("Lock %s not %slocked @ %s:%d\n", lk->lock_object.lo_name, slocked ? "share" : "", file, line); if ((lk->lk_lock & LK_SHARE) == 0) { if (lockmgr_recursed(lk)) { if (what & KA_NOTRECURSED) panic("Lock %s recursed @ %s:%d\n", lk->lock_object.lo_name, file, line); } else if (what & KA_RECURSED) panic("Lock %s not recursed @ %s:%d\n", lk->lock_object.lo_name, file, line); } break; case KA_XLOCKED: case KA_XLOCKED | KA_NOTRECURSED: case KA_XLOCKED | KA_RECURSED: if (!lockmgr_xlocked(lk) && !lockmgr_disowned(lk)) panic("Lock %s not exclusively locked @ %s:%d\n", lk->lock_object.lo_name, file, line); if (lockmgr_recursed(lk)) { if (what & KA_NOTRECURSED) panic("Lock %s recursed @ %s:%d\n", lk->lock_object.lo_name, file, line); } else if (what & KA_RECURSED) panic("Lock %s not recursed @ %s:%d\n", lk->lock_object.lo_name, file, line); break; case KA_UNLOCKED: if (lockmgr_xlocked(lk) || lockmgr_disowned(lk)) panic("Lock %s exclusively locked @ %s:%d\n", lk->lock_object.lo_name, file, line); break; default: panic("Unknown lockmgr assertion: %d @ %s:%d\n", what, file, line); } } #endif #ifdef DDB int lockmgr_chain(struct thread *td, struct thread **ownerp) { struct lock *lk; lk = td->td_wchan; if (LOCK_CLASS(&lk->lock_object) != &lock_class_lockmgr) return (0); db_printf("blocked on lockmgr %s", lk->lock_object.lo_name); if (lk->lk_lock & LK_SHARE) db_printf("SHARED (count %ju)\n", (uintmax_t)LK_SHARERS(lk->lk_lock)); else db_printf("EXCL\n"); *ownerp = lockmgr_xholder(lk); return (1); } static void db_show_lockmgr(const struct lock_object *lock) { struct thread *td; const struct lock *lk; lk = (const struct lock *)lock; db_printf(" state: "); if (lk->lk_lock == LK_UNLOCKED) db_printf("UNLOCKED\n"); else if (lk->lk_lock & LK_SHARE) db_printf("SLOCK: %ju\n", (uintmax_t)LK_SHARERS(lk->lk_lock)); else { td = lockmgr_xholder(lk); if (td == (struct thread *)LK_KERNPROC) db_printf("XLOCK: LK_KERNPROC\n"); else db_printf("XLOCK: %p (tid %d, pid %d, \"%s\")\n", td, td->td_tid, td->td_proc->p_pid, td->td_proc->p_comm); if (lockmgr_recursed(lk)) db_printf(" recursed: %d\n", lk->lk_recurse); } db_printf(" waiters: "); switch (lk->lk_lock & LK_ALL_WAITERS) { case LK_SHARED_WAITERS: db_printf("shared\n"); break; case LK_EXCLUSIVE_WAITERS: db_printf("exclusive\n"); break; case LK_ALL_WAITERS: db_printf("shared and exclusive\n"); break; default: db_printf("none\n"); } db_printf(" spinners: "); if (lk->lk_lock & LK_EXCLUSIVE_SPINNERS) db_printf("exclusive\n"); else db_printf("none\n"); } #endif Index: head/sys/kern/kern_lockstat.c =================================================================== --- head/sys/kern/kern_lockstat.c (revision 351360) +++ head/sys/kern/kern_lockstat.c (revision 351361) @@ -1,84 +1,92 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright 2008-2009 Stacey Son * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include SDT_PROVIDER_DEFINE(lockstat); SDT_PROBE_DEFINE1(lockstat, , , adaptive__acquire, "struct mtx *"); SDT_PROBE_DEFINE1(lockstat, , , adaptive__release, "struct mtx *"); SDT_PROBE_DEFINE2(lockstat, , , adaptive__spin, "struct mtx *", "uint64_t"); SDT_PROBE_DEFINE2(lockstat, , , adaptive__block, "struct mtx *", "uint64_t"); SDT_PROBE_DEFINE1(lockstat, , , spin__acquire, "struct mtx *"); SDT_PROBE_DEFINE1(lockstat, , , spin__release, "struct mtx *"); SDT_PROBE_DEFINE2(lockstat, , , spin__spin, "struct mtx *", "uint64_t"); SDT_PROBE_DEFINE2(lockstat, , , rw__acquire, "struct rwlock *", "int"); SDT_PROBE_DEFINE2(lockstat, , , rw__release, "struct rwlock *", "int"); SDT_PROBE_DEFINE5(lockstat, , , rw__block, "struct rwlock *", "uint64_t", "int", "int", "int"); SDT_PROBE_DEFINE2(lockstat, , , rw__spin, "struct rwlock *", "uint64_t"); SDT_PROBE_DEFINE1(lockstat, , , rw__upgrade, "struct rwlock *"); SDT_PROBE_DEFINE1(lockstat, , , rw__downgrade, "struct rwlock *"); SDT_PROBE_DEFINE2(lockstat, , , sx__acquire, "struct sx *", "int"); SDT_PROBE_DEFINE2(lockstat, , , sx__release, "struct sx *", "int"); SDT_PROBE_DEFINE5(lockstat, , , sx__block, "struct sx *", "uint64_t", "int", "int", "int"); SDT_PROBE_DEFINE2(lockstat, , , sx__spin, "struct sx *", "uint64_t"); SDT_PROBE_DEFINE1(lockstat, , , sx__upgrade, "struct sx *"); SDT_PROBE_DEFINE1(lockstat, , , sx__downgrade, "struct sx *"); +SDT_PROBE_DEFINE2(lockstat, , , lockmgr__acquire, "struct lock *", "int"); +SDT_PROBE_DEFINE2(lockstat, , , lockmgr__release, "struct lock *", "int"); +SDT_PROBE_DEFINE2(lockstat, , , lockmgr__disown, "struct lock *", "int"); +SDT_PROBE_DEFINE5(lockstat, , , lockmgr__block, "struct lock *", "uint64_t", + "int", "int", "int"); +SDT_PROBE_DEFINE1(lockstat, , , lockmgr__upgrade, "struct lock *"); +SDT_PROBE_DEFINE1(lockstat, , , lockmgr__downgrade, "struct lock *"); + SDT_PROBE_DEFINE2(lockstat, , , thread__spin, "struct mtx *", "uint64_t"); volatile bool __read_frequently lockstat_enabled; uint64_t lockstat_nsecs(struct lock_object *lo) { struct bintime bt; uint64_t ns; if (!lockstat_enabled) return (0); if ((lo->lo_flags & LO_NOPROFILE) != 0) return (0); binuptime(&bt); ns = bt.sec * (uint64_t)1000000000; ns += ((uint64_t)1000000000 * (uint32_t)(bt.frac >> 32)) >> 32; return (ns); } Index: head/sys/sys/lockstat.h =================================================================== --- head/sys/sys/lockstat.h (revision 351360) +++ head/sys/sys/lockstat.h (revision 351361) @@ -1,142 +1,149 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2008-2009 Stacey Son * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ /* * DTrace lockstat provider definitions */ #ifndef _SYS_LOCKSTAT_H #define _SYS_LOCKSTAT_H #ifdef _KERNEL #include #include #include SDT_PROVIDER_DECLARE(lockstat); SDT_PROBE_DECLARE(lockstat, , , adaptive__acquire); SDT_PROBE_DECLARE(lockstat, , , adaptive__release); SDT_PROBE_DECLARE(lockstat, , , adaptive__spin); SDT_PROBE_DECLARE(lockstat, , , adaptive__block); SDT_PROBE_DECLARE(lockstat, , , spin__acquire); SDT_PROBE_DECLARE(lockstat, , , spin__release); SDT_PROBE_DECLARE(lockstat, , , spin__spin); SDT_PROBE_DECLARE(lockstat, , , rw__acquire); SDT_PROBE_DECLARE(lockstat, , , rw__release); SDT_PROBE_DECLARE(lockstat, , , rw__block); SDT_PROBE_DECLARE(lockstat, , , rw__spin); SDT_PROBE_DECLARE(lockstat, , , rw__upgrade); SDT_PROBE_DECLARE(lockstat, , , rw__downgrade); SDT_PROBE_DECLARE(lockstat, , , sx__acquire); SDT_PROBE_DECLARE(lockstat, , , sx__release); SDT_PROBE_DECLARE(lockstat, , , sx__block); SDT_PROBE_DECLARE(lockstat, , , sx__spin); SDT_PROBE_DECLARE(lockstat, , , sx__upgrade); SDT_PROBE_DECLARE(lockstat, , , sx__downgrade); +SDT_PROBE_DECLARE(lockstat, , , lockmgr__acquire); +SDT_PROBE_DECLARE(lockstat, , , lockmgr__release); +SDT_PROBE_DECLARE(lockstat, , , lockmgr__disown); +SDT_PROBE_DECLARE(lockstat, , , lockmgr__block); +SDT_PROBE_DECLARE(lockstat, , , lockmgr__upgrade); +SDT_PROBE_DECLARE(lockstat, , , lockmgr__downgrade); + SDT_PROBE_DECLARE(lockstat, , , thread__spin); #define LOCKSTAT_WRITER 0 #define LOCKSTAT_READER 1 extern volatile bool lockstat_enabled; #ifdef KDTRACE_HOOKS #define LOCKSTAT_RECORD0(probe, lp) \ SDT_PROBE1(lockstat, , , probe, lp) #define LOCKSTAT_RECORD1(probe, lp, arg1) \ SDT_PROBE2(lockstat, , , probe, lp, arg1) #define LOCKSTAT_RECORD2(probe, lp, arg1, arg2) \ SDT_PROBE3(lockstat, , , probe, lp, arg1, arg2) #define LOCKSTAT_RECORD3(probe, lp, arg1, arg2, arg3) \ SDT_PROBE4(lockstat, , , probe, lp, arg1, arg2, arg3) #define LOCKSTAT_RECORD4(probe, lp, arg1, arg2, arg3, arg4) \ SDT_PROBE5(lockstat, , , probe, lp, arg1, arg2, arg3, arg4) #define LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(probe, lp, c, wt, f, l) do { \ lock_profile_obtain_lock_success(&(lp)->lock_object, c, wt, f, l); \ LOCKSTAT_RECORD0(probe, lp); \ } while (0) #define LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(probe, lp, c, wt, f, l, a) do { \ lock_profile_obtain_lock_success(&(lp)->lock_object, c, wt, f, l); \ LOCKSTAT_RECORD1(probe, lp, a); \ } while (0) #define LOCKSTAT_PROFILE_RELEASE_LOCK(probe, lp) do { \ lock_profile_release_lock(&(lp)->lock_object); \ LOCKSTAT_RECORD0(probe, lp); \ } while (0) #define LOCKSTAT_PROFILE_RELEASE_RWLOCK(probe, lp, a) do { \ lock_profile_release_lock(&(lp)->lock_object); \ LOCKSTAT_RECORD1(probe, lp, a); \ } while (0) #define LOCKSTAT_PROFILE_ENABLED(probe) __predict_false(lockstat_enabled) struct lock_object; uint64_t lockstat_nsecs(struct lock_object *); #else /* !KDTRACE_HOOKS */ #define LOCKSTAT_RECORD0(probe, lp) #define LOCKSTAT_RECORD1(probe, lp, arg1) #define LOCKSTAT_RECORD2(probe, lp, arg1, arg2) #define LOCKSTAT_RECORD3(probe, lp, arg1, arg2, arg3) #define LOCKSTAT_RECORD4(probe, lp, arg1, arg2, arg3, arg4) #define LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(probe, lp, c, wt, f, l) \ lock_profile_obtain_lock_success(&(lp)->lock_object, c, wt, f, l) #define LOCKSTAT_PROFILE_OBTAIN_RWLOCK_SUCCESS(probe, lp, c, wt, f, l, a) \ LOCKSTAT_PROFILE_OBTAIN_LOCK_SUCCESS(probe, lp, c, wt, f, l) #define LOCKSTAT_PROFILE_RELEASE_LOCK(probe, lp) \ lock_profile_release_lock(&(lp)->lock_object) #define LOCKSTAT_PROFILE_RELEASE_RWLOCK(probe, lp, a) \ LOCKSTAT_PROFILE_RELEASE_LOCK(probe, lp) #define LOCKSTAT_PROFILE_ENABLED(probe) 0 #endif /* !KDTRACE_HOOKS */ #endif /* _KERNEL */ #endif /* _SYS_LOCKSTAT_H */