]> git.saurik.com Git - apple/xnu.git/blobdiff - bsd/kern/kdebug.c
xnu-6153.81.5.tar.gz
[apple/xnu.git] / bsd / kern / kdebug.c
index 6d7fc0902c1c92f3d35e81740ddb6ce252535593..eb78ca89a87fe4f0b93df590caf4a2b3d7c3c0ef 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000-2016 Apple Inc. All rights reserved.
+ * Copyright (c) 2000-2019 Apple Inc. All rights reserved.
  *
  * @Apple_LICENSE_HEADER_START@
  *
@@ -20,8 +20,6 @@
  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
  */
 
-#include <machine/spl.h>
-
 #include <sys/errno.h>
 #include <sys/param.h>
 #include <sys/systm.h>
@@ -39,6 +37,7 @@
 #include <mach/mach_types.h>
 #include <mach/mach_time.h>
 #include <mach/mach_vm.h>
+#include <machine/atomic.h>
 #include <machine/machine_routines.h>
 
 #include <mach/machine.h>
@@ -48,6 +47,7 @@
 #include <i386/rtclock_protos.h>
 #include <i386/mp.h>
 #include <i386/machine_routines.h>
+#include <i386/tsc.h>
 #endif
 
 #include <kern/clock.h>
@@ -73,9 +73,9 @@
 #include <sys/fcntl.h>
 #include <sys/file_internal.h>
 #include <sys/ubc.h>
-#include <sys/param.h>                 /* for isset() */
+#include <sys/param.h>                  /* for isset() */
 
-#include <mach/mach_host.h>            /* for host_info() */
+#include <mach/mach_host.h>             /* for host_info() */
 #include <libkern/OSAtomic.h>
 
 #include <machine/pal_routines.h>
@@ -84,8 +84,6 @@
 /*
  * IOP(s)
  *
- * https://coreoswiki.apple.com/wiki/pages/U6z3i0q9/Consistent_Logging_Implementers_Guide.html
- *
  * IOP(s) are auxiliary cores that want to participate in kdebug event logging.
  * They are registered dynamically. Each is assigned a cpu_id at registration.
  *
  */
 
 typedef struct kd_iop {
-       kd_callback_t   callback;
-       uint32_t        cpu_id;
-       uint64_t        last_timestamp; /* Prevent timer rollback */
-       struct kd_iop*  next;
+       kd_callback_t   callback;
+       uint32_t        cpu_id;
+       uint64_t        last_timestamp; /* Prevent timer rollback */
+       struct kd_iop*  next;
 } kd_iop_t;
 
 static kd_iop_t* kd_iops = NULL;
@@ -153,7 +151,8 @@ static mach_port_t  kdbg_typefilter_memory_entry;
  */
 #define TYPEFILTER_ALLOC_SIZE MAX(round_page_32(KDBG_TYPEFILTER_BITMAP_SIZE), KDBG_TYPEFILTER_BITMAP_SIZE)
 
-static typefilter_t typefilter_create(void)
+static typefilter_t
+typefilter_create(void)
 {
        typefilter_t tf;
        if (KERN_SUCCESS == kmem_alloc(kernel_map, (vm_offset_t*)&tf, TYPEFILTER_ALLOC_SIZE, VM_KERN_MEMORY_DIAG)) {
@@ -163,58 +162,72 @@ static typefilter_t typefilter_create(void)
        return NULL;
 }
 
-static void typefilter_deallocate(typefilter_t tf)
+static void
+typefilter_deallocate(typefilter_t tf)
 {
-       assert(tf);
+       assert(tf != NULL);
        assert(tf != kdbg_typefilter);
        kmem_free(kernel_map, (vm_offset_t)tf, TYPEFILTER_ALLOC_SIZE);
 }
 
-static void typefilter_copy(typefilter_t dst, typefilter_t src)
+static void
+typefilter_copy(typefilter_t dst, typefilter_t src)
 {
-       assert(src);
-       assert(dst);
+       assert(src != NULL);
+       assert(dst != NULL);
        memcpy(dst, src, KDBG_TYPEFILTER_BITMAP_SIZE);
 }
 
-static void typefilter_reject_all(typefilter_t tf)
+static void
+typefilter_reject_all(typefilter_t tf)
 {
-       assert(tf);
+       assert(tf != NULL);
        memset(tf, 0, KDBG_TYPEFILTER_BITMAP_SIZE);
 }
 
-static void typefilter_allow_class(typefilter_t tf, uint8_t class)
+static void
+typefilter_allow_all(typefilter_t tf)
+{
+       assert(tf != NULL);
+       memset(tf, ~0, KDBG_TYPEFILTER_BITMAP_SIZE);
+}
+
+static void
+typefilter_allow_class(typefilter_t tf, uint8_t class)
 {
-       assert(tf);
+       assert(tf != NULL);
        const uint32_t BYTES_PER_CLASS = 256 / 8; // 256 subclasses, 1 bit each
        memset(&tf[class * BYTES_PER_CLASS], 0xFF, BYTES_PER_CLASS);
 }
 
-static void typefilter_allow_csc(typefilter_t tf, uint16_t csc)
+static void
+typefilter_allow_csc(typefilter_t tf, uint16_t csc)
 {
-       assert(tf);
+       assert(tf != NULL);
        setbit(tf, csc);
 }
 
-static boolean_t typefilter_is_debugid_allowed(typefilter_t tf, uint32_t id)
+static bool
+typefilter_is_debugid_allowed(typefilter_t tf, uint32_t id)
 {
-       assert(tf);
+       assert(tf != NULL);
        return isset(tf, KDBG_EXTRACT_CSC(id));
 }
 
-static mach_port_t typefilter_create_memory_entry(typefilter_t tf)
+static mach_port_t
+typefilter_create_memory_entry(typefilter_t tf)
 {
-       assert(tf);
+       assert(tf != NULL);
 
        mach_port_t memory_entry = MACH_PORT_NULL;
        memory_object_size_t size = TYPEFILTER_ALLOC_SIZE;
 
        mach_make_memory_entry_64(kernel_map,
-                                 &size,
-                                 (memory_object_offset_t)tf,
-                                 VM_PROT_READ,
-                                 &memory_entry,
-                                 MACH_PORT_NULL);
+           &size,
+           (memory_object_offset_t)tf,
+           VM_PROT_READ,
+           &memory_entry,
+           MACH_PORT_NULL);
 
        return memory_entry;
 }
@@ -227,18 +240,35 @@ static void kdbg_disable_typefilter(void);
  * External prototypes
  */
 
-void task_act_iterate_wth_args(task_t, void(*)(thread_t, void *), void *);
-int cpu_number(void);  /* XXX <machine/...> include path broken */
+void task_act_iterate_wth_args(task_t, void (*)(thread_t, void *), void *);
+int cpu_number(void);   /* XXX <machine/...> include path broken */
 void commpage_update_kdebug_state(void); /* XXX sign */
 
 extern int log_leaks;
-extern boolean_t kdebug_serial;
+
+/*
+ * This flag is for testing purposes only -- it's highly experimental and tools
+ * have not been updated to support it.
+ */
+static bool kdbg_continuous_time = false;
+
+static inline uint64_t
+kdbg_timestamp(void)
+{
+       if (kdbg_continuous_time) {
+               return mach_continuous_time();
+       } else {
+               return mach_absolute_time();
+       }
+}
+
+static int kdbg_debug = 0;
 
 #if KDEBUG_MOJO_TRACE
 #include <sys/kdebugevents.h>
 static void kdebug_serial_print( /* forward */
-               uint32_t, uint32_t, uint64_t,
-               uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t);
+       uint32_t, uint32_t, uint64_t,
+       uintptr_t, uintptr_t, uintptr_t, uintptr_t, uintptr_t);
 #endif
 
 int kdbg_control(int *, u_int, user_addr_t, size_t *);
@@ -251,62 +281,73 @@ static int kdbg_setreg(kd_regtype *);
 static int kdbg_setpidex(kd_regtype *);
 static int kdbg_setpid(kd_regtype *);
 static void kdbg_thrmap_init(void);
-static int kdbg_reinit(boolean_t);
-static int kdbg_bootstrap(boolean_t);
-static int kdbg_test(void);
+static int kdbg_reinit(bool);
+static int kdbg_bootstrap(bool);
+static int kdbg_test(size_t flavor);
 
-static int kdbg_write_v1_header(boolean_t write_thread_map, vnode_t vp, vfs_context_t ctx);
+static int kdbg_write_v1_header(bool write_thread_map, vnode_t vp, vfs_context_t ctx);
 static int kdbg_write_thread_map(vnode_t vp, vfs_context_t ctx);
 static int kdbg_copyout_thread_map(user_addr_t buffer, size_t *buffer_size);
 static void kdbg_clear_thread_map(void);
 
-static boolean_t kdbg_wait(uint64_t timeout_ms, boolean_t locked_wait);
+static bool kdbg_wait(uint64_t timeout_ms, bool locked_wait);
 static void kdbg_wakeup(void);
 
 int kdbg_cpumap_init_internal(kd_iop_t* iops, uint32_t cpu_count,
-                              uint8_t** cpumap, uint32_t* cpumap_size);
+    uint8_t** cpumap, uint32_t* cpumap_size);
 
 static kd_threadmap *kdbg_thrmap_init_internal(unsigned int count,
-                                               unsigned int *mapsize,
-                                               unsigned int *mapcount);
+    unsigned int *mapsize,
+    unsigned int *mapcount);
 
-static boolean_t kdebug_current_proc_enabled(uint32_t debugid);
-boolean_t kdebug_debugid_enabled(uint32_t debugid);
+static bool kdebug_current_proc_enabled(uint32_t debugid);
 static errno_t kdebug_check_trace_string(uint32_t debugid, uint64_t str_id);
 
 int kdbg_write_v3_header(user_addr_t, size_t *, int);
 int kdbg_write_v3_chunk_header(user_addr_t buffer, uint32_t tag,
-                               uint32_t sub_tag, uint64_t length,
-                               vnode_t vp, vfs_context_t ctx);
+    uint32_t sub_tag, uint64_t length,
+    vnode_t vp, vfs_context_t ctx);
 
 user_addr_t kdbg_write_v3_event_chunk_header(user_addr_t buffer, uint32_t tag,
-                                             uint64_t length, vnode_t vp,
-                                             vfs_context_t ctx);
+    uint64_t length, vnode_t vp,
+    vfs_context_t ctx);
 
 // Helper functions
 
-static int create_buffers(boolean_t);
+static int create_buffers(bool);
 static void delete_buffers(void);
 
 extern int tasks_count;
 extern int threads_count;
-extern char *proc_best_name(proc_t p);
 extern void IOSleep(int);
 
 /* trace enable status */
 unsigned int kdebug_enable = 0;
 
 /* A static buffer to record events prior to the start of regular logging */
-#define        KD_EARLY_BUFFER_MAX      64
-static kd_buf          kd_early_buffer[KD_EARLY_BUFFER_MAX];
-static int             kd_early_index = 0;
-static boolean_t       kd_early_overflow = FALSE;
+
+#define KD_EARLY_BUFFER_SIZE (16 * 1024)
+#define KD_EARLY_BUFFER_NBUFS (KD_EARLY_BUFFER_SIZE / sizeof(kd_buf))
+#if CONFIG_EMBEDDED
+/*
+ * On embedded, the space for this is carved out by osfmk/arm/data.s -- clang
+ * has problems aligning to greater than 4K.
+ */
+extern kd_buf kd_early_buffer[KD_EARLY_BUFFER_NBUFS];
+#else /* CONFIG_EMBEDDED */
+__attribute__((aligned(KD_EARLY_BUFFER_SIZE)))
+static kd_buf kd_early_buffer[KD_EARLY_BUFFER_NBUFS];
+#endif /* !CONFIG_EMBEDDED */
+
+static unsigned int kd_early_index = 0;
+static bool kd_early_overflow = false;
+static bool kd_early_done = false;
 
 #define SLOW_NOLOG  0x01
 #define SLOW_CHECKS 0x02
 
-#define EVENTS_PER_STORAGE_UNIT                2048
-#define MIN_STORAGE_UNITS_PER_CPU      4
+#define EVENTS_PER_STORAGE_UNIT         2048
+#define MIN_STORAGE_UNITS_PER_CPU       4
 
 #define POINTER_FROM_KDS_PTR(x) (&kd_bufs[x.buffer_index].kdsb_addr[x.offset])
 
@@ -319,40 +360,42 @@ union kds_ptr {
 };
 
 struct kd_storage {
-       union   kds_ptr kds_next;
+       union   kds_ptr kds_next;
        uint32_t kds_bufindx;
        uint32_t kds_bufcnt;
        uint32_t kds_readlast;
-       boolean_t kds_lostevents;
+       bool kds_lostevents;
        uint64_t  kds_timestamp;
 
-       kd_buf  kds_records[EVENTS_PER_STORAGE_UNIT];
+       kd_buf  kds_records[EVENTS_PER_STORAGE_UNIT];
 };
 
-#define MAX_BUFFER_SIZE                        (1024 * 1024 * 128)
-#define N_STORAGE_UNITS_PER_BUFFER     (MAX_BUFFER_SIZE / sizeof(struct kd_storage))
+#define MAX_BUFFER_SIZE            (1024 * 1024 * 128)
+#define N_STORAGE_UNITS_PER_BUFFER (MAX_BUFFER_SIZE / sizeof(struct kd_storage))
+static_assert(N_STORAGE_UNITS_PER_BUFFER <= 0x7ff,
+    "shoudn't overflow kds_ptr.offset");
 
 struct kd_storage_buffers {
-       struct  kd_storage      *kdsb_addr;
-       uint32_t                kdsb_size;
+       struct  kd_storage      *kdsb_addr;
+       uint32_t                kdsb_size;
 };
 
 #define KDS_PTR_NULL 0xffffffff
 struct kd_storage_buffers *kd_bufs = NULL;
-int    n_storage_units = 0;
-int    n_storage_buffers = 0;
-int    n_storage_threshold = 0;
-int    kds_waiter = 0;
+int n_storage_units = 0;
+unsigned int n_storage_buffers = 0;
+int n_storage_threshold = 0;
+int kds_waiter = 0;
 
 #pragma pack(0)
 struct kd_bufinfo {
        union  kds_ptr kd_list_head;
        union  kds_ptr kd_list_tail;
-       boolean_t kd_lostevents;
+       bool kd_lostevents;
        uint32_t _pad;
        uint64_t kd_prev_timebase;
        uint32_t num_bufs;
-} __attribute__(( aligned(MAX_CPU_CACHE_LINE_SIZE) ));
+} __attribute__((aligned(MAX_CPU_CACHE_LINE_SIZE)));
 
 
 /*
@@ -361,9 +404,9 @@ struct kd_bufinfo {
  */
 struct kd_ctrl_page_t {
        union kds_ptr kds_free_list;
-       uint32_t enabled        :1;
-       uint32_t _pad0          :31;
-       int                     kds_inuse_count;
+       uint32_t enabled        :1;
+       uint32_t _pad0          :31;
+       int                     kds_inuse_count;
        uint32_t kdebug_flags;
        uint32_t kdebug_slowcheck;
        uint64_t oldest_time;
@@ -386,21 +429,21 @@ struct kd_ctrl_page_t {
 
 struct kd_bufinfo *kdbip = NULL;
 
-#define KDCOPYBUF_COUNT        8192
-#define KDCOPYBUF_SIZE (KDCOPYBUF_COUNT * sizeof(kd_buf))
+#define KDCOPYBUF_COUNT 8192
+#define KDCOPYBUF_SIZE  (KDCOPYBUF_COUNT * sizeof(kd_buf))
 
-#define PAGE_4KB       4096
-#define PAGE_16KB      16384
+#define PAGE_4KB        4096
+#define PAGE_16KB       16384
 
 kd_buf *kdcopybuf = NULL;
 
 unsigned int nkdbufs = 0;
-unsigned int kdlog_beg=0;
-unsigned int kdlog_end=0;
-unsigned int kdlog_value1=0;
-unsigned int kdlog_value2=0;
-unsigned int kdlog_value3=0;
-unsigned int kdlog_value4=0;
+unsigned int kdlog_beg = 0;
+unsigned int kdlog_end = 0;
+unsigned int kdlog_value1 = 0;
+unsigned int kdlog_value2 = 0;
+unsigned int kdlog_value3 = 0;
+unsigned int kdlog_value4 = 0;
 
 static lck_spin_t * kdw_spin_lock;
 static lck_spin_t * kds_spin_lock;
@@ -409,10 +452,10 @@ kd_threadmap *kd_mapptr = 0;
 unsigned int kd_mapsize = 0;
 unsigned int kd_mapcount = 0;
 
-off_t  RAW_file_offset = 0;
-int    RAW_file_written = 0;
+off_t   RAW_file_offset = 0;
+int     RAW_file_written = 0;
 
-#define        RAW_FLUSH_SIZE  (2 * 1024 * 1024)
+#define RAW_FLUSH_SIZE  (2 * 1024 * 1024)
 
 /*
  * A globally increasing counter for identifying strings in trace.  Starts at
@@ -431,36 +474,157 @@ static uint64_t g_curr_str_id = 1;
  */
 static uint64_t g_str_id_signature = (0x70acULL << STR_ID_SIG_OFFSET);
 
-#define INTERRUPT      0x01050000
-#define MACH_vmfault   0x01300008
-#define BSC_SysCall    0x040c0000
-#define MACH_SysCall   0x010c0000
+#define INTERRUPT       0x01050000
+#define MACH_vmfault    0x01300008
+#define BSC_SysCall     0x040c0000
+#define MACH_SysCall    0x010c0000
 
 /* task to string structure */
-struct tts
-{
-  task_t    task;            /* from procs task */
-  pid_t     pid;             /* from procs p_pid  */
-  char      task_comm[20];   /* from procs p_comm */
+struct tts {
+       task_t    task;      /* from procs task */
+       pid_t     pid;       /* from procs p_pid  */
+       char      task_comm[20];/* from procs p_comm */
 };
 
 typedef struct tts tts_t;
 
-struct krt
-{
+struct krt {
        kd_threadmap *map;    /* pointer to the map buffer */
        int count;
        int maxcount;
        struct tts *atts;
 };
 
+/*
+ * TRACE file formats...
+ *
+ * RAW_VERSION0
+ *
+ * uint32_t #threadmaps
+ * kd_threadmap[]
+ * kd_buf[]
+ *
+ * RAW_VERSION1
+ *
+ * RAW_header, with version_no set to RAW_VERSION1
+ * kd_threadmap[]
+ * Empty space to pad alignment to the nearest page boundary.
+ * kd_buf[]
+ *
+ * RAW_VERSION1+
+ *
+ * RAW_header, with version_no set to RAW_VERSION1
+ * kd_threadmap[]
+ * kd_cpumap_header, with version_no set to RAW_VERSION1
+ * kd_cpumap[]
+ * Empty space to pad alignment to the nearest page boundary.
+ * kd_buf[]
+ *
+ * V1+ implementation details...
+ *
+ * It would have been nice to add the cpumap data "correctly", but there were
+ * several obstacles. Existing code attempts to parse both V1 and V0 files.
+ * Due to the fact that V0 has no versioning or header, the test looks like
+ * this:
+ *
+ * // Read header
+ * if (header.version_no != RAW_VERSION1) { // Assume V0 }
+ *
+ * If we add a VERSION2 file format, all existing code is going to treat that
+ * as a VERSION0 file when reading it, and crash terribly when trying to read
+ * RAW_VERSION2 threadmap entries.
+ *
+ * To differentiate between a V1 and V1+ file, read as V1 until you reach
+ * the padding bytes. Then:
+ *
+ * boolean_t is_v1plus = FALSE;
+ * if (padding_bytes >= sizeof(kd_cpumap_header)) {
+ *     kd_cpumap_header header = // read header;
+ *     if (header.version_no == RAW_VERSION1) {
+ *         is_v1plus = TRUE;
+ *     }
+ * }
+ *
+ */
+
+#define RAW_VERSION3    0x00001000
+
+// Version 3 header
+// The header chunk has the tag 0x00001000 which also serves as a magic word
+// that identifies the file as a version 3 trace file. The header payload is
+// a set of fixed fields followed by a variable number of sub-chunks:
+/*
+ *  ____________________________________________________________________________
+ | Offset | Size | Field                                                    |
+ |  ----------------------------------------------------------------------------
+ |    0   |  4   | Tag (0x00001000)                                         |
+ |    4   |  4   | Sub-tag. Represents the version of the header.           |
+ |    8   |  8   | Length of header payload (40+8x)                         |
+ |   16   |  8   | Time base info. Two 32-bit numbers, numer/denom,         |
+ |        |      | for converting timestamps to nanoseconds.                |
+ |   24   |  8   | Timestamp of trace start.                                |
+ |   32   |  8   | Wall time seconds since Unix epoch.                      |
+ |        |      | As returned by gettimeofday().                           |
+ |   40   |  4   | Wall time microseconds. As returned by gettimeofday().   |
+ |   44   |  4   | Local time zone offset in minutes. ( " )                 |
+ |   48   |  4   | Type of daylight savings time correction to apply. ( " ) |
+ |   52   |  4   | Flags. 1 = 64-bit. Remaining bits should be written      |
+ |        |      | as 0 and ignored when reading.                           |
+ |   56   |  8x  | Variable number of sub-chunks. None are required.        |
+ |        |      | Ignore unknown chunks.                                   |
+ |  ----------------------------------------------------------------------------
+ */
+// NOTE: The header sub-chunks are considered part of the header chunk,
+// so they must be included in the header chunk’s length field.
+// The CPU map is an optional sub-chunk of the header chunk. It provides
+// information about the CPUs that are referenced from the trace events.
+typedef struct {
+       uint32_t tag;
+       uint32_t sub_tag;
+       uint64_t length;
+       uint32_t timebase_numer;
+       uint32_t timebase_denom;
+       uint64_t timestamp;
+       uint64_t walltime_secs;
+       uint32_t walltime_usecs;
+       uint32_t timezone_minuteswest;
+       uint32_t timezone_dst;
+       uint32_t flags;
+} __attribute__((packed)) kd_header_v3;
+
+typedef struct {
+       uint32_t tag;
+       uint32_t sub_tag;
+       uint64_t length;
+} __attribute__((packed)) kd_chunk_header_v3;
+
+#define V3_CONFIG       0x00001b00
+#define V3_CPU_MAP      0x00001c00
+#define V3_THREAD_MAP   0x00001d00
+#define V3_RAW_EVENTS   0x00001e00
+#define V3_NULL_CHUNK   0x00002000
+
+// The current version of all kernel managed chunks is 1. The
+// V3_CURRENT_CHUNK_VERSION is added to ease the simple case
+// when most/all the kernel managed chunks have the same version.
+
+#define V3_CURRENT_CHUNK_VERSION 1
+#define V3_HEADER_VERSION     V3_CURRENT_CHUNK_VERSION
+#define V3_CPUMAP_VERSION     V3_CURRENT_CHUNK_VERSION
+#define V3_THRMAP_VERSION     V3_CURRENT_CHUNK_VERSION
+#define V3_EVENT_DATA_VERSION V3_CURRENT_CHUNK_VERSION
+
 typedef struct krt krt_t;
 
 static uint32_t
-kdbg_cpu_count(boolean_t early_trace)
+kdbg_cpu_count(bool early_trace)
 {
        if (early_trace) {
+#if CONFIG_EMBEDDED
+               return ml_get_cpu_count();
+#else
                return max_ncpus;
+#endif
        }
 
        host_basic_info_data_t hinfo;
@@ -471,6 +635,42 @@ kdbg_cpu_count(boolean_t early_trace)
 }
 
 #if MACH_ASSERT
+#if CONFIG_EMBEDDED
+static bool
+kdbg_iop_list_is_valid(kd_iop_t* iop)
+{
+       if (iop) {
+               /* Is list sorted by cpu_id? */
+               kd_iop_t* temp = iop;
+               do {
+                       assert(!temp->next || temp->next->cpu_id == temp->cpu_id - 1);
+                       assert(temp->next || (temp->cpu_id == kdbg_cpu_count(false) || temp->cpu_id == kdbg_cpu_count(true)));
+               } while ((temp = temp->next));
+
+               /* Does each entry have a function and a name? */
+               temp = iop;
+               do {
+                       assert(temp->callback.func);
+                       assert(strlen(temp->callback.iop_name) < sizeof(temp->callback.iop_name));
+               } while ((temp = temp->next));
+       }
+
+       return true;
+}
+
+static bool
+kdbg_iop_list_contains_cpu_id(kd_iop_t* list, uint32_t cpu_id)
+{
+       while (list) {
+               if (list->cpu_id == cpu_id) {
+                       return true;
+               }
+               list = list->next;
+       }
+
+       return false;
+}
+#endif /* CONFIG_EMBEDDED */
 #endif /* MACH_ASSERT */
 
 static void
@@ -482,18 +682,33 @@ kdbg_iop_list_callback(kd_iop_t* iop, kd_callback_type type, void* arg)
        }
 }
 
+static lck_grp_t *kdebug_lck_grp = NULL;
+
 static void
-kdbg_set_tracing_enabled(boolean_t enabled, uint32_t trace_type)
+kdbg_set_tracing_enabled(bool enabled, uint32_t trace_type)
 {
-       int s = ml_set_interrupts_enabled(FALSE);
-       lck_spin_lock(kds_spin_lock);
+       /*
+        * Drain any events from IOPs before making the state change.  On
+        * enabling, this removes any stale events from before tracing.  On
+        * disabling, this saves any events up to the point tracing is disabled.
+        */
+       kdbg_iop_list_callback(kd_ctrl_page.kdebug_iops, KD_CALLBACK_SYNC_FLUSH,
+           NULL);
+
+       int s = ml_set_interrupts_enabled(false);
+       lck_spin_lock_grp(kds_spin_lock, kdebug_lck_grp);
+
        if (enabled) {
+               /*
+                * The oldest valid time is now; reject past events from IOPs.
+                */
+               kd_ctrl_page.oldest_time = kdbg_timestamp();
                kdebug_enable |= trace_type;
                kd_ctrl_page.kdebug_slowcheck &= ~SLOW_NOLOG;
                kd_ctrl_page.enabled = 1;
                commpage_update_kdebug_state();
        } else {
-               kdebug_enable &= ~(KDEBUG_ENABLE_TRACE|KDEBUG_ENABLE_PPT);
+               kdebug_enable &= ~(KDEBUG_ENABLE_TRACE | KDEBUG_ENABLE_PPT);
                kd_ctrl_page.kdebug_slowcheck |= SLOW_NOLOG;
                kd_ctrl_page.enabled = 0;
                commpage_update_kdebug_state();
@@ -502,23 +717,19 @@ kdbg_set_tracing_enabled(boolean_t enabled, uint32_t trace_type)
        ml_set_interrupts_enabled(s);
 
        if (enabled) {
-               kdbg_iop_list_callback(kd_ctrl_page.kdebug_iops, KD_CALLBACK_KDEBUG_ENABLED, NULL);
+               kdbg_iop_list_callback(kd_ctrl_page.kdebug_iops,
+                   KD_CALLBACK_KDEBUG_ENABLED, NULL);
        } else {
-               /*
-                * If you do not flush the IOP trace buffers, they can linger
-                * for a considerable period; consider code which disables and
-                * deallocates without a final sync flush.
-                */
-               kdbg_iop_list_callback(kd_ctrl_page.kdebug_iops, KD_CALLBACK_KDEBUG_DISABLED, NULL);
-               kdbg_iop_list_callback(kd_ctrl_page.kdebug_iops, KD_CALLBACK_SYNC_FLUSH, NULL);
+               kdbg_iop_list_callback(kd_ctrl_page.kdebug_iops,
+                   KD_CALLBACK_KDEBUG_DISABLED, NULL);
        }
 }
 
 static void
-kdbg_set_flags(int slowflag, int enableflag, boolean_t enabled)
+kdbg_set_flags(int slowflag, int enableflag, bool enabled)
 {
-       int s = ml_set_interrupts_enabled(FALSE);
-       lck_spin_lock(kds_spin_lock);
+       int s = ml_set_interrupts_enabled(false);
+       lck_spin_lock_grp(kds_spin_lock, kdebug_lck_grp);
 
        if (enabled) {
                kd_ctrl_page.kdebug_slowcheck |= slowflag;
@@ -527,7 +738,7 @@ kdbg_set_flags(int slowflag, int enableflag, boolean_t enabled)
                kd_ctrl_page.kdebug_slowcheck &= ~slowflag;
                kdebug_enable &= ~enableflag;
        }
-        
+
        lck_spin_unlock(kds_spin_lock);
        ml_set_interrupts_enabled(s);
 }
@@ -535,12 +746,12 @@ kdbg_set_flags(int slowflag, int enableflag, boolean_t enabled)
 /*
  * Disable wrapping and return true if trace wrapped, false otherwise.
  */
-boolean_t
+static bool
 disable_wrap(uint32_t *old_slowcheck, uint32_t *old_flags)
 {
-       boolean_t wrapped;
-       int s = ml_set_interrupts_enabled(FALSE);
-       lck_spin_lock(kds_spin_lock);
+       bool wrapped;
+       int s = ml_set_interrupts_enabled(false);
+       lck_spin_lock_grp(kds_spin_lock, kdebug_lck_grp);
 
        *old_slowcheck = kd_ctrl_page.kdebug_slowcheck;
        *old_flags = kd_ctrl_page.kdebug_flags;
@@ -555,31 +766,29 @@ disable_wrap(uint32_t *old_slowcheck, uint32_t *old_flags)
        return wrapped;
 }
 
-void
-enable_wrap(uint32_t old_slowcheck, boolean_t lostevents)
+static void
+enable_wrap(uint32_t old_slowcheck)
 {
-       int s = ml_set_interrupts_enabled(FALSE);
-       lck_spin_lock(kds_spin_lock);
+       int s = ml_set_interrupts_enabled(false);
+       lck_spin_lock_grp(kds_spin_lock, kdebug_lck_grp);
 
        kd_ctrl_page.kdebug_flags &= ~KDBG_NOWRAP;
 
-       if ( !(old_slowcheck & SLOW_NOLOG))
+       if (!(old_slowcheck & SLOW_NOLOG)) {
                kd_ctrl_page.kdebug_slowcheck &= ~SLOW_NOLOG;
-
-       if (lostevents == TRUE)
-               kd_ctrl_page.kdebug_flags |= KDBG_WRAPPED;
+       }
 
        lck_spin_unlock(kds_spin_lock);
        ml_set_interrupts_enabled(s);
 }
 
 static int
-create_buffers(boolean_t early_trace)
+create_buffers(bool early_trace)
 {
-       int i;
-       int p_buffer_size;
-       int f_buffer_size;
-       int f_buffers;
+       unsigned int i;
+       unsigned int p_buffer_size;
+       unsigned int f_buffer_size;
+       unsigned int f_buffers;
        int error = 0;
 
        /*
@@ -591,6 +800,9 @@ create_buffers(boolean_t early_trace)
         */
        kd_ctrl_page.kdebug_iops = kd_iops;
 
+#if CONFIG_EMBEDDED
+       assert(kdbg_iop_list_is_valid(kd_ctrl_page.kdebug_iops));
+#endif
 
        /*
         * If the list is valid, it is sorted, newest -> oldest. Each iop entry
@@ -605,10 +817,11 @@ create_buffers(boolean_t early_trace)
                goto out;
        }
 
-       if (nkdbufs < (kd_ctrl_page.kdebug_cpus * EVENTS_PER_STORAGE_UNIT * MIN_STORAGE_UNITS_PER_CPU))
+       if (nkdbufs < (kd_ctrl_page.kdebug_cpus * EVENTS_PER_STORAGE_UNIT * MIN_STORAGE_UNITS_PER_CPU)) {
                n_storage_units = kd_ctrl_page.kdebug_cpus * MIN_STORAGE_UNITS_PER_CPU;
-       else
+       } else {
                n_storage_units = nkdbufs / EVENTS_PER_STORAGE_UNIT;
+       }
 
        nkdbufs = n_storage_units * EVENTS_PER_STORAGE_UNIT;
 
@@ -618,13 +831,14 @@ create_buffers(boolean_t early_trace)
        f_buffer_size = N_STORAGE_UNITS_PER_BUFFER * sizeof(struct kd_storage);
        p_buffer_size = (n_storage_units % N_STORAGE_UNITS_PER_BUFFER) * sizeof(struct kd_storage);
 
-       if (p_buffer_size)
+       if (p_buffer_size) {
                n_storage_buffers++;
+       }
 
        kd_bufs = NULL;
 
        if (kdcopybuf == 0) {
-               if (kmem_alloc(kernel_map, (vm_offset_t *)&kdcopybuf, (vm_size_t)KDCOPYBUF_SIZE, VM_KERN_MEMORY_DIAG) != KERN_SUCCESS) {
+               if (kmem_alloc(kernel_map, (vm_offset_t *)&kdcopybuf, (vm_size_t)KDCOPYBUF_SIZE, VM_KERN_MEMORY_DIAG) != KERN_SUCCESS) {
                        error = ENOSPC;
                        goto out;
                }
@@ -657,8 +871,8 @@ create_buffers(boolean_t early_trace)
 
        for (i = 0; i < n_storage_buffers; i++) {
                struct kd_storage *kds;
-               int     n_elements;
-               int     n;
+               int     n_elements;
+               int     n;
 
                n_elements = kd_bufs[i].kdsb_size / sizeof(struct kd_storage);
                kds = kd_bufs[i].kdsb_addr;
@@ -675,29 +889,30 @@ create_buffers(boolean_t early_trace)
 
        bzero((char *)kdbip, sizeof(struct kd_bufinfo) * kd_ctrl_page.kdebug_cpus);
 
-       for (i = 0; i < (int)kd_ctrl_page.kdebug_cpus; i++) {
+       for (i = 0; i < kd_ctrl_page.kdebug_cpus; i++) {
                kdbip[i].kd_list_head.raw = KDS_PTR_NULL;
                kdbip[i].kd_list_tail.raw = KDS_PTR_NULL;
-               kdbip[i].kd_lostevents = FALSE;
+               kdbip[i].kd_lostevents = false;
                kdbip[i].num_bufs = 0;
        }
-        
+
        kd_ctrl_page.kdebug_flags |= KDBG_BUFINIT;
 
        kd_ctrl_page.kds_inuse_count = 0;
        n_storage_threshold = n_storage_units / 2;
 out:
-       if (error)
+       if (error) {
                delete_buffers();
+       }
 
-       return(error);
+       return error;
 }
 
 static void
 delete_buffers(void)
 {
-       int i;
-       
+       unsigned int i;
+
        if (kd_bufs) {
                for (i = 0; i < n_storage_buffers; i++) {
                        if (kd_bufs[i].kdsb_addr) {
@@ -718,10 +933,10 @@ delete_buffers(void)
 
        if (kdbip) {
                kmem_free(kernel_map, (vm_offset_t)kdbip, sizeof(struct kd_bufinfo) * kd_ctrl_page.kdebug_cpus);
-               
+
                kdbip = NULL;
        }
-        kd_ctrl_page.kdebug_iops = NULL;
+       kd_ctrl_page.kdebug_iops = NULL;
        kd_ctrl_page.kdebug_cpus = 0;
        kd_ctrl_page.kdebug_flags &= ~KDBG_BUFINIT;
 }
@@ -730,14 +945,14 @@ void
 release_storage_unit(int cpu, uint32_t kdsp_raw)
 {
        int s = 0;
-       struct  kd_storage *kdsp_actual;
+       struct  kd_storage *kdsp_actual;
        struct kd_bufinfo *kdbp;
        union kds_ptr kdsp;
 
        kdsp.raw = kdsp_raw;
 
-       s = ml_set_interrupts_enabled(FALSE);
-       lck_spin_lock(kds_spin_lock);
+       s = ml_set_interrupts_enabled(false);
+       lck_spin_lock_grp(kds_spin_lock, kdebug_lck_grp);
 
        kdbp = &kdbip[cpu];
 
@@ -746,7 +961,7 @@ release_storage_unit(int cpu, uint32_t kdsp_raw)
                 * it's possible for the storage unit pointed to
                 * by kdsp to have already been stolen... so
                 * check to see if it's still the head of the list
-                * now that we're behind the lock that protects 
+                * now that we're behind the lock that protects
                 * adding and removing from the queue...
                 * since we only ever release and steal units from
                 * that position, if it's no longer the head
@@ -764,19 +979,18 @@ release_storage_unit(int cpu, uint32_t kdsp_raw)
        ml_set_interrupts_enabled(s);
 }
 
-
-boolean_t
+bool
 allocate_storage_unit(int cpu)
 {
        union kds_ptr kdsp;
        struct kd_storage *kdsp_actual, *kdsp_next_actual;
        struct kd_bufinfo *kdbp, *kdbp_vict, *kdbp_try;
        uint64_t oldest_ts, ts;
-       boolean_t retval = TRUE;
+       bool retval = true;
        int s = 0;
 
-       s = ml_set_interrupts_enabled(FALSE);
-       lck_spin_lock(kds_spin_lock);
+       s = ml_set_interrupts_enabled(false);
+       lck_spin_lock_grp(kds_spin_lock, kdebug_lck_grp);
 
        kdbp = &kdbip[cpu];
 
@@ -784,27 +998,34 @@ allocate_storage_unit(int cpu)
        if (kdbp->kd_list_tail.raw != KDS_PTR_NULL) {
                kdsp_actual = POINTER_FROM_KDS_PTR(kdbp->kd_list_tail);
 
-               if (kdsp_actual->kds_bufindx < EVENTS_PER_STORAGE_UNIT)
+               if (kdsp_actual->kds_bufindx < EVENTS_PER_STORAGE_UNIT) {
                        goto out;
+               }
        }
-       
+
        if ((kdsp = kd_ctrl_page.kds_free_list).raw != KDS_PTR_NULL) {
+               /*
+                * If there's a free page, grab it from the free list.
+                */
                kdsp_actual = POINTER_FROM_KDS_PTR(kdsp);
                kd_ctrl_page.kds_free_list = kdsp_actual->kds_next;
 
                kd_ctrl_page.kds_inuse_count++;
        } else {
+               /*
+                * Otherwise, we're going to lose events and repurpose the oldest
+                * storage unit we can find.
+                */
                if (kd_ctrl_page.kdebug_flags & KDBG_NOWRAP) {
                        kd_ctrl_page.kdebug_slowcheck |= SLOW_NOLOG;
-                       kdbp->kd_lostevents = TRUE;
-                       retval = FALSE;
+                       kdbp->kd_lostevents = true;
+                       retval = false;
                        goto out;
                }
                kdbp_vict = NULL;
                oldest_ts = UINT64_MAX;
 
                for (kdbp_try = &kdbip[0]; kdbp_try < &kdbip[kd_ctrl_page.kdebug_cpus]; kdbp_try++) {
-
                        if (kdbp_try->kd_list_head.raw == KDS_PTR_NULL) {
                                /*
                                 * no storage unit to steal
@@ -842,7 +1063,7 @@ allocate_storage_unit(int cpu)
                        kdebug_enable = 0;
                        kd_ctrl_page.enabled = 0;
                        commpage_update_kdebug_state();
-                       retval = FALSE;
+                       retval = false;
                        goto out;
                }
                kdsp = kdbp_vict->kd_list_head;
@@ -851,32 +1072,36 @@ allocate_storage_unit(int cpu)
 
                if (kdbp_vict->kd_list_head.raw != KDS_PTR_NULL) {
                        kdsp_next_actual = POINTER_FROM_KDS_PTR(kdbp_vict->kd_list_head);
-                       kdsp_next_actual->kds_lostevents = TRUE;
-               } else
-                       kdbp_vict->kd_lostevents = TRUE;
+                       kdsp_next_actual->kds_lostevents = true;
+               } else {
+                       kdbp_vict->kd_lostevents = true;
+               }
 
-               kd_ctrl_page.oldest_time = oldest_ts;
+               if (kd_ctrl_page.oldest_time < oldest_ts) {
+                       kd_ctrl_page.oldest_time = oldest_ts;
+               }
                kd_ctrl_page.kdebug_flags |= KDBG_WRAPPED;
        }
-       kdsp_actual->kds_timestamp = mach_absolute_time();
+       kdsp_actual->kds_timestamp = kdbg_timestamp();
        kdsp_actual->kds_next.raw = KDS_PTR_NULL;
-       kdsp_actual->kds_bufcnt   = 0;
+       kdsp_actual->kds_bufcnt   = 0;
        kdsp_actual->kds_readlast = 0;
 
        kdsp_actual->kds_lostevents = kdbp->kd_lostevents;
-       kdbp->kd_lostevents = FALSE;
-       kdsp_actual->kds_bufindx  = 0;
+       kdbp->kd_lostevents = false;
+       kdsp_actual->kds_bufindx = 0;
 
-       if (kdbp->kd_list_head.raw == KDS_PTR_NULL)
+       if (kdbp->kd_list_head.raw == KDS_PTR_NULL) {
                kdbp->kd_list_head = kdsp;
-       else
+       } else {
                POINTER_FROM_KDS_PTR(kdbp->kd_list_tail)->kds_next = kdsp;
+       }
        kdbp->kd_list_tail = kdsp;
 out:
        lck_spin_unlock(kds_spin_lock);
        ml_set_interrupts_enabled(s);
 
-       return (retval);
+       return retval;
 }
 
 int
@@ -885,32 +1110,34 @@ kernel_debug_register_callback(kd_callback_t callback)
        kd_iop_t* iop;
        if (kmem_alloc(kernel_map, (vm_offset_t *)&iop, sizeof(kd_iop_t), VM_KERN_MEMORY_DIAG) == KERN_SUCCESS) {
                memcpy(&iop->callback, &callback, sizeof(kd_callback_t));
-               
+
                /*
                 * <rdar://problem/13351477> Some IOP clients are not providing a name.
                 *
                 * Remove when fixed.
                 */
                {
-                       boolean_t is_valid_name = FALSE;
-                       for (uint32_t length=0; length<sizeof(callback.iop_name); ++length) {
+                       bool is_valid_name = false;
+                       for (uint32_t length = 0; length < sizeof(callback.iop_name); ++length) {
                                /* This is roughly isprintable(c) */
-                               if (callback.iop_name[length] > 0x20 && callback.iop_name[length] < 0x7F)
+                               if (callback.iop_name[length] > 0x20 && callback.iop_name[length] < 0x7F) {
                                        continue;
+                               }
                                if (callback.iop_name[length] == 0) {
-                                       if (length)
-                                               is_valid_name = TRUE;
+                                       if (length) {
+                                               is_valid_name = true;
+                                       }
                                        break;
                                }
                        }
-                       
+
                        if (!is_valid_name) {
                                strlcpy(iop->callback.iop_name, "IOP-???", sizeof(iop->callback.iop_name));
                        }
                }
 
                iop->last_timestamp = 0;
-               
+
                do {
                        /*
                         * We use two pieces of state, the old list head
@@ -921,7 +1148,7 @@ kernel_debug_register_callback(kd_callback_t callback)
                         * TLDR; Must not read kd_iops more than once per loop.
                         */
                        iop->next = kd_iops;
-                       iop->cpu_id = iop->next ? (iop->next->cpu_id+1) : kdbg_cpu_count(FALSE);
+                       iop->cpu_id = iop->next ? (iop->next->cpu_id + 1) : kdbg_cpu_count(false);
 
                        /*
                         * Header says OSCompareAndSwapPtr has a memory barrier
@@ -936,66 +1163,79 @@ kernel_debug_register_callback(kd_callback_t callback)
 
 void
 kernel_debug_enter(
-       uint32_t        coreid,
-       uint32_t        debugid,
-       uint64_t        timestamp,
-       uintptr_t       arg1,
-       uintptr_t       arg2,
-       uintptr_t       arg3,
-       uintptr_t       arg4,
-       uintptr_t       threadid
+       uint32_t        coreid,
+       uint32_t        debugid,
+       uint64_t        timestamp,
+       uintptr_t       arg1,
+       uintptr_t       arg2,
+       uintptr_t       arg3,
+       uintptr_t       arg4,
+       uintptr_t       threadid
        )
 {
-       uint32_t        bindx;
-       kd_buf          *kd;
+       uint32_t        bindx;
+       kd_buf          *kd;
        struct kd_bufinfo *kdbp;
        struct kd_storage *kdsp_actual;
        union  kds_ptr kds_raw;
 
        if (kd_ctrl_page.kdebug_slowcheck) {
-
-               if ( (kd_ctrl_page.kdebug_slowcheck & SLOW_NOLOG) || !(kdebug_enable & (KDEBUG_ENABLE_TRACE|KDEBUG_ENABLE_PPT)))
+               if ((kd_ctrl_page.kdebug_slowcheck & SLOW_NOLOG) || !(kdebug_enable & (KDEBUG_ENABLE_TRACE | KDEBUG_ENABLE_PPT))) {
                        goto out1;
-       
+               }
+
                if (kd_ctrl_page.kdebug_flags & KDBG_TYPEFILTER_CHECK) {
-                       if (typefilter_is_debugid_allowed(kdbg_typefilter, debugid))
+                       if (typefilter_is_debugid_allowed(kdbg_typefilter, debugid)) {
                                goto record_event;
+                       }
                        goto out1;
-               }
-               else if (kd_ctrl_page.kdebug_flags & KDBG_RANGECHECK) {
-                       if (debugid >= kdlog_beg && debugid <= kdlog_end)
+               } else if (kd_ctrl_page.kdebug_flags & KDBG_RANGECHECK) {
+                       if (debugid >= kdlog_beg && debugid <= kdlog_end) {
                                goto record_event;
+                       }
                        goto out1;
-               }
-               else if (kd_ctrl_page.kdebug_flags & KDBG_VALCHECK) {
+               } else if (kd_ctrl_page.kdebug_flags & KDBG_VALCHECK) {
                        if ((debugid & KDBG_EVENTID_MASK) != kdlog_value1 &&
-                               (debugid & KDBG_EVENTID_MASK) != kdlog_value2 &&
-                               (debugid & KDBG_EVENTID_MASK) != kdlog_value3 &&
-                               (debugid & KDBG_EVENTID_MASK) != kdlog_value4)
+                           (debugid & KDBG_EVENTID_MASK) != kdlog_value2 &&
+                           (debugid & KDBG_EVENTID_MASK) != kdlog_value3 &&
+                           (debugid & KDBG_EVENTID_MASK) != kdlog_value4) {
                                goto out1;
+                       }
                }
        }
 
-       if (kd_ctrl_page.kdebug_flags & KDBG_WRAPPED) {
-               if (timestamp < kd_ctrl_page.oldest_time) {
-                       goto out1;
-               }
+record_event:
+       if (timestamp < kd_ctrl_page.oldest_time) {
+               goto out1;
        }
 
-record_event:
+#if CONFIG_EMBEDDED
+       /*
+        * When start_kern_tracing is called by the kernel to trace very
+        * early kernel events, it saves data to a secondary buffer until
+        * it is possible to initialize ktrace, and then dumps the events
+        * into the ktrace buffer using this method. In this case, iops will
+        * be NULL, and the coreid will be zero. It is not possible to have
+        * a valid IOP coreid of zero, so pass if both iops is NULL and coreid
+        * is zero.
+        */
+       assert(kdbg_iop_list_contains_cpu_id(kd_ctrl_page.kdebug_iops, coreid) || (kd_ctrl_page.kdebug_iops == NULL && coreid == 0));
+#endif
 
        disable_preemption();
 
-       if (kd_ctrl_page.enabled == 0)
+       if (kd_ctrl_page.enabled == 0) {
                goto out;
+       }
 
        kdbp = &kdbip[coreid];
        timestamp &= KDBG_TIMESTAMP_MASK;
 
 #if KDEBUG_MOJO_TRACE
-       if (kdebug_enable & KDEBUG_ENABLE_SERIAL)
+       if (kdebug_enable & KDEBUG_ENABLE_SERIAL) {
                kdebug_serial_print(coreid, debugid, timestamp,
-                                   arg1, arg2, arg3, arg4, threadid);
+                   arg1, arg2, arg3, arg4, threadid);
+       }
 #endif
 
 retry_q:
@@ -1004,11 +1244,13 @@ retry_q:
        if (kds_raw.raw != KDS_PTR_NULL) {
                kdsp_actual = POINTER_FROM_KDS_PTR(kds_raw);
                bindx = kdsp_actual->kds_bufindx;
-       } else
+       } else {
                kdsp_actual = NULL;
-       
+               bindx = EVENTS_PER_STORAGE_UNIT;
+       }
+
        if (kdsp_actual == NULL || bindx >= EVENTS_PER_STORAGE_UNIT) {
-               if (allocate_storage_unit(coreid) == FALSE) {
+               if (allocate_storage_unit(coreid) == false) {
                        /*
                         * this can only happen if wrapping
                         * has been disabled
@@ -1017,12 +1259,14 @@ retry_q:
                }
                goto retry_q;
        }
-       if ( !OSCompareAndSwap(bindx, bindx + 1, &kdsp_actual->kds_bufindx))
+       if (!OSCompareAndSwap(bindx, bindx + 1, &kdsp_actual->kds_bufindx)) {
                goto retry_q;
+       }
 
        // IOP entries can be allocated before xnu allocates and inits the buffer
-       if (timestamp < kdsp_actual->kds_timestamp)
+       if (timestamp < kdsp_actual->kds_timestamp) {
                kdsp_actual->kds_timestamp = timestamp;
+       }
 
        kd = &kdsp_actual->kds_records[bindx];
 
@@ -1032,7 +1276,7 @@ retry_q:
        kd->arg3 = arg3;
        kd->arg4 = arg4;
        kd->arg5 = threadid;
-                 
+
        kdbg_set_timestamp_and_cpu(kd, timestamp, coreid);
 
        OSAddAtomic(1, &kdsp_actual->kds_bufcnt);
@@ -1044,102 +1288,134 @@ out1:
        }
 }
 
+/*
+ * Check if the given debug ID is allowed to be traced on the current process.
+ *
+ * Returns true if allowed and false otherwise.
+ */
+static inline bool
+kdebug_debugid_procfilt_allowed(uint32_t debugid)
+{
+       uint32_t procfilt_flags = kd_ctrl_page.kdebug_flags &
+           (KDBG_PIDCHECK | KDBG_PIDEXCLUDE);
+
+       if (!procfilt_flags) {
+               return true;
+       }
+
+       /*
+        * DBG_TRACE and MACH_SCHED tracepoints ignore the process filter.
+        */
+       if ((debugid & 0xffff0000) == MACHDBG_CODE(DBG_MACH_SCHED, 0) ||
+           (debugid >> 24 == DBG_TRACE)) {
+               return true;
+       }
+
+       struct proc *curproc = current_proc();
+       /*
+        * If the process is missing (early in boot), allow it.
+        */
+       if (!curproc) {
+               return true;
+       }
+
+       if (procfilt_flags & KDBG_PIDCHECK) {
+               /*
+                * Allow only processes marked with the kdebug bit.
+                */
+               return curproc->p_kdebug;
+       } else if (procfilt_flags & KDBG_PIDEXCLUDE) {
+               /*
+                * Exclude any process marked with the kdebug bit.
+                */
+               return !curproc->p_kdebug;
+       } else {
+               panic("kdebug: invalid procfilt flags %x", kd_ctrl_page.kdebug_flags);
+               __builtin_unreachable();
+       }
+}
+
 static void
 kernel_debug_internal(
-       boolean_t only_filter,
-       uint32_t  debugid,
+       uint32_t debugid,
        uintptr_t arg1,
        uintptr_t arg2,
        uintptr_t arg3,
        uintptr_t arg4,
-       uintptr_t arg5)
+       uintptr_t arg5,
+       uint64_t flags)
 {
-       struct proc     *curproc;
-       uint64_t        now;
-       uint32_t        bindx;
-       kd_buf          *kd;
-       int             cpu;
+       uint64_t now;
+       uint32_t bindx;
+       kd_buf *kd;
+       int cpu;
        struct kd_bufinfo *kdbp;
        struct kd_storage *kdsp_actual;
-       union  kds_ptr kds_raw;
+       union kds_ptr kds_raw;
+       bool only_filter = flags & KDBG_FLAG_FILTERED;
+       bool observe_procfilt = !(flags & KDBG_FLAG_NOPROCFILT);
 
        if (kd_ctrl_page.kdebug_slowcheck) {
                if ((kd_ctrl_page.kdebug_slowcheck & SLOW_NOLOG) ||
-                   !(kdebug_enable & (KDEBUG_ENABLE_TRACE | KDEBUG_ENABLE_PPT)))
-               {
+                   !(kdebug_enable & (KDEBUG_ENABLE_TRACE | KDEBUG_ENABLE_PPT))) {
                        goto out1;
                }
 
-               if ( !ml_at_interrupt_context()) {
-                       if (kd_ctrl_page.kdebug_flags & KDBG_PIDCHECK) {
-                               /*
-                                * If kdebug flag is not set for current proc, return
-                                */
-                               curproc = current_proc();
-
-                               if ((curproc && !(curproc->p_kdebug)) &&
-                                   ((debugid & 0xffff0000) != (MACHDBG_CODE(DBG_MACH_SCHED, 0) | DBG_FUNC_NONE)) &&
-                                     (debugid >> 24 != DBG_TRACE))
-                                       goto out1;
-                       }
-                       else if (kd_ctrl_page.kdebug_flags & KDBG_PIDEXCLUDE) {
-                               /*
-                                * If kdebug flag is set for current proc, return
-                                */
-                               curproc = current_proc();
-
-                               if ((curproc && curproc->p_kdebug) &&
-                                   ((debugid & 0xffff0000) != (MACHDBG_CODE(DBG_MACH_SCHED, 0) | DBG_FUNC_NONE)) &&
-                                     (debugid >> 24 != DBG_TRACE))
-                                       goto out1;
-                       }
+               if (!ml_at_interrupt_context() && observe_procfilt &&
+                   !kdebug_debugid_procfilt_allowed(debugid)) {
+                       goto out1;
                }
 
                if (kd_ctrl_page.kdebug_flags & KDBG_TYPEFILTER_CHECK) {
-                       if (typefilter_is_debugid_allowed(kdbg_typefilter, debugid))
+                       if (typefilter_is_debugid_allowed(kdbg_typefilter, debugid)) {
                                goto record_event;
+                       }
 
                        goto out1;
-               } else if (only_filter == TRUE) {
+               } else if (only_filter) {
                        goto out1;
-               }
-               else if (kd_ctrl_page.kdebug_flags & KDBG_RANGECHECK) {
+               } else if (kd_ctrl_page.kdebug_flags & KDBG_RANGECHECK) {
                        /* Always record trace system info */
-                       if (KDBG_EXTRACT_CLASS(debugid) == DBG_TRACE)
+                       if (KDBG_EXTRACT_CLASS(debugid) == DBG_TRACE) {
                                goto record_event;
-                               
-                       if (debugid < kdlog_beg || debugid > kdlog_end)
+                       }
+
+                       if (debugid < kdlog_beg || debugid > kdlog_end) {
                                goto out1;
-               }
-               else if (kd_ctrl_page.kdebug_flags & KDBG_VALCHECK) {
+                       }
+               else if (kd_ctrl_page.kdebug_flags & KDBG_VALCHECK) {
                        /* Always record trace system info */
-                       if (KDBG_EXTRACT_CLASS(debugid) == DBG_TRACE)
+                       if (KDBG_EXTRACT_CLASS(debugid) == DBG_TRACE) {
                                goto record_event;
-               
+                       }
+
                        if ((debugid & KDBG_EVENTID_MASK) != kdlog_value1 &&
                            (debugid & KDBG_EVENTID_MASK) != kdlog_value2 &&
                            (debugid & KDBG_EVENTID_MASK) != kdlog_value3 &&
-                           (debugid & KDBG_EVENTID_MASK) != kdlog_value4)
+                           (debugid & KDBG_EVENTID_MASK) != kdlog_value4) {
                                goto out1;
+                       }
                }
-       } else if (only_filter == TRUE) {
+       } else if (only_filter) {
                goto out1;
        }
 
 record_event:
        disable_preemption();
 
-       if (kd_ctrl_page.enabled == 0)
+       if (kd_ctrl_page.enabled == 0) {
                goto out;
+       }
 
        cpu = cpu_number();
        kdbp = &kdbip[cpu];
 
 #if KDEBUG_MOJO_TRACE
-       if (kdebug_enable & KDEBUG_ENABLE_SERIAL)
+       if (kdebug_enable & KDEBUG_ENABLE_SERIAL) {
                kdebug_serial_print(cpu, debugid,
-                                   mach_absolute_time() & KDBG_TIMESTAMP_MASK,
-                                   arg1, arg2, arg3, arg4, arg5);
+                   kdbg_timestamp() & KDBG_TIMESTAMP_MASK,
+                   arg1, arg2, arg3, arg4, arg5);
+       }
 #endif
 
 retry_q:
@@ -1148,11 +1424,13 @@ retry_q:
        if (kds_raw.raw != KDS_PTR_NULL) {
                kdsp_actual = POINTER_FROM_KDS_PTR(kds_raw);
                bindx = kdsp_actual->kds_bufindx;
-       } else
+       } else {
                kdsp_actual = NULL;
-       
+               bindx = EVENTS_PER_STORAGE_UNIT;
+       }
+
        if (kdsp_actual == NULL || bindx >= EVENTS_PER_STORAGE_UNIT) {
-               if (allocate_storage_unit(cpu) == FALSE) {
+               if (allocate_storage_unit(cpu) == false) {
                        /*
                         * this can only happen if wrapping
                         * has been disabled
@@ -1161,10 +1439,12 @@ retry_q:
                }
                goto retry_q;
        }
-       now = mach_absolute_time() & KDBG_TIMESTAMP_MASK;
 
-       if ( !OSCompareAndSwap(bindx, bindx + 1, &kdsp_actual->kds_bufindx))
+       now = kdbg_timestamp() & KDBG_TIMESTAMP_MASK;
+
+       if (!OSCompareAndSwap(bindx, bindx + 1, &kdsp_actual->kds_bufindx)) {
                goto retry_q;
+       }
 
        kd = &kdsp_actual->kds_records[bindx];
 
@@ -1186,8 +1466,8 @@ out:
        enable_preemption();
 out1:
        if (kds_waiter && kd_ctrl_page.kds_inuse_count >= n_storage_threshold) {
-               uint32_t        etype;
-               uint32_t        stype;
+               uint32_t        etype;
+               uint32_t        stype;
 
                etype = debugid & KDBG_EVENTID_MASK;
                stype = debugid & KDBG_CSC_MASK;
@@ -1199,41 +1479,57 @@ out1:
        }
 }
 
+__attribute__((noinline))
 void
 kernel_debug(
-       uint32_t        debugid,
-       uintptr_t       arg1,
-       uintptr_t       arg2,
-       uintptr_t       arg3,
-       uintptr_t       arg4,
+       uint32_t        debugid,
+       uintptr_t       arg1,
+       uintptr_t       arg2,
+       uintptr_t       arg3,
+       uintptr_t       arg4,
        __unused uintptr_t arg5)
 {
-       kernel_debug_internal(FALSE, debugid, arg1, arg2, arg3, arg4,
-               (uintptr_t)thread_tid(current_thread()));
+       kernel_debug_internal(debugid, arg1, arg2, arg3, arg4,
+           (uintptr_t)thread_tid(current_thread()), 0);
 }
 
+__attribute__((noinline))
 void
 kernel_debug1(
-       uint32_t        debugid,
-       uintptr_t       arg1,
-       uintptr_t       arg2,
-       uintptr_t       arg3,
-       uintptr_t       arg4,
-       uintptr_t       arg5)
+       uint32_t        debugid,
+       uintptr_t       arg1,
+       uintptr_t       arg2,
+       uintptr_t       arg3,
+       uintptr_t       arg4,
+       uintptr_t       arg5)
+{
+       kernel_debug_internal(debugid, arg1, arg2, arg3, arg4, arg5, 0);
+}
+
+__attribute__((noinline))
+void
+kernel_debug_flags(
+       uint32_t debugid,
+       uintptr_t arg1,
+       uintptr_t arg2,
+       uintptr_t arg3,
+       uintptr_t arg4,
+       uint64_t flags)
 {
-       kernel_debug_internal(FALSE, debugid, arg1, arg2, arg3, arg4, arg5);
+       kernel_debug_internal(debugid, arg1, arg2, arg3, arg4,
+           (uintptr_t)thread_tid(current_thread()), flags);
 }
 
+__attribute__((noinline))
 void
 kernel_debug_filtered(
-       uint32_t  debugid,
+       uint32_t debugid,
        uintptr_t arg1,
        uintptr_t arg2,
        uintptr_t arg3,
        uintptr_t arg4)
 {
-       kernel_debug_internal(TRUE, debugid, arg1, arg2, arg3, arg4,
-               (uintptr_t)thread_tid(current_thread()));
+       kernel_debug_flags(debugid, arg1, arg2, arg3, arg4, KDBG_FLAG_FILTERED);
 }
 
 void
@@ -1254,6 +1550,10 @@ static_assert(SIMPLE_STR_LEN % sizeof(uintptr_t) == 0);
 void
 kernel_debug_string_simple(uint32_t eventid, const char *str)
 {
+       if (!kdebug_enable) {
+               return;
+       }
+
        /* array of uintptr_ts simplifies emitting the string as arguments */
        uintptr_t str_buf[(SIMPLE_STR_LEN / sizeof(uintptr_t)) + 1] = { 0 };
        size_t len = strlcpy((char *)str_buf, str, SIMPLE_STR_LEN + 1);
@@ -1266,10 +1566,10 @@ kernel_debug_string_simple(uint32_t eventid, const char *str)
                debugid |= DBG_FUNC_END;
        }
 
-       kernel_debug_internal(FALSE, debugid, str_buf[0],
-                                             str_buf[1],
-                                             str_buf[2],
-                                             str_buf[3], thread_id);
+       kernel_debug_internal(debugid, str_buf[0],
+           str_buf[1],
+           str_buf[2],
+           str_buf[3], thread_id, 0);
 
        debugid &= KDBG_EVENTID_MASK;
        int i = 4;
@@ -1280,37 +1580,49 @@ kernel_debug_string_simple(uint32_t eventid, const char *str)
                if ((written + (4 * sizeof(uintptr_t))) >= len) {
                        debugid |= DBG_FUNC_END;
                }
-               kernel_debug_internal(FALSE, debugid, str_buf[i],
-                                                     str_buf[i + 1],
-                                                     str_buf[i + 2],
-                                                     str_buf[i + 3], thread_id);
+               kernel_debug_internal(debugid, str_buf[i],
+                   str_buf[i + 1],
+                   str_buf[i + 2],
+                   str_buf[i + 3], thread_id, 0);
        }
 }
 
-extern int     master_cpu;             /* MACH_KERNEL_PRIVATE */
+extern int      master_cpu;             /* MACH_KERNEL_PRIVATE */
 /*
  * Used prior to start_kern_tracing() being called.
  * Log temporarily into a static buffer.
  */
 void
 kernel_debug_early(
-       uint32_t        debugid,
-       uintptr_t       arg1,
-       uintptr_t       arg2,
-       uintptr_t       arg3,
-       uintptr_t       arg4)
+       uint32_t        debugid,
+       uintptr_t       arg1,
+       uintptr_t       arg2,
+       uintptr_t       arg3,
+       uintptr_t       arg4)
 {
-       /* If tracing is already initialized, use it */
-       if (nkdbufs) {
+#if defined(__x86_64__)
+       extern int early_boot;
+       /*
+        * Note that "early" isn't early enough in some cases where
+        * we're invoked before gsbase is set on x86, hence the
+        * check of "early_boot".
+        */
+       if (early_boot) {
+               return;
+       }
+#endif
+
+       /* If early tracing is over, use the normal path. */
+       if (kd_early_done) {
                KERNEL_DEBUG_CONSTANT(debugid, arg1, arg2, arg3, arg4, 0);
                return;
        }
 
-       /* Do nothing if the buffer is full or we're not on the boot cpu */ 
-       kd_early_overflow = kd_early_index >= KD_EARLY_BUFFER_MAX;
-       if (kd_early_overflow ||
-           cpu_number() != master_cpu)
+       /* Do nothing if the buffer is full or we're not on the boot cpu. */
+       kd_early_overflow = kd_early_index >= KD_EARLY_BUFFER_NBUFS;
+       if (kd_early_overflow || cpu_number() != master_cpu) {
                return;
+       }
 
        kd_early_buffer[kd_early_index].debugid = debugid;
        kd_early_buffer[kd_early_index].timestamp = mach_absolute_time();
@@ -1323,44 +1635,48 @@ kernel_debug_early(
 }
 
 /*
- * Transfen the contents of the temporary buffer into the trace buffers.
+ * Transfer the contents of the temporary buffer into the trace buffers.
  * Precede that by logging the rebase time (offset) - the TSC-based time (in ns)
  * when mach_absolute_time is set to 0.
  */
 static void
 kernel_debug_early_end(void)
 {
-       int     i;
-
-       if (cpu_number() != master_cpu)
+       if (cpu_number() != master_cpu) {
                panic("kernel_debug_early_end() not call on boot processor");
+       }
+
+       /* reset the current oldest time to allow early events */
+       kd_ctrl_page.oldest_time = 0;
 
+#if !CONFIG_EMBEDDED
        /* Fake sentinel marking the start of kernel time relative to TSC */
-       kernel_debug_enter(
-               0,
-               TRACE_TIMESTAMPS,
-               0,
-               (uint32_t)(tsc_rebase_abs_time >> 32),
-               (uint32_t)tsc_rebase_abs_time,
-               0,
-               0,
-               0);
-       for (i = 0; i < kd_early_index; i++) {
-               kernel_debug_enter(
-                       0,
-                       kd_early_buffer[i].debugid,
-                       kd_early_buffer[i].timestamp,
-                       kd_early_buffer[i].arg1,
-                       kd_early_buffer[i].arg2,
-                       kd_early_buffer[i].arg3,
-                       kd_early_buffer[i].arg4,
-                       0);
+       kernel_debug_enter(0,
+           TRACE_TIMESTAMPS,
+           0,
+           (uint32_t)(tsc_rebase_abs_time >> 32),
+           (uint32_t)tsc_rebase_abs_time,
+           tsc_at_boot,
+           0,
+           0);
+#endif
+       for (unsigned int i = 0; i < kd_early_index; i++) {
+               kernel_debug_enter(0,
+                   kd_early_buffer[i].debugid,
+                   kd_early_buffer[i].timestamp,
+                   kd_early_buffer[i].arg1,
+                   kd_early_buffer[i].arg2,
+                   kd_early_buffer[i].arg3,
+                   kd_early_buffer[i].arg4,
+                   0);
        }
 
        /* Cut events-lost event on overflow */
-       if (kd_early_overflow)
-               KERNEL_DEBUG_CONSTANT(
-                       TRACE_LOST_EVENTS, 0, 0, 0, 0, 0);
+       if (kd_early_overflow) {
+               KDBG_RELEASE(TRACE_LOST_EVENTS, 1);
+       }
+
+       kd_early_done = true;
 
        /* This trace marks the start of kernel tracing */
        kernel_debug_string_early("early trace done");
@@ -1370,7 +1686,7 @@ void
 kernel_debug_disable(void)
 {
        if (kdebug_enable) {
-               kdbg_set_tracing_enabled(FALSE, 0);
+               kdbg_set_tracing_enabled(false, 0);
        }
 }
 
@@ -1384,8 +1700,8 @@ kdebug_validate_debugid(uint32_t debugid)
 
        debugid_class = KDBG_EXTRACT_CLASS(debugid);
        switch (debugid_class) {
-               case DBG_TRACE:
-                       return EPERM;
+       case DBG_TRACE:
+               return EPERM;
        }
 
        return 0;
@@ -1396,8 +1712,8 @@ kdebug_validate_debugid(uint32_t debugid)
  */
 int
 kdebug_typefilter(__unused struct proc* p,
-                 struct kdebug_typefilter_args* uap,
-                 __unused int *retval)
+    struct kdebug_typefilter_args* uap,
+    __unused int *retval)
 {
        int ret = KERN_SUCCESS;
 
@@ -1434,7 +1750,7 @@ kdebug_typefilter(__unused struct proc* p,
         * the first atomic load test of Global Typefilter Ptr, this function
         * can then safely use the remaining global state without atomic checks.
         */
-       if (!__c11_atomic_load((_Atomic typefilter_t *)&kdbg_typefilter, memory_order_acquire)) {
+       if (!os_atomic_load(&kdbg_typefilter, acquire)) {
                return EINVAL;
        }
 
@@ -1444,17 +1760,19 @@ kdebug_typefilter(__unused struct proc* p,
        vm_map_t user_map = current_map();
 
        ret = mach_to_bsd_errno(
-                       mach_vm_map(user_map,                           // target map
-                                   &user_addr,                         // [in, out] target address
-                                   TYPEFILTER_ALLOC_SIZE,              // initial size
-                                   0,                                  // mask (alignment?)
-                                   VM_FLAGS_ANYWHERE,                  // flags
-                                   kdbg_typefilter_memory_entry,       // port (memory entry!)
-                                   0,                                  // offset (in memory entry)
-                                   FALSE,                              // should copy
-                                   VM_PROT_READ,                       // cur_prot
-                                   VM_PROT_READ,                       // max_prot
-                                   VM_INHERIT_SHARE));                 // inherit behavior on fork
+               mach_vm_map_kernel(user_map,                                    // target map
+               &user_addr,                                             // [in, out] target address
+               TYPEFILTER_ALLOC_SIZE,                                  // initial size
+               0,                                                      // mask (alignment?)
+               VM_FLAGS_ANYWHERE,                                      // flags
+               VM_MAP_KERNEL_FLAGS_NONE,
+               VM_KERN_MEMORY_NONE,
+               kdbg_typefilter_memory_entry,                           // port (memory entry!)
+               0,                                                      // offset (in memory entry)
+               false,                                                  // should copy
+               VM_PROT_READ,                                           // cur_prot
+               VM_PROT_READ,                                           // max_prot
+               VM_INHERIT_SHARE));                                     // inherit behavior on fork
 
        if (ret == KERN_SUCCESS) {
                vm_size_t user_ptr_size = vm_map_is_64bit(user_map) ? 8 : 4;
@@ -1493,25 +1811,24 @@ kdebug_trace(struct proc *p, struct kdebug_trace_args *uap, int32_t *retval)
  * enabled. This is to match the userspace wrapper behavior, which is optimizing
  * for non-error case performance.
  */
-int kdebug_trace64(__unused struct proc *p, struct kdebug_trace64_args *uap, __unused int32_t *retval)
+int
+kdebug_trace64(__unused struct proc *p, struct kdebug_trace64_args *uap, __unused int32_t *retval)
 {
        int err;
 
-       if ( __probable(kdebug_enable == 0) )
-               return(0);
+       if (__probable(kdebug_enable == 0)) {
+               return 0;
+       }
 
        if ((err = kdebug_validate_debugid(uap->code)) != 0) {
                return err;
        }
 
-       kernel_debug_internal(FALSE, uap->code,
-                             (uintptr_t)uap->arg1,
-                             (uintptr_t)uap->arg2,
-                             (uintptr_t)uap->arg3,
-                             (uintptr_t)uap->arg4,
-                             (uintptr_t)thread_tid(current_thread()));
+       kernel_debug_internal(uap->code, (uintptr_t)uap->arg1,
+           (uintptr_t)uap->arg2, (uintptr_t)uap->arg3, (uintptr_t)uap->arg4,
+           (uintptr_t)thread_tid(current_thread()), 0);
 
-       return(0);
+       return 0;
 }
 
 /*
@@ -1540,7 +1857,7 @@ int kdebug_trace64(__unused struct proc *p, struct kdebug_trace64_args *uap, __u
  */
 static uint64_t
 kernel_debug_string_internal(uint32_t debugid, uint64_t str_id, void *vstr,
-                             size_t str_len)
+    size_t str_len)
 {
        /* str must be word-aligned */
        uintptr_t *str = vstr;
@@ -1548,15 +1865,14 @@ kernel_debug_string_internal(uint32_t debugid, uint64_t str_id, void *vstr,
        uintptr_t thread_id;
        int i;
        uint32_t trace_debugid = TRACEDBG_CODE(DBG_TRACE_STRING,
-                                              TRACE_STRING_GLOBAL);
+           TRACE_STRING_GLOBAL);
 
        thread_id = (uintptr_t)thread_tid(current_thread());
 
        /* if the ID is being invalidated, just emit that */
        if (str_id != 0 && str_len == 0) {
-               kernel_debug_internal(FALSE, trace_debugid | DBG_FUNC_START | DBG_FUNC_END,
-                                     (uintptr_t)debugid, (uintptr_t)str_id, 0, 0,
-                                     thread_id);
+               kernel_debug_internal(trace_debugid | DBG_FUNC_START | DBG_FUNC_END,
+                   (uintptr_t)debugid, (uintptr_t)str_id, 0, 0, thread_id, 0);
                return str_id;
        }
 
@@ -1572,9 +1888,8 @@ kernel_debug_string_internal(uint32_t debugid, uint64_t str_id, void *vstr,
                trace_debugid |= DBG_FUNC_END;
        }
 
-       kernel_debug_internal(FALSE, trace_debugid, (uintptr_t)debugid,
-                             (uintptr_t)str_id, str[0],
-                                                str[1], thread_id);
+       kernel_debug_internal(trace_debugid, (uintptr_t)debugid, (uintptr_t)str_id,
+           str[0], str[1], thread_id, 0);
 
        trace_debugid &= KDBG_EVENTID_MASK;
        i = 2;
@@ -1584,10 +1899,10 @@ kernel_debug_string_internal(uint32_t debugid, uint64_t str_id, void *vstr,
                if ((written + (4 * sizeof(uintptr_t))) >= str_len) {
                        trace_debugid |= DBG_FUNC_END;
                }
-               kernel_debug_internal(FALSE, trace_debugid, str[i],
-                                                           str[i + 1],
-                                                           str[i + 2],
-                                                           str[i + 3], thread_id);
+               kernel_debug_internal(trace_debugid, str[i],
+                   str[i + 1],
+                   str[i + 2],
+                   str[i + 3], thread_id, 0);
        }
 
        return str_id;
@@ -1598,19 +1913,18 @@ kernel_debug_string_internal(uint32_t debugid, uint64_t str_id, void *vstr,
  * Trace system and scheduling events circumvent this check, as do events
  * emitted in interrupt context.
  */
-static boolean_t
+static bool
 kdebug_current_proc_enabled(uint32_t debugid)
 {
        /* can't determine current process in interrupt context */
        if (ml_at_interrupt_context()) {
-               return TRUE;
+               return true;
        }
 
        /* always emit trace system and scheduling events */
        if ((KDBG_EXTRACT_CLASS(debugid) == DBG_TRACE ||
-           (debugid & KDBG_CSC_MASK) == MACHDBG_CODE(DBG_MACH_SCHED, 0)))
-       {
-               return TRUE;
+           (debugid & KDBG_CSC_MASK) == MACHDBG_CODE(DBG_MACH_SCHED, 0))) {
+               return true;
        }
 
        if (kd_ctrl_page.kdebug_flags & KDBG_PIDCHECK) {
@@ -1618,56 +1932,58 @@ kdebug_current_proc_enabled(uint32_t debugid)
 
                /* only the process with the kdebug bit set is allowed */
                if (cur_proc && !(cur_proc->p_kdebug)) {
-                       return FALSE;
+                       return false;
                }
        } else if (kd_ctrl_page.kdebug_flags & KDBG_PIDEXCLUDE) {
                proc_t cur_proc = current_proc();
 
                /* every process except the one with the kdebug bit set is allowed */
                if (cur_proc && cur_proc->p_kdebug) {
-                       return FALSE;
+                       return false;
                }
        }
 
-       return TRUE;
+       return true;
 }
 
-/*
- * Returns false if the debugid is disabled by filters, and true if the
- * debugid is allowed to be traced.  A debugid may not be traced if the
- * typefilter disables its class and subclass, it's outside a range
- * check, or if it's not an allowed debugid in a value check.  Trace
- * system events bypass this check.
- */
-boolean_t
+bool
 kdebug_debugid_enabled(uint32_t debugid)
 {
        /* if no filtering is enabled */
        if (!kd_ctrl_page.kdebug_slowcheck) {
-               return TRUE;
+               return true;
        }
 
+       return kdebug_debugid_explicitly_enabled(debugid);
+}
+
+bool
+kdebug_debugid_explicitly_enabled(uint32_t debugid)
+{
        if (kd_ctrl_page.kdebug_flags & KDBG_TYPEFILTER_CHECK) {
                return typefilter_is_debugid_allowed(kdbg_typefilter, debugid);
        } else if (KDBG_EXTRACT_CLASS(debugid) == DBG_TRACE) {
-               return TRUE;
-       }
-
-       if (kd_ctrl_page.kdebug_flags & KDBG_RANGECHECK) {
+               return true;
+       } else if (kd_ctrl_page.kdebug_flags & KDBG_RANGECHECK) {
                if (debugid < kdlog_beg || debugid > kdlog_end) {
-                       return FALSE;
+                       return false;
                }
        } else if (kd_ctrl_page.kdebug_flags & KDBG_VALCHECK) {
                if ((debugid & KDBG_EVENTID_MASK) != kdlog_value1 &&
-                       (debugid & KDBG_EVENTID_MASK) != kdlog_value2 &&
-                       (debugid & KDBG_EVENTID_MASK) != kdlog_value3 &&
-                       (debugid & KDBG_EVENTID_MASK) != kdlog_value4)
-               {
-                       return FALSE;
+                   (debugid & KDBG_EVENTID_MASK) != kdlog_value2 &&
+                   (debugid & KDBG_EVENTID_MASK) != kdlog_value3 &&
+                   (debugid & KDBG_EVENTID_MASK) != kdlog_value4) {
+                       return false;
                }
        }
 
-       return TRUE;
+       return true;
+}
+
+bool
+kdebug_using_continuous_time(void)
+{
+       return kdebug_enable & KDEBUG_ENABLE_CONT_TIME;
 }
 
 /*
@@ -1735,7 +2051,7 @@ kernel_debug_string(uint32_t debugid, uint64_t *str_id, const char *str)
        memset(str_buf, 0, sizeof(str_buf));
        len_copied = strlcpy(str_buf, str, MAX_STR_LEN + 1);
        *str_id = kernel_debug_string_internal(debugid, *str_id, str_buf,
-                                              len_copied);
+           len_copied);
        return 0;
 }
 
@@ -1744,8 +2060,8 @@ kernel_debug_string(uint32_t debugid, uint64_t *str_id, const char *str)
  */
 int
 kdebug_trace_string(__unused struct proc *p,
-                    struct kdebug_trace_string_args *uap,
-                    uint64_t *retval)
+    struct kdebug_trace_string_args *uap,
+    uint64_t *retval)
 {
        __attribute__((aligned(sizeof(uintptr_t)))) char str_buf[STR_BUF_SIZE];
        static_assert(sizeof(str_buf) > MAX_STR_LEN);
@@ -1774,7 +2090,7 @@ kdebug_trace_string(__unused struct proc *p,
                }
 
                *retval = kernel_debug_string_internal(uap->debugid, uap->str_id,
-                                                      NULL, 0);
+                   NULL, 0);
                return 0;
        }
 
@@ -1796,7 +2112,7 @@ kdebug_trace_string(__unused struct proc *p,
        len_copied--;
 
        *retval = kernel_debug_string_internal(uap->debugid, uap->str_id, str_buf,
-                                              len_copied);
+           len_copied);
        return 0;
 }
 
@@ -1804,7 +2120,6 @@ static void
 kdbg_lock_init(void)
 {
        static lck_grp_attr_t *kdebug_lck_grp_attr = NULL;
-       static lck_grp_t      *kdebug_lck_grp      = NULL;
        static lck_attr_t     *kdebug_lck_attr     = NULL;
 
        if (kd_ctrl_page.kdebug_flags & KDBG_LOCKINIT) {
@@ -1823,15 +2138,15 @@ kdbg_lock_init(void)
 }
 
 int
-kdbg_bootstrap(boolean_t early_trace)
+kdbg_bootstrap(bool early_trace)
 {
        kd_ctrl_page.kdebug_flags &= ~KDBG_WRAPPED;
 
-       return (create_buffers(early_trace));
+       return create_buffers(early_trace);
 }
 
 int
-kdbg_reinit(boolean_t early_trace)
+kdbg_reinit(bool early_trace)
 {
        int ret = 0;
 
@@ -1857,26 +2172,29 @@ kdbg_reinit(boolean_t early_trace)
        RAW_file_offset = 0;
        RAW_file_written = 0;
 
-       return(ret);
+       return ret;
 }
 
 void
-kdbg_trace_data(struct proc *proc, long *arg_pid)
+kdbg_trace_data(struct proc *proc, long *arg_pid, long *arg_uniqueid)
 {
-       if (!proc)
+       if (!proc) {
                *arg_pid = 0;
-       else
+               *arg_uniqueid = 0;
+       } else {
                *arg_pid = proc->p_pid;
+               *arg_uniqueid = proc->p_uniqueid;
+               if ((uint64_t) *arg_uniqueid != proc->p_uniqueid) {
+                       *arg_uniqueid = 0;
+               }
+       }
 }
 
 
 void
-kdbg_trace_string(struct proc *proc, long *arg1, long *arg2, long *arg3, long *arg4)
+kdbg_trace_string(struct proc *proc, long *arg1, long *arg2, long *arg3,
+    long *arg4)
 {
-       char *dbg_nameptr; 
-       int dbg_namelen;
-       long dbg_parms[4];
-
        if (!proc) {
                *arg1 = 0;
                *arg2 = 0;
@@ -1884,25 +2202,22 @@ kdbg_trace_string(struct proc *proc, long *arg1, long *arg2, long *arg3, long *a
                *arg4 = 0;
                return;
        }
-       /*
-        * Collect the pathname for tracing
-        */
-       dbg_nameptr = proc->p_comm;
-       dbg_namelen = (int)strlen(proc->p_comm);
-       dbg_parms[0]=0L;
-       dbg_parms[1]=0L;
-       dbg_parms[2]=0L;
-       dbg_parms[3]=0L;
-  
-       if(dbg_namelen > (int)sizeof(dbg_parms))
-               dbg_namelen = (int)sizeof(dbg_parms);
-    
-       strncpy((char *)dbg_parms, dbg_nameptr, dbg_namelen);
-
-       *arg1=dbg_parms[0];
-       *arg2=dbg_parms[1];
-       *arg3=dbg_parms[2];
-       *arg4=dbg_parms[3];
+
+       const char *procname = proc_best_name(proc);
+       size_t namelen = strlen(procname);
+
+       long args[4] = { 0 };
+
+       if (namelen > sizeof(args)) {
+               namelen = sizeof(args);
+       }
+
+       strncpy((char *)args, procname, namelen);
+
+       *arg1 = args[0];
+       *arg2 = args[1];
+       *arg3 = args[2];
+       *arg4 = args[3];
 }
 
 static void
@@ -1915,16 +2230,17 @@ kdbg_resolve_map(thread_t th_act, void *opaque)
                mapptr = &t->map[t->count];
                mapptr->thread  = (uintptr_t)thread_tid(th_act);
 
-               (void) strlcpy (mapptr->command, t->atts->task_comm,
-                               sizeof(t->atts->task_comm));
+               (void) strlcpy(mapptr->command, t->atts->task_comm,
+                   sizeof(t->atts->task_comm));
                /*
                 * Some kernel threads have no associated pid.
                 * We still need to mark the entry as valid.
                 */
-               if (t->atts->pid)
+               if (t->atts->pid) {
                        mapptr->valid = t->atts->pid;
-               else
+               } else {
                        mapptr->valid = 1;
+               }
 
                t->count++;
        }
@@ -1966,7 +2282,7 @@ kdbg_cpumap_init_internal(kd_iop_t* iops, uint32_t cpu_count, uint8_t** cpumap,
        uint32_t bytes_needed = sizeof(kd_cpumap_header) + cpu_count * sizeof(kd_cpumap);
        uint32_t bytes_available = *cpumap_size;
        *cpumap_size = bytes_needed;
-       
+
        if (*cpumap == NULL) {
                if (kmem_alloc(kernel_map, (vm_offset_t*)cpumap, (vm_size_t)*cpumap_size, VM_KERN_MEMORY_DIAG) != KERN_SUCCESS) {
                        return ENOMEM;
@@ -1988,11 +2304,11 @@ kdbg_cpumap_init_internal(kd_iop_t* iops, uint32_t cpu_count, uint8_t** cpumap,
                cpus[index].cpu_id = iops->cpu_id;
                cpus[index].flags = KDBG_CPUMAP_IS_IOP;
                strlcpy(cpus[index].name, iops->callback.iop_name, sizeof(cpus->name));
-               
+
                iops = iops->next;
                index--;
        }
-       
+
        while (index >= 0) {
                cpus[index].cpu_id = index;
                cpus[index].flags = 0;
@@ -2000,14 +2316,14 @@ kdbg_cpumap_init_internal(kd_iop_t* iops, uint32_t cpu_count, uint8_t** cpumap,
 
                index--;
        }
-       
+
        return KERN_SUCCESS;
 }
 
 void
 kdbg_thrmap_init(void)
 {
-       lck_mtx_assert(ktrace_lock, LCK_MTX_ASSERT_OWNED);
+       ktrace_assert_lock_held();
 
        if (kd_ctrl_page.kdebug_flags & KDBG_MAPINIT) {
                return;
@@ -2040,7 +2356,7 @@ kdbg_thrmap_init_internal(unsigned int count, unsigned int *mapsize, unsigned in
        /*
         * The proc count could change during buffer allocation,
         * so introduce a small fudge factor to bump up the
-        * buffer sizes. This gives new tasks some chance of 
+        * buffer sizes. This gives new tasks some chance of
         * making into the tables.  Bump up by 25%.
         */
        *mapcount += *mapcount / 4;
@@ -2150,7 +2466,7 @@ kdbg_clear(void)
        kd_ctrl_page.oldest_time = 0;
 
        delete_buffers();
-       nkdbufs = 0;
+       nkdbufs = 0;
 
        /* Clean up the thread map buffer */
        kdbg_clear_thread_map();
@@ -2162,7 +2478,7 @@ kdbg_clear(void)
 void
 kdebug_reset(void)
 {
-       lck_mtx_assert(ktrace_lock, LCK_MTX_ASSERT_OWNED);
+       ktrace_assert_lock_held();
 
        kdbg_lock_init();
 
@@ -2173,27 +2489,37 @@ kdebug_reset(void)
        }
 }
 
+void
+kdebug_free_early_buf(void)
+{
+#if !CONFIG_EMBEDDED
+       /* Must be done with the buffer, so release it back to the VM.
+        * On embedded targets this buffer is freed when the BOOTDATA segment is freed. */
+       ml_static_mfree((vm_offset_t)&kd_early_buffer, sizeof(kd_early_buffer));
+#endif
+}
+
 int
 kdbg_setpid(kd_regtype *kdr)
 {
        pid_t pid;
-       int flag, ret=0;
+       int flag, ret = 0;
        struct proc *p;
 
        pid = (pid_t)kdr->value1;
        flag = (int)kdr->value2;
 
        if (pid >= 0) {
-               if ((p = proc_find(pid)) == NULL)
+               if ((p = proc_find(pid)) == NULL) {
                        ret = ESRCH;
-               else {
+               else {
                        if (flag == 1) {
                                /*
                                 * turn on pid check for this and all pids
                                 */
                                kd_ctrl_page.kdebug_flags |= KDBG_PIDCHECK;
                                kd_ctrl_page.kdebug_flags &= ~KDBG_PIDEXCLUDE;
-                               kdbg_set_flags(SLOW_CHECKS, 0, TRUE);
+                               kdbg_set_flags(SLOW_CHECKS, 0, true);
 
                                p->p_kdebug = 1;
                        } else {
@@ -2202,16 +2528,16 @@ kdbg_setpid(kd_regtype *kdr)
                                 * Don't turn off all pid checking though
                                 *
                                 * kd_ctrl_page.kdebug_flags &= ~KDBG_PIDCHECK;
-                                */   
+                                */
                                p->p_kdebug = 0;
                        }
                        proc_rele(p);
                }
-       }
-       else
+       } else {
                ret = EINVAL;
+       }
 
-       return(ret);
+       return ret;
 }
 
 /* This is for pid exclusion in the trace buffer */
@@ -2219,41 +2545,41 @@ int
 kdbg_setpidex(kd_regtype *kdr)
 {
        pid_t pid;
-       int flag, ret=0;
+       int flag, ret = 0;
        struct proc *p;
 
        pid = (pid_t)kdr->value1;
        flag = (int)kdr->value2;
 
        if (pid >= 0) {
-               if ((p = proc_find(pid)) == NULL)
+               if ((p = proc_find(pid)) == NULL) {
                        ret = ESRCH;
-               else {
+               else {
                        if (flag == 1) {
                                /*
                                 * turn on pid exclusion
                                 */
                                kd_ctrl_page.kdebug_flags |= KDBG_PIDEXCLUDE;
                                kd_ctrl_page.kdebug_flags &= ~KDBG_PIDCHECK;
-                               kdbg_set_flags(SLOW_CHECKS, 0, TRUE);
+                               kdbg_set_flags(SLOW_CHECKS, 0, true);
 
                                p->p_kdebug = 1;
-                       }
-                       else {
+                       } else {
                                /*
                                 * turn off pid exclusion for this pid value
                                 * Don't turn off all pid exclusion though
                                 *
                                 * kd_ctrl_page.kdebug_flags &= ~KDBG_PIDEXCLUDE;
-                                */   
+                                */
                                p->p_kdebug = 0;
                        }
                        proc_rele(p);
                }
-       } else
+       } else {
                ret = EINVAL;
+       }
 
-       return(ret);
+       return ret;
 }
 
 /*
@@ -2267,7 +2593,7 @@ kdbg_setpidex(kd_regtype *kdr)
 static int
 kdbg_initialize_typefilter(typefilter_t tf)
 {
-       lck_mtx_assert(ktrace_lock, LCK_MTX_ASSERT_OWNED);
+       ktrace_assert_lock_held();
        assert(!kdbg_typefilter);
        assert(!kdbg_typefilter_memory_entry);
        typefilter_t deallocate_tf = NULL;
@@ -2289,7 +2615,7 @@ kdbg_initialize_typefilter(typefilter_t tf)
         * that any non-null kdbg_typefilter means a
         * valid memory_entry is available.
         */
-       __c11_atomic_store(((_Atomic typefilter_t*)&kdbg_typefilter), tf, memory_order_release);
+       os_atomic_store(&kdbg_typefilter, tf, release);
 
        return KERN_SUCCESS;
 }
@@ -2300,7 +2626,7 @@ kdbg_copyin_typefilter(user_addr_t addr, size_t size)
        int ret = ENOMEM;
        typefilter_t tf;
 
-       lck_mtx_assert(ktrace_lock, LCK_MTX_ASSERT_OWNED);
+       ktrace_assert_lock_held();
 
        if (size != KDBG_TYPEFILTER_BITMAP_SIZE) {
                return EINVAL;
@@ -2317,7 +2643,7 @@ kdbg_copyin_typefilter(user_addr_t addr, size_t size)
                         *
                         * Allocating a typefilter for the copyin allows
                         * the kernel to hold the invariant that DBG_TRACE
-                        * must always be allowed. 
+                        * must always be allowed.
                         */
                        if (!kdbg_typefilter) {
                                if ((ret = kdbg_initialize_typefilter(tf))) {
@@ -2332,8 +2658,9 @@ kdbg_copyin_typefilter(user_addr_t addr, size_t size)
                        kdbg_iop_list_callback(kd_ctrl_page.kdebug_iops, KD_CALLBACK_TYPEFILTER_CHANGED, kdbg_typefilter);
                }
 
-               if (tf)
+               if (tf) {
                        typefilter_deallocate(tf);
+               }
        }
 
        return ret;
@@ -2350,7 +2677,7 @@ kdbg_enable_typefilter(void)
        assert(kdbg_typefilter);
        kd_ctrl_page.kdebug_flags &= ~(KDBG_RANGECHECK | KDBG_VALCHECK);
        kd_ctrl_page.kdebug_flags |= KDBG_TYPEFILTER_CHECK;
-       kdbg_set_flags(SLOW_CHECKS, 0, TRUE);
+       kdbg_set_flags(SLOW_CHECKS, 0, true);
        commpage_update_kdebug_state();
 }
 
@@ -2361,14 +2688,26 @@ kdbg_enable_typefilter(void)
 static void
 kdbg_disable_typefilter(void)
 {
+       bool notify_iops = kd_ctrl_page.kdebug_flags & KDBG_TYPEFILTER_CHECK;
        kd_ctrl_page.kdebug_flags &= ~KDBG_TYPEFILTER_CHECK;
 
        if ((kd_ctrl_page.kdebug_flags & (KDBG_PIDCHECK | KDBG_PIDEXCLUDE))) {
-               kdbg_set_flags(SLOW_CHECKS, 0, TRUE);
+               kdbg_set_flags(SLOW_CHECKS, 0, true);
        } else {
-               kdbg_set_flags(SLOW_CHECKS, 0, FALSE);
+               kdbg_set_flags(SLOW_CHECKS, 0, false);
        }
        commpage_update_kdebug_state();
+
+       if (notify_iops) {
+               /*
+                * Notify IOPs that the typefilter will now allow everything.
+                * Otherwise, they won't know a typefilter is no longer in
+                * effect.
+                */
+               typefilter_allow_all(kdbg_typefilter);
+               kdbg_iop_list_callback(kd_ctrl_page.kdebug_iops,
+                   KD_CALLBACK_TYPEFILTER_CHANGED, kdbg_typefilter);
+       }
 }
 
 uint32_t
@@ -2388,38 +2727,37 @@ kdebug_commpage_state(void)
 int
 kdbg_setreg(kd_regtype * kdr)
 {
-       int ret=0;
+       int ret = 0;
        unsigned int val_1, val_2, val;
        switch (kdr->type) {
-       
-       case KDBG_CLASSTYPE :
+       case KDBG_CLASSTYPE:
                val_1 = (kdr->value1 & 0xff);
                val_2 = (kdr->value2 & 0xff);
-               kdlog_beg = (val_1<<24);
-               kdlog_end = (val_2<<24);
+               kdlog_beg = (val_1 << 24);
+               kdlog_end = (val_2 << 24);
                kd_ctrl_page.kdebug_flags &= (unsigned int)~KDBG_CKTYPES;
                kd_ctrl_page.kdebug_flags &= ~KDBG_VALCHECK;       /* Turn off specific value check  */
                kd_ctrl_page.kdebug_flags |= (KDBG_RANGECHECK | KDBG_CLASSTYPE);
-               kdbg_set_flags(SLOW_CHECKS, 0, TRUE);
+               kdbg_set_flags(SLOW_CHECKS, 0, true);
                break;
-       case KDBG_SUBCLSTYPE :
+       case KDBG_SUBCLSTYPE:
                val_1 = (kdr->value1 & 0xff);
                val_2 = (kdr->value2 & 0xff);
                val = val_2 + 1;
-               kdlog_beg = ((val_1<<24) | (val_2 << 16));
-               kdlog_end = ((val_1<<24) | (val << 16));
+               kdlog_beg = ((val_1 << 24) | (val_2 << 16));
+               kdlog_end = ((val_1 << 24) | (val << 16));
                kd_ctrl_page.kdebug_flags &= (unsigned int)~KDBG_CKTYPES;
                kd_ctrl_page.kdebug_flags &= ~KDBG_VALCHECK;       /* Turn off specific value check  */
                kd_ctrl_page.kdebug_flags |= (KDBG_RANGECHECK | KDBG_SUBCLSTYPE);
-               kdbg_set_flags(SLOW_CHECKS, 0, TRUE);
+               kdbg_set_flags(SLOW_CHECKS, 0, true);
                break;
-       case KDBG_RANGETYPE :
+       case KDBG_RANGETYPE:
                kdlog_beg = (kdr->value1);
                kdlog_end = (kdr->value2);
                kd_ctrl_page.kdebug_flags &= (unsigned int)~KDBG_CKTYPES;
                kd_ctrl_page.kdebug_flags &= ~KDBG_VALCHECK;       /* Turn off specific value check  */
                kd_ctrl_page.kdebug_flags |= (KDBG_RANGECHECK | KDBG_RANGETYPE);
-               kdbg_set_flags(SLOW_CHECKS, 0, TRUE);
+               kdbg_set_flags(SLOW_CHECKS, 0, true);
                break;
        case KDBG_VALCHECK:
                kdlog_value1 = (kdr->value1);
@@ -2429,33 +2767,34 @@ kdbg_setreg(kd_regtype * kdr)
                kd_ctrl_page.kdebug_flags &= (unsigned int)~KDBG_CKTYPES;
                kd_ctrl_page.kdebug_flags &= ~KDBG_RANGECHECK;    /* Turn off range check */
                kd_ctrl_page.kdebug_flags |= KDBG_VALCHECK;       /* Turn on specific value check  */
-               kdbg_set_flags(SLOW_CHECKS, 0, TRUE);
+               kdbg_set_flags(SLOW_CHECKS, 0, true);
                break;
-       case KDBG_TYPENONE :
+       case KDBG_TYPENONE:
                kd_ctrl_page.kdebug_flags &= (unsigned int)~KDBG_CKTYPES;
 
-               if ( (kd_ctrl_page.kdebug_flags & (KDBG_RANGECHECK | KDBG_VALCHECK   | 
-                                                  KDBG_PIDCHECK   | KDBG_PIDEXCLUDE | 
-                                                  KDBG_TYPEFILTER_CHECK)) )
-                       kdbg_set_flags(SLOW_CHECKS, 0, TRUE);
-               else
-                       kdbg_set_flags(SLOW_CHECKS, 0, FALSE);
+               if ((kd_ctrl_page.kdebug_flags & (KDBG_RANGECHECK | KDBG_VALCHECK   |
+                   KDBG_PIDCHECK   | KDBG_PIDEXCLUDE |
+                   KDBG_TYPEFILTER_CHECK))) {
+                       kdbg_set_flags(SLOW_CHECKS, 0, true);
+               } else {
+                       kdbg_set_flags(SLOW_CHECKS, 0, false);
+               }
 
                kdlog_beg = 0;
                kdlog_end = 0;
                break;
-       default :
+       default:
                ret = EINVAL;
                break;
        }
-       return(ret);
+       return ret;
 }
 
 static int
 kdbg_write_to_vnode(caddr_t buffer, size_t size, vnode_t vp, vfs_context_t ctx, off_t file_offset)
 {
-       return vn_rdwr(UIO_WRITE, vp, buffer, size, file_offset, UIO_SYSSPACE, IO_NODELOCKED|IO_UNIT,
-                       vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
+       return vn_rdwr(UIO_WRITE, vp, buffer, size, file_offset, UIO_SYSSPACE, IO_NODELOCKED | IO_UNIT,
+                  vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
 }
 
 int
@@ -2480,8 +2819,7 @@ kdbg_write_v3_chunk_header(user_addr_t buffer, uint32_t tag, uint32_t sub_tag, u
                                goto write_error;
                        }
                        RAW_file_offset  += (sizeof(kd_chunk_header_v3));
-               }
-               else {
+               } else {
                        ret = copyout(&header, buffer, sizeof(kd_chunk_header_v3));
                        if (ret) {
                                goto write_error;
@@ -2492,25 +2830,7 @@ write_error:
        return ret;
 }
 
-int
-kdbg_write_v3_chunk_header_to_buffer(void * buffer, uint32_t tag, uint32_t sub_tag, uint64_t length)
-{
-       kd_chunk_header_v3 header = {
-               .tag = tag,
-               .sub_tag = sub_tag,
-               .length = length,
-       };
-
-       if (!buffer) {
-               return 0;
-       }
-
-       memcpy(buffer, &header, sizeof(kd_chunk_header_v3));
-
-       return (sizeof(kd_chunk_header_v3));
-}
-
-int
+static int
 kdbg_write_v3_chunk_to_fd(uint32_t tag, uint32_t sub_tag, uint64_t length, void *payload, uint64_t payload_size, int fd)
 {
        proc_t p;
@@ -2520,7 +2840,7 @@ kdbg_write_v3_chunk_to_fd(uint32_t tag, uint32_t sub_tag, uint64_t length, void
        p = current_proc();
 
        proc_fdlock(p);
-       if ( (fp_lookup(p, fd, &fp, 1)) ) {
+       if ((fp_lookup(p, fd, &fp, 1))) {
                proc_fdunlock(p);
                return EFAULT;
        }
@@ -2536,7 +2856,7 @@ kdbg_write_v3_chunk_to_fd(uint32_t tag, uint32_t sub_tag, uint64_t length, void
        vp = (struct vnode *) fp->f_fglob->fg_data;
        proc_fdunlock(p);
 
-       if ( (vnode_getwithref(vp)) == 0 ) {
+       if ((vnode_getwithref(vp)) == 0) {
                RAW_file_offset = fp->f_fglob->fg_offset;
 
                kd_chunk_header_v3 chunk_header = {
@@ -2566,180 +2886,176 @@ kdbg_write_v3_chunk_to_fd(uint32_t tag, uint32_t sub_tag, uint64_t length, void
 user_addr_t
 kdbg_write_v3_event_chunk_header(user_addr_t buffer, uint32_t tag, uint64_t length, vnode_t vp, vfs_context_t ctx)
 {
-        uint64_t future_chunk_timestamp = 0;
-        length += sizeof(uint64_t);
-
-        if (kdbg_write_v3_chunk_header(buffer, tag, V3_EVENT_DATA_VERSION, length, vp, ctx)) {
-                return 0;
-        }
-        if (buffer) {
-                buffer += sizeof(kd_chunk_header_v3);
-        }
-
-        // Check that only one of them is valid
-        assert(!buffer ^ !vp);
-        assert((vp == NULL) || (ctx != NULL));
-
-        // Write the 8-byte future_chunk_timestamp field in the payload
-        if (buffer || vp) {
-                if (vp) {
-                        int ret = kdbg_write_to_vnode((caddr_t)&future_chunk_timestamp, sizeof(uint64_t), vp, ctx, RAW_file_offset);
-                        if (!ret) {
-                                RAW_file_offset  += (sizeof(uint64_t));
-                        }
-                }
-                else {
-                        if (copyout(&future_chunk_timestamp, buffer, sizeof(uint64_t))) {
-                                return 0;
-                        }
-                }
-        }
-
-        return (buffer + sizeof(uint64_t));
+       uint64_t future_chunk_timestamp = 0;
+       length += sizeof(uint64_t);
+
+       if (kdbg_write_v3_chunk_header(buffer, tag, V3_EVENT_DATA_VERSION, length, vp, ctx)) {
+               return 0;
+       }
+       if (buffer) {
+               buffer += sizeof(kd_chunk_header_v3);
+       }
+
+       // Check that only one of them is valid
+       assert(!buffer ^ !vp);
+       assert((vp == NULL) || (ctx != NULL));
+
+       // Write the 8-byte future_chunk_timestamp field in the payload
+       if (buffer || vp) {
+               if (vp) {
+                       int ret = kdbg_write_to_vnode((caddr_t)&future_chunk_timestamp, sizeof(uint64_t), vp, ctx, RAW_file_offset);
+                       if (!ret) {
+                               RAW_file_offset  += (sizeof(uint64_t));
+                       }
+               } else {
+                       if (copyout(&future_chunk_timestamp, buffer, sizeof(uint64_t))) {
+                               return 0;
+                       }
+               }
+       }
+
+       return buffer + sizeof(uint64_t);
 }
 
 int
 kdbg_write_v3_header(user_addr_t user_header, size_t *user_header_size, int fd)
 {
-        int ret = KERN_SUCCESS;
-
-        uint8_t* cpumap = 0;
-        uint32_t cpumap_size = 0;
-        uint32_t thrmap_size = 0;
-
-        size_t bytes_needed = 0;
-
-        // Check that only one of them is valid
-        assert(!user_header ^ !fd);
-        assert(user_header_size);
-
-        if ( !(kd_ctrl_page.kdebug_flags & KDBG_BUFINIT) ) {
-                ret = EINVAL;
-                goto bail;
-        }
-
-        if ( !(user_header || fd) ) {
-                ret = EINVAL;
-                goto bail;
-        }
-
-        // Initialize the cpu map
-        ret = kdbg_cpumap_init_internal(kd_ctrl_page.kdebug_iops, kd_ctrl_page.kdebug_cpus, &cpumap, &cpumap_size);
-        if (ret != KERN_SUCCESS) {
-                goto bail;
-        }
-
-        // Check if a thread map is initialized
-        if ( !kd_mapptr ) {
-                ret = EINVAL;
-                goto bail;
-        }
-        thrmap_size = kd_mapcount * sizeof(kd_threadmap);
-
-        mach_timebase_info_data_t timebase = {0, 0};
-        clock_timebase_info(&timebase);
-
-        // Setup the header.
-        // See v3 header description in sys/kdebug.h for more inforamtion.
-        kd_header_v3 header = {
-            .tag = RAW_VERSION3,
-            .sub_tag = V3_HEADER_VERSION,
-            .length = (sizeof(kd_header_v3) + cpumap_size - sizeof(kd_cpumap_header)),
-            .timebase_numer = timebase.numer,
-            .timebase_denom = timebase.denom,
-            .timestamp = 0, /* FIXME rdar://problem/22053009 */
-            .walltime_secs = 0,
-            .walltime_usecs = 0,
-            .timezone_minuteswest = 0,
-            .timezone_dst = 0,
+       int ret = KERN_SUCCESS;
+
+       uint8_t* cpumap = 0;
+       uint32_t cpumap_size = 0;
+       uint32_t thrmap_size = 0;
+
+       size_t bytes_needed = 0;
+
+       // Check that only one of them is valid
+       assert(!user_header ^ !fd);
+       assert(user_header_size);
+
+       if (!(kd_ctrl_page.kdebug_flags & KDBG_BUFINIT)) {
+               ret = EINVAL;
+               goto bail;
+       }
+
+       if (!(user_header || fd)) {
+               ret = EINVAL;
+               goto bail;
+       }
+
+       // Initialize the cpu map
+       ret = kdbg_cpumap_init_internal(kd_ctrl_page.kdebug_iops, kd_ctrl_page.kdebug_cpus, &cpumap, &cpumap_size);
+       if (ret != KERN_SUCCESS) {
+               goto bail;
+       }
+
+       // Check if a thread map is initialized
+       if (!kd_mapptr) {
+               ret = EINVAL;
+               goto bail;
+       }
+       thrmap_size = kd_mapcount * sizeof(kd_threadmap);
+
+       mach_timebase_info_data_t timebase = {0, 0};
+       clock_timebase_info(&timebase);
+
+       // Setup the header.
+       // See v3 header description in sys/kdebug.h for more inforamtion.
+       kd_header_v3 header = {
+               .tag = RAW_VERSION3,
+               .sub_tag = V3_HEADER_VERSION,
+               .length = (sizeof(kd_header_v3) + cpumap_size - sizeof(kd_cpumap_header)),
+               .timebase_numer = timebase.numer,
+               .timebase_denom = timebase.denom,
+               .timestamp = 0, /* FIXME rdar://problem/22053009 */
+               .walltime_secs = 0,
+               .walltime_usecs = 0,
+               .timezone_minuteswest = 0,
+               .timezone_dst = 0,
 #if defined(__LP64__)
-            .flags = 1,
+               .flags = 1,
 #else
-            .flags = 0,
+               .flags = 0,
 #endif
-        };
-
-        // If its a buffer, check if we have enough space to copy the header and the maps.
-        if (user_header) {
-                bytes_needed = header.length + thrmap_size + (2 * sizeof(kd_chunk_header_v3));
-                if (*user_header_size < bytes_needed) {
-                        ret = EINVAL;
-                        goto bail;
-                }
-        }
-
-        // Start writing the header
-        if (fd) {
-                void *hdr_ptr = (void *)(((uintptr_t) &header) + sizeof(kd_chunk_header_v3));
-                size_t payload_size = (sizeof(kd_header_v3) - sizeof(kd_chunk_header_v3));
-
-                ret = kdbg_write_v3_chunk_to_fd(RAW_VERSION3, V3_HEADER_VERSION, header.length, hdr_ptr, payload_size, fd);
-                if (ret) {
-                        goto bail;
-                }
-        }
-        else {
-            if (copyout(&header, user_header, sizeof(kd_header_v3))) {
-                    ret = EFAULT;
-                    goto bail;
-            }
-            // Update the user pointer
-            user_header += sizeof(kd_header_v3);
-        }
-
-        // Write a cpu map. This is a sub chunk of the header
-        cpumap = (uint8_t*)((uintptr_t) cpumap + sizeof(kd_cpumap_header));
-        size_t payload_size = (size_t)(cpumap_size - sizeof(kd_cpumap_header));
-        if (fd) {
-                ret = kdbg_write_v3_chunk_to_fd(V3_CPU_MAP, V3_CPUMAP_VERSION, payload_size, (void *)cpumap, payload_size, fd);
-                if (ret) {
-                        goto bail;
-                }
-        }
-        else {
-                ret = kdbg_write_v3_chunk_header(user_header, V3_CPU_MAP, V3_CPUMAP_VERSION, payload_size, NULL, NULL);
-                if (ret) {
-                        goto bail;
-                }
-                user_header += sizeof(kd_chunk_header_v3);
-                if (copyout(cpumap, user_header, payload_size))  {
-                        ret = EFAULT;
-                        goto bail;
-                }
-                // Update the user pointer
-                user_header += payload_size;
-        }
-
-        // Write a thread map
-        if (fd) {
-                ret = kdbg_write_v3_chunk_to_fd(V3_THREAD_MAP, V3_THRMAP_VERSION, thrmap_size, (void *)kd_mapptr, thrmap_size, fd);
-                if (ret) {
-                        goto bail;
-                }
-        }
-        else {
-                ret = kdbg_write_v3_chunk_header(user_header, V3_THREAD_MAP, V3_THRMAP_VERSION, thrmap_size, NULL, NULL);
-                if (ret) {
-                        goto bail;
-                }
-                user_header += sizeof(kd_chunk_header_v3);
-                if (copyout(kd_mapptr, user_header, thrmap_size)) {
-                        ret = EFAULT;
-                        goto bail;
-                }
-                user_header += thrmap_size;
-        }
-
-        if (fd) {
-                RAW_file_written += bytes_needed;
-        }
-
-        *user_header_size = bytes_needed;
+       };
+
+       // If its a buffer, check if we have enough space to copy the header and the maps.
+       if (user_header) {
+               bytes_needed = header.length + thrmap_size + (2 * sizeof(kd_chunk_header_v3));
+               if (*user_header_size < bytes_needed) {
+                       ret = EINVAL;
+                       goto bail;
+               }
+       }
+
+       // Start writing the header
+       if (fd) {
+               void *hdr_ptr = (void *)(((uintptr_t) &header) + sizeof(kd_chunk_header_v3));
+               size_t payload_size = (sizeof(kd_header_v3) - sizeof(kd_chunk_header_v3));
+
+               ret = kdbg_write_v3_chunk_to_fd(RAW_VERSION3, V3_HEADER_VERSION, header.length, hdr_ptr, payload_size, fd);
+               if (ret) {
+                       goto bail;
+               }
+       } else {
+               if (copyout(&header, user_header, sizeof(kd_header_v3))) {
+                       ret = EFAULT;
+                       goto bail;
+               }
+               // Update the user pointer
+               user_header += sizeof(kd_header_v3);
+       }
+
+       // Write a cpu map. This is a sub chunk of the header
+       cpumap = (uint8_t*)((uintptr_t) cpumap + sizeof(kd_cpumap_header));
+       size_t payload_size = (size_t)(cpumap_size - sizeof(kd_cpumap_header));
+       if (fd) {
+               ret = kdbg_write_v3_chunk_to_fd(V3_CPU_MAP, V3_CPUMAP_VERSION, payload_size, (void *)cpumap, payload_size, fd);
+               if (ret) {
+                       goto bail;
+               }
+       } else {
+               ret = kdbg_write_v3_chunk_header(user_header, V3_CPU_MAP, V3_CPUMAP_VERSION, payload_size, NULL, NULL);
+               if (ret) {
+                       goto bail;
+               }
+               user_header += sizeof(kd_chunk_header_v3);
+               if (copyout(cpumap, user_header, payload_size)) {
+                       ret = EFAULT;
+                       goto bail;
+               }
+               // Update the user pointer
+               user_header += payload_size;
+       }
+
+       // Write a thread map
+       if (fd) {
+               ret = kdbg_write_v3_chunk_to_fd(V3_THREAD_MAP, V3_THRMAP_VERSION, thrmap_size, (void *)kd_mapptr, thrmap_size, fd);
+               if (ret) {
+                       goto bail;
+               }
+       } else {
+               ret = kdbg_write_v3_chunk_header(user_header, V3_THREAD_MAP, V3_THRMAP_VERSION, thrmap_size, NULL, NULL);
+               if (ret) {
+                       goto bail;
+               }
+               user_header += sizeof(kd_chunk_header_v3);
+               if (copyout(kd_mapptr, user_header, thrmap_size)) {
+                       ret = EFAULT;
+                       goto bail;
+               }
+               user_header += thrmap_size;
+       }
+
+       if (fd) {
+               RAW_file_written += bytes_needed;
+       }
+
+       *user_header_size = bytes_needed;
 bail:
-        if (cpumap) {
-                kmem_free(kernel_map, (vm_offset_t)cpumap, cpumap_size);
-        }
-        return (ret);
+       if (cpumap) {
+               kmem_free(kernel_map, (vm_offset_t)cpumap, cpumap_size);
+       }
+       return ret;
 }
 
 int
@@ -2759,12 +3075,14 @@ kdbg_readcpumap(user_addr_t user_cpumap, size_t *user_cpumap_size)
                        }
                        *user_cpumap_size = cpumap_size;
                        kmem_free(kernel_map, (vm_offset_t)cpumap, cpumap_size);
-               } else
+               } else {
                        ret = EINVAL;
-       } else
+               }
+       } else {
                ret = EINVAL;
+       }
 
-       return (ret);
+       return ret;
 }
 
 int
@@ -2776,24 +3094,26 @@ kdbg_readcurthrmap(user_addr_t buffer, size_t *bufsize)
        unsigned int count = 0;
        int ret = 0;
 
-       count = *bufsize/sizeof(kd_threadmap);
+       count = *bufsize / sizeof(kd_threadmap);
        *bufsize = 0;
 
-       if ( (mapptr = kdbg_thrmap_init_internal(count, &mapsize, &mapcount)) ) {
-               if (copyout(mapptr, buffer, mapcount * sizeof(kd_threadmap)))
+       if ((mapptr = kdbg_thrmap_init_internal(count, &mapsize, &mapcount))) {
+               if (copyout(mapptr, buffer, mapcount * sizeof(kd_threadmap))) {
                        ret = EFAULT;
-               else
+               } else {
                        *bufsize = (mapcount * sizeof(kd_threadmap));
+               }
 
                kmem_free(kernel_map, (vm_offset_t)mapptr, mapsize);
-       } else
+       } else {
                ret = EINVAL;
+       }
 
-       return (ret);
+       return ret;
 }
 
 static int
-kdbg_write_v1_header(boolean_t write_thread_map, vnode_t vp, vfs_context_t ctx)
+kdbg_write_v1_header(bool write_thread_map, vnode_t vp, vfs_context_t ctx)
 {
        int ret = 0;
        RAW_header header;
@@ -2848,7 +3168,7 @@ kdbg_write_v1_header(boolean_t write_thread_map, vnode_t vp, vfs_context_t ctx)
         * the cpumap is embedded in the last 4K page before when the event data is expected.
         * This way the tools can read the data starting the next page boundary on both
         * 4K and 16K systems preserving compatibility with older versions of the tools
-       */
+        */
        if (pad_size > PAGE_4KB) {
                pad_size -= PAGE_4KB;
                extra_thread_count = (pad_size / sizeof(kd_threadmap)) + 1;
@@ -2863,7 +3183,7 @@ kdbg_write_v1_header(boolean_t write_thread_map, vnode_t vp, vfs_context_t ctx)
        header.TOD_usecs = usecs;
 
        ret = vn_rdwr(UIO_WRITE, vp, (caddr_t)&header, sizeof(RAW_header), RAW_file_offset,
-                     UIO_SYSSPACE, IO_NODELOCKED|IO_UNIT, vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
+           UIO_SYSSPACE, IO_NODELOCKED | IO_UNIT, vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
        if (ret) {
                goto write_error;
        }
@@ -2872,7 +3192,7 @@ kdbg_write_v1_header(boolean_t write_thread_map, vnode_t vp, vfs_context_t ctx)
 
        if (write_thread_map) {
                ret = vn_rdwr(UIO_WRITE, vp, (caddr_t)kd_mapptr, map_size, RAW_file_offset,
-                             UIO_SYSSPACE, IO_NODELOCKED|IO_UNIT, vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
+                   UIO_SYSSPACE, IO_NODELOCKED | IO_UNIT, vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
                if (ret) {
                        goto write_error;
                }
@@ -2891,7 +3211,7 @@ kdbg_write_v1_header(boolean_t write_thread_map, vnode_t vp, vfs_context_t ctx)
                memset(pad_buf, 0, pad_size);
 
                ret = vn_rdwr(UIO_WRITE, vp, (caddr_t)pad_buf, pad_size, RAW_file_offset,
-                             UIO_SYSSPACE, IO_NODELOCKED|IO_UNIT, vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
+                   UIO_SYSSPACE, IO_NODELOCKED | IO_UNIT, vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
                kfree(pad_buf, pad_size);
                if (ret) {
                        goto write_error;
@@ -2921,7 +3241,7 @@ kdbg_write_v1_header(boolean_t write_thread_map, vnode_t vp, vfs_context_t ctx)
                }
 
                ret = vn_rdwr(UIO_WRITE, vp, (caddr_t)pad_buf, pad_size, RAW_file_offset,
-                               UIO_SYSSPACE, IO_NODELOCKED|IO_UNIT, vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
+                   UIO_SYSSPACE, IO_NODELOCKED | IO_UNIT, vfs_context_ucred(ctx), (int *) 0, vfs_context_proc(ctx));
                kfree(pad_buf, pad_size);
                if (ret) {
                        goto write_error;
@@ -2938,7 +3258,7 @@ write_error:
 static void
 kdbg_clear_thread_map(void)
 {
-       lck_mtx_assert(ktrace_lock, LCK_MTX_ASSERT_OWNED);
+       ktrace_assert_lock_held();
 
        if (kd_ctrl_page.kdebug_flags & KDBG_MAPINIT) {
                assert(kd_mapptr != NULL);
@@ -2962,9 +3282,9 @@ static int
 kdbg_write_thread_map(vnode_t vp, vfs_context_t ctx)
 {
        int ret = 0;
-       boolean_t map_initialized;
+       bool map_initialized;
 
-       lck_mtx_assert(ktrace_lock, LCK_MTX_ASSERT_OWNED);
+       ktrace_assert_lock_held();
        assert(ctx != NULL);
 
        map_initialized = (kd_ctrl_page.kdebug_flags & KDBG_MAPINIT);
@@ -2991,11 +3311,11 @@ kdbg_write_thread_map(vnode_t vp, vfs_context_t ctx)
 static int
 kdbg_copyout_thread_map(user_addr_t buffer, size_t *buffer_size)
 {
-       boolean_t map_initialized;
+       bool map_initialized;
        size_t map_size;
        int ret = 0;
 
-       lck_mtx_assert(ktrace_lock, LCK_MTX_ASSERT_OWNED);
+       ktrace_assert_lock_held();
        assert(buffer_size != NULL);
 
        map_initialized = (kd_ctrl_page.kdebug_flags & KDBG_MAPINIT);
@@ -3020,10 +3340,10 @@ int
 kdbg_readthrmap_v3(user_addr_t buffer, size_t buffer_size, int fd)
 {
        int ret = 0;
-       boolean_t map_initialized;
+       bool map_initialized;
        size_t map_size;
 
-       lck_mtx_assert(ktrace_lock, LCK_MTX_ASSERT_OWNED);
+       ktrace_assert_lock_held();
 
        if ((!fd && !buffer) || (fd && buffer)) {
                return EINVAL;
@@ -3032,8 +3352,7 @@ kdbg_readthrmap_v3(user_addr_t buffer, size_t buffer_size, int fd)
        map_initialized = (kd_ctrl_page.kdebug_flags & KDBG_MAPINIT);
        map_size = kd_mapcount * sizeof(kd_threadmap);
 
-       if (map_initialized && (buffer_size >= map_size))
-       {
+       if (map_initialized && (buffer_size >= map_size)) {
                ret = kdbg_write_v3_header(buffer, &buffer_size, fd);
 
                if (ret == 0) {
@@ -3043,24 +3362,17 @@ kdbg_readthrmap_v3(user_addr_t buffer, size_t buffer_size, int fd)
                ret = EINVAL;
        }
 
-       return  ret;
+       return ret;
 }
 
 static void
-kdbg_set_nkdbufs(unsigned int value)
+kdbg_set_nkdbufs(unsigned int req_nkdbufs)
 {
        /*
-        * We allow a maximum buffer size of 50% of either ram or max mapped
-        * address, whichever is smaller 'value' is the desired number of trace
-        * entries
+        * Only allow allocation up to half the available memory (sane_size).
         */
-       unsigned int max_entries = (sane_size / 2) / sizeof(kd_buf);
-
-       if (value <= max_entries) {
-               nkdbufs = value;
-       } else {
-               nkdbufs = max_entries;
-       }
+       uint64_t max_nkdbufs = (sane_size / 2) / sizeof(kd_buf);
+       nkdbufs = (req_nkdbufs > max_nkdbufs) ? max_nkdbufs : req_nkdbufs;
 }
 
 /*
@@ -3073,32 +3385,33 @@ kdbg_set_nkdbufs(unsigned int value)
  *
  * Called with `ktrace_lock` locked and interrupts enabled.
  */
-static boolean_t
-kdbg_wait(uint64_t timeout_ms, boolean_t locked_wait)
+static bool
+kdbg_wait(uint64_t timeout_ms, bool locked_wait)
 {
        int wait_result = THREAD_AWAKENED;
        uint64_t abstime = 0;
 
+       ktrace_assert_lock_held();
+
        if (timeout_ms != 0) {
                uint64_t ns = timeout_ms * NSEC_PER_MSEC;
-               nanoseconds_to_absolutetime(ns,  &abstime);
+               nanoseconds_to_absolutetime(ns, &abstime);
                clock_absolutetime_interval_to_deadline(abstime, &abstime);
        }
 
-       boolean_t s = ml_set_interrupts_enabled(FALSE);
+       bool s = ml_set_interrupts_enabled(false);
        if (!s) {
                panic("kdbg_wait() called with interrupts disabled");
        }
-       lck_spin_lock(kdw_spin_lock);
+       lck_spin_lock_grp(kdw_spin_lock, kdebug_lck_grp);
 
        if (!locked_wait) {
                /* drop the mutex to allow others to access trace */
-               lck_mtx_unlock(ktrace_lock);
+               ktrace_unlock();
        }
 
        while (wait_result == THREAD_AWAKENED &&
-              kd_ctrl_page.kds_inuse_count < n_storage_threshold)
-       {
+           kd_ctrl_page.kds_inuse_count < n_storage_threshold) {
                kds_waiter = 1;
 
                if (abstime) {
@@ -3111,14 +3424,14 @@ kdbg_wait(uint64_t timeout_ms, boolean_t locked_wait)
        }
 
        /* check the count under the spinlock */
-       boolean_t threshold_exceeded = (kd_ctrl_page.kds_inuse_count >= n_storage_threshold);
+       bool threshold_exceeded = (kd_ctrl_page.kds_inuse_count >= n_storage_threshold);
 
        lck_spin_unlock(kdw_spin_lock);
        ml_set_interrupts_enabled(s);
 
        if (!locked_wait) {
                /* pick the mutex back up again */
-               lck_mtx_lock(ktrace_lock);
+               ktrace_lock();
        }
 
        /* write out whether we've exceeded the threshold */
@@ -3132,7 +3445,7 @@ kdbg_wait(uint64_t timeout_ms, boolean_t locked_wait)
 static void
 kdbg_wakeup(void)
 {
-       boolean_t need_kds_wakeup = FALSE;
+       bool need_kds_wakeup = false;
 
        /*
         * Try to take the lock here to synchronize with the waiter entering
@@ -3142,21 +3455,20 @@ kdbg_wakeup(void)
         * conditions.  No problem if we fail, there will be lots of additional
         * events coming in that will eventually succeed in grabbing this lock.
         */
-       boolean_t s = ml_set_interrupts_enabled(FALSE);
+       bool s = ml_set_interrupts_enabled(false);
 
        if (lck_spin_try_lock(kdw_spin_lock)) {
                if (kds_waiter &&
-                   (kd_ctrl_page.kds_inuse_count >= n_storage_threshold))
-               {
+                   (kd_ctrl_page.kds_inuse_count >= n_storage_threshold)) {
                        kds_waiter = 0;
-                       need_kds_wakeup = TRUE;
+                       need_kds_wakeup = true;
                }
                lck_spin_unlock(kdw_spin_lock);
        }
 
        ml_set_interrupts_enabled(s);
 
-       if (need_kds_wakeup == TRUE) {
+       if (need_kds_wakeup == true) {
                wakeup(&kds_waiter);
        }
 }
@@ -3171,16 +3483,14 @@ kdbg_control(int *name, u_int namelen, user_addr_t where, size_t *sizep)
        kbufinfo_t kd_bufinfo;
        proc_t p;
 
-       if (name[0] == KERN_KDGETENTROPY ||
-               name[0] == KERN_KDWRITETR ||
-               name[0] == KERN_KDWRITETR_V3 ||
-               name[0] == KERN_KDWRITEMAP ||
-               name[0] == KERN_KDWRITEMAP_V3 ||
-               name[0] == KERN_KDEFLAGS ||
-               name[0] == KERN_KDDFLAGS ||
-               name[0] == KERN_KDENABLE ||
-               name[0] == KERN_KDSETBUF)
-       {
+       if (name[0] == KERN_KDWRITETR ||
+           name[0] == KERN_KDWRITETR_V3 ||
+           name[0] == KERN_KDWRITEMAP ||
+           name[0] == KERN_KDWRITEMAP_V3 ||
+           name[0] == KERN_KDEFLAGS ||
+           name[0] == KERN_KDDFLAGS ||
+           name[0] == KERN_KDENABLE ||
+           name[0] == KERN_KDSETBUF) {
                if (namelen < 2) {
                        return EINVAL;
                }
@@ -3190,7 +3500,7 @@ kdbg_control(int *name, u_int namelen, user_addr_t where, size_t *sizep)
        kdbg_lock_init();
        assert(kd_ctrl_page.kdebug_flags & KDBG_LOCKINIT);
 
-       lck_mtx_lock(ktrace_lock);
+       ktrace_lock();
 
        /*
         * Some requests only require "read" access to kdebug trace.  Regardless,
@@ -3199,9 +3509,7 @@ kdbg_control(int *name, u_int namelen, user_addr_t where, size_t *sizep)
         */
        if (name[0] != KERN_KDGETBUF &&
            name[0] != KERN_KDGETREG &&
-           name[0] != KERN_KDREADCURTHRMAP &&
-           name[0] != KERN_KDGETENTROPY)
-       {
+           name[0] != KERN_KDREADCURTHRMAP) {
                if ((ret = ktrace_configure(KTRACE_KDEBUG))) {
                        goto out;
                }
@@ -3211,256 +3519,249 @@ kdbg_control(int *name, u_int namelen, user_addr_t where, size_t *sizep)
                }
        }
 
-       switch(name[0]) {
-               case KERN_KDGETBUF:
-                       if (size < sizeof(kd_bufinfo.nkdbufs)) {
-                               /*
-                                * There is not enough room to return even
-                                * the first element of the info structure.
-                                */
-                               ret = EINVAL;
-                               break;
-                       }
+       switch (name[0]) {
+       case KERN_KDGETBUF:
+               if (size < sizeof(kd_bufinfo.nkdbufs)) {
+                       /*
+                        * There is not enough room to return even
+                        * the first element of the info structure.
+                        */
+                       ret = EINVAL;
+                       break;
+               }
 
-                       memset(&kd_bufinfo, 0, sizeof(kd_bufinfo));
+               memset(&kd_bufinfo, 0, sizeof(kd_bufinfo));
 
-                       kd_bufinfo.nkdbufs = nkdbufs;
-                       kd_bufinfo.nkdthreads = kd_mapcount;
+               kd_bufinfo.nkdbufs = nkdbufs;
+               kd_bufinfo.nkdthreads = kd_mapcount;
 
-                       if ( (kd_ctrl_page.kdebug_slowcheck & SLOW_NOLOG) )
-                               kd_bufinfo.nolog = 1;
-                       else
-                               kd_bufinfo.nolog = 0;
+               if ((kd_ctrl_page.kdebug_slowcheck & SLOW_NOLOG)) {
+                       kd_bufinfo.nolog = 1;
+               } else {
+                       kd_bufinfo.nolog = 0;
+               }
 
-                       kd_bufinfo.flags = kd_ctrl_page.kdebug_flags;
+               kd_bufinfo.flags = kd_ctrl_page.kdebug_flags;
 #if defined(__LP64__)
-                       kd_bufinfo.flags |= KDBG_LP64;
+               kd_bufinfo.flags |= KDBG_LP64;
 #endif
-                       {
-                               int pid = ktrace_get_owning_pid();
-                               kd_bufinfo.bufid = (pid == 0 ? -1 : pid);
-                       }
+               {
+                       int pid = ktrace_get_owning_pid();
+                       kd_bufinfo.bufid = (pid == 0 ? -1 : pid);
+               }
 
-                       if (size >= sizeof(kd_bufinfo)) {
-                               /*
-                                * Provide all the info we have
-                                */
-                               if (copyout(&kd_bufinfo, where, sizeof(kd_bufinfo)))
-                                       ret = EINVAL;
-                       } else {
-                               /*
-                                * For backwards compatibility, only provide
-                                * as much info as there is room for.
-                                */
-                               if (copyout(&kd_bufinfo, where, size))
-                                       ret = EINVAL;
+               if (size >= sizeof(kd_bufinfo)) {
+                       /*
+                        * Provide all the info we have
+                        */
+                       if (copyout(&kd_bufinfo, where, sizeof(kd_bufinfo))) {
+                               ret = EINVAL;
+                       }
+               } else {
+                       /*
+                        * For backwards compatibility, only provide
+                        * as much info as there is room for.
+                        */
+                       if (copyout(&kd_bufinfo, where, size)) {
+                               ret = EINVAL;
                        }
-                       break;
-
-               case KERN_KDGETENTROPY: {
-                       /* Obsolescent - just fake with a random buffer */
-                       char    *buffer = (char *) kalloc(size);
-                       read_frandom((void *) buffer, size);
-                       ret = copyout(buffer, where, size);
-                       kfree(buffer, size);
-                       break;
                }
+               break;
 
-               case KERN_KDREADCURTHRMAP:
-                       ret = kdbg_readcurthrmap(where, sizep);
-                       break;
+       case KERN_KDREADCURTHRMAP:
+               ret = kdbg_readcurthrmap(where, sizep);
+               break;
 
-               case KERN_KDEFLAGS:
-                       value &= KDBG_USERFLAGS;
-                       kd_ctrl_page.kdebug_flags |= value;
-                       break;
+       case KERN_KDEFLAGS:
+               value &= KDBG_USERFLAGS;
+               kd_ctrl_page.kdebug_flags |= value;
+               break;
 
-               case KERN_KDDFLAGS:
-                       value &= KDBG_USERFLAGS;
-                       kd_ctrl_page.kdebug_flags &= ~value;
-                       break;
+       case KERN_KDDFLAGS:
+               value &= KDBG_USERFLAGS;
+               kd_ctrl_page.kdebug_flags &= ~value;
+               break;
 
-               case KERN_KDENABLE:
+       case KERN_KDENABLE:
+               /*
+                * Enable tracing mechanism.  Two types:
+                * KDEBUG_TRACE is the standard one,
+                * and KDEBUG_PPT which is a carefully
+                * chosen subset to avoid performance impact.
+                */
+               if (value) {
                        /*
-                        * Enable tracing mechanism.  Two types:
-                        * KDEBUG_TRACE is the standard one,
-                        * and KDEBUG_PPT which is a carefully
-                        * chosen subset to avoid performance impact.
+                        * enable only if buffer is initialized
                         */
-                       if (value) {
-                               /*
-                                * enable only if buffer is initialized
-                                */
-                               if (!(kd_ctrl_page.kdebug_flags & KDBG_BUFINIT) || 
-                                   !(value == KDEBUG_ENABLE_TRACE || value == KDEBUG_ENABLE_PPT)) {
-                                       ret = EINVAL;
-                                       break;
-                               }
-                               kdbg_thrmap_init();
-
-                               kdbg_set_tracing_enabled(TRUE, value);
+                       if (!(kd_ctrl_page.kdebug_flags & KDBG_BUFINIT) ||
+                           !(value == KDEBUG_ENABLE_TRACE || value == KDEBUG_ENABLE_PPT)) {
+                               ret = EINVAL;
+                               break;
                        }
-                       else
-                       {
-                               if (!kdebug_enable) {
-                                       break;
-                               }
+                       kdbg_thrmap_init();
 
-                               kernel_debug_disable();
+                       kdbg_set_tracing_enabled(true, value);
+               } else {
+                       if (!kdebug_enable) {
+                               break;
                        }
-                       break;
 
-               case KERN_KDSETBUF:
-                       kdbg_set_nkdbufs(value);
-                       break;
+                       kernel_debug_disable();
+               }
+               break;
 
-               case KERN_KDSETUP:
-                       ret = kdbg_reinit(FALSE);
-                       break;
+       case KERN_KDSETBUF:
+               kdbg_set_nkdbufs(value);
+               break;
 
-               case KERN_KDREMOVE:
-                       ktrace_reset(KTRACE_KDEBUG);
-                       break;
+       case KERN_KDSETUP:
+               ret = kdbg_reinit(false);
+               break;
 
-               case KERN_KDSETREG:
-                       if(size < sizeof(kd_regtype)) {
-                               ret = EINVAL;
-                               break;
-                       }
-                       if (copyin(where, &kd_Reg, sizeof(kd_regtype))) {
-                               ret = EINVAL;
-                               break;
-                       }
+       case KERN_KDREMOVE:
+               ktrace_reset(KTRACE_KDEBUG);
+               break;
 
-                       ret = kdbg_setreg(&kd_Reg);
+       case KERN_KDSETREG:
+               if (size < sizeof(kd_regtype)) {
+                       ret = EINVAL;
                        break;
-
-               case KERN_KDGETREG:
+               }
+               if (copyin(where, &kd_Reg, sizeof(kd_regtype))) {
                        ret = EINVAL;
                        break;
+               }
 
-               case KERN_KDREADTR:
-                       ret = kdbg_read(where, sizep, NULL, NULL, RAW_VERSION1);
-                       break;
+               ret = kdbg_setreg(&kd_Reg);
+               break;
 
-               case KERN_KDWRITETR:
-               case KERN_KDWRITETR_V3:
-               case KERN_KDWRITEMAP:
-               case KERN_KDWRITEMAP_V3:
-               {
-                       struct  vfs_context context;
-                       struct  fileproc *fp;
-                       size_t  number;
-                       vnode_t vp;
-                       int     fd;
+       case KERN_KDGETREG:
+               ret = EINVAL;
+               break;
 
-                       if (name[0] == KERN_KDWRITETR || name[0] == KERN_KDWRITETR_V3) {
-                               (void)kdbg_wait(size, TRUE);
-                       }
-                       p = current_proc();
-                       fd = value;
+       case KERN_KDREADTR:
+               ret = kdbg_read(where, sizep, NULL, NULL, RAW_VERSION1);
+               break;
 
-                       proc_fdlock(p);
-                       if ( (ret = fp_lookup(p, fd, &fp, 1)) ) {
-                               proc_fdunlock(p);
-                               break;
-                       }
-                       context.vc_thread = current_thread();
-                       context.vc_ucred = fp->f_fglob->fg_cred;
+       case KERN_KDWRITETR:
+       case KERN_KDWRITETR_V3:
+       case KERN_KDWRITEMAP:
+       case KERN_KDWRITEMAP_V3:
+       {
+               struct  vfs_context context;
+               struct  fileproc *fp;
+               size_t  number;
+               vnode_t vp;
+               int     fd;
+
+               if (name[0] == KERN_KDWRITETR || name[0] == KERN_KDWRITETR_V3) {
+                       (void)kdbg_wait(size, true);
+               }
+               p = current_proc();
+               fd = value;
 
-                       if (FILEGLOB_DTYPE(fp->f_fglob) != DTYPE_VNODE) {
-                               fp_drop(p, fd, fp, 1);
-                               proc_fdunlock(p);
+               proc_fdlock(p);
+               if ((ret = fp_lookup(p, fd, &fp, 1))) {
+                       proc_fdunlock(p);
+                       break;
+               }
+               context.vc_thread = current_thread();
+               context.vc_ucred = fp->f_fglob->fg_cred;
 
-                               ret = EBADF;
-                               break;
-                       }
-                       vp = (struct vnode *)fp->f_fglob->fg_data;
+               if (FILEGLOB_DTYPE(fp->f_fglob) != DTYPE_VNODE) {
+                       fp_drop(p, fd, fp, 1);
                        proc_fdunlock(p);
 
-                       if ((ret = vnode_getwithref(vp)) == 0) {
-                               RAW_file_offset = fp->f_fglob->fg_offset;
-                               if (name[0] == KERN_KDWRITETR || name[0] == KERN_KDWRITETR_V3) {
-                                       number = nkdbufs * sizeof(kd_buf);
+                       ret = EBADF;
+                       break;
+               }
+               vp = (struct vnode *)fp->f_fglob->fg_data;
+               proc_fdunlock(p);
+
+               if ((ret = vnode_getwithref(vp)) == 0) {
+                       RAW_file_offset = fp->f_fglob->fg_offset;
+                       if (name[0] == KERN_KDWRITETR || name[0] == KERN_KDWRITETR_V3) {
+                               number = nkdbufs * sizeof(kd_buf);
 
-                                       KERNEL_DEBUG_CONSTANT(TRACE_WRITING_EVENTS | DBG_FUNC_START, 0, 0, 0, 0, 0);
-                                       if (name[0] == KERN_KDWRITETR_V3)
-                                               ret = kdbg_read(0, &number, vp, &context, RAW_VERSION3);
-                                       else
-                                               ret = kdbg_read(0, &number, vp, &context, RAW_VERSION1);
-                                       KERNEL_DEBUG_CONSTANT(TRACE_WRITING_EVENTS | DBG_FUNC_END, number, 0, 0, 0, 0);
+                               KDBG_RELEASE(TRACE_WRITING_EVENTS | DBG_FUNC_START);
+                               if (name[0] == KERN_KDWRITETR_V3) {
+                                       ret = kdbg_read(0, &number, vp, &context, RAW_VERSION3);
+                               } else {
+                                       ret = kdbg_read(0, &number, vp, &context, RAW_VERSION1);
+                               }
+                               KDBG_RELEASE(TRACE_WRITING_EVENTS | DBG_FUNC_END, number);
 
-                                       *sizep = number;
+                               *sizep = number;
+                       } else {
+                               number = kd_mapcount * sizeof(kd_threadmap);
+                               if (name[0] == KERN_KDWRITEMAP_V3) {
+                                       ret = kdbg_readthrmap_v3(0, number, fd);
                                } else {
-                                       number = kd_mapcount * sizeof(kd_threadmap);
-                                       if (name[0] == KERN_KDWRITEMAP_V3) {
-                                               ret = kdbg_readthrmap_v3(0, number, fd);
-                                       } else {
-                                               ret = kdbg_write_thread_map(vp, &context);
-                                       }
+                                       ret = kdbg_write_thread_map(vp, &context);
                                }
-                               fp->f_fglob->fg_offset = RAW_file_offset;
-                               vnode_put(vp);
                        }
-                       fp_drop(p, fd, fp, 0);
+                       fp->f_fglob->fg_offset = RAW_file_offset;
+                       vnode_put(vp);
+               }
+               fp_drop(p, fd, fp, 0);
 
+               break;
+       }
+       case KERN_KDBUFWAIT:
+               *sizep = kdbg_wait(size, false);
+               break;
+
+       case KERN_KDPIDTR:
+               if (size < sizeof(kd_regtype)) {
+                       ret = EINVAL;
                        break;
                }
-               case KERN_KDBUFWAIT:
-                       *sizep = kdbg_wait(size, FALSE);
+               if (copyin(where, &kd_Reg, sizeof(kd_regtype))) {
+                       ret = EINVAL;
                        break;
+               }
 
-               case KERN_KDPIDTR:
-                       if (size < sizeof(kd_regtype)) {
-                               ret = EINVAL;
-                               break;
-                       }
-                       if (copyin(where, &kd_Reg, sizeof(kd_regtype))) {
-                               ret = EINVAL;
-                               break;
-                       }
+               ret = kdbg_setpid(&kd_Reg);
+               break;
 
-                       ret = kdbg_setpid(&kd_Reg);
+       case KERN_KDPIDEX:
+               if (size < sizeof(kd_regtype)) {
+                       ret = EINVAL;
                        break;
-
-               case KERN_KDPIDEX:
-                       if (size < sizeof(kd_regtype)) {
-                               ret = EINVAL;
-                               break;
-                       }
-                       if (copyin(where, &kd_Reg, sizeof(kd_regtype))) {
-                               ret = EINVAL;
-                               break;
-                       }
-
-                       ret = kdbg_setpidex(&kd_Reg);
+               }
+               if (copyin(where, &kd_Reg, sizeof(kd_regtype))) {
+                       ret = EINVAL;
                        break;
+               }
 
-               case KERN_KDCPUMAP:
-                       ret = kdbg_readcpumap(where, sizep);
-                       break;
+               ret = kdbg_setpidex(&kd_Reg);
+               break;
 
-               case KERN_KDTHRMAP:
-                       ret = kdbg_copyout_thread_map(where, sizep);
-                       break;
+       case KERN_KDCPUMAP:
+               ret = kdbg_readcpumap(where, sizep);
+               break;
 
-               case KERN_KDSET_TYPEFILTER: {
-                       ret = kdbg_copyin_typefilter(where, size);
-                       break;
-               }
+       case KERN_KDTHRMAP:
+               ret = kdbg_copyout_thread_map(where, sizep);
+               break;
 
-               case KERN_KDTEST:
-                       ret = kdbg_test();
-                       break;
+       case KERN_KDSET_TYPEFILTER: {
+               ret = kdbg_copyin_typefilter(where, size);
+               break;
+       }
 
-               default:
-                       ret = EINVAL;
-                       break;
+       case KERN_KDTEST:
+               ret = kdbg_test(size);
+               break;
+
+       default:
+               ret = EINVAL;
+               break;
        }
 out:
-       lck_mtx_unlock(ktrace_lock);
+       ktrace_unlock();
 
-       return(ret);
+       return ret;
 }
 
 
@@ -3481,6 +3782,7 @@ kdbg_read(user_addr_t buffer, size_t *number, vnode_t vp, vfs_context_t ctx, uin
        uint32_t rcursor;
        kd_buf lostevent;
        union kds_ptr kdsp;
+       bool traced_retrograde = false;
        struct kd_storage *kdsp_actual;
        struct kd_bufinfo *kdbp;
        struct kd_bufinfo *min_kdbp;
@@ -3488,38 +3790,37 @@ kdbg_read(user_addr_t buffer, size_t *number, vnode_t vp, vfs_context_t ctx, uin
        uint32_t tempbuf_number;
        uint32_t old_kdebug_flags;
        uint32_t old_kdebug_slowcheck;
-       boolean_t lostevents = FALSE;
-       boolean_t out_of_events = FALSE;
-       boolean_t wrapped = FALSE;
+       bool out_of_events = false;
+       bool wrapped = false;
 
        assert(number);
-       count = *number/sizeof(kd_buf);
+       count = *number / sizeof(kd_buf);
        *number = 0;
 
-       if (count == 0 || !(kd_ctrl_page.kdebug_flags & KDBG_BUFINIT) || kdcopybuf == 0)
+       ktrace_assert_lock_held();
+
+       if (count == 0 || !(kd_ctrl_page.kdebug_flags & KDBG_BUFINIT) || kdcopybuf == 0) {
                return EINVAL;
+       }
 
        thread_set_eager_preempt(current_thread());
 
        memset(&lostevent, 0, sizeof(lostevent));
        lostevent.debugid = TRACE_LOST_EVENTS;
 
-       /*
-        * Capture the current time. Only sort events that have occured
-        * before now.  Since the IOPs are being flushed here, it is possible
-        * that events occur on the AP while running live tracing. If we are
-        * disabled, no new events should occur on the AP.
-        */
-       if (kd_ctrl_page.enabled) {
-               barrier_max = mach_absolute_time() & KDBG_TIMESTAMP_MASK;
-       }
-
        /*
         * Request each IOP to provide us with up to date entries before merging
         * buffers together.
         */
        kdbg_iop_list_callback(kd_ctrl_page.kdebug_iops, KD_CALLBACK_SYNC_FLUSH, NULL);
 
+       /*
+        * Capture the current time.  Only sort events that have occured
+        * before now.  Since the IOPs are being flushed here, it is possible
+        * that events occur on the AP while running live tracing.
+        */
+       barrier_max = kdbg_timestamp() & KDBG_TIMESTAMP_MASK;
+
        /*
         * Disable wrap so storage units cannot be stolen out from underneath us
         * while merging events.
@@ -3532,134 +3833,188 @@ kdbg_read(user_addr_t buffer, size_t *number, vnode_t vp, vfs_context_t ctx, uin
         */
        wrapped = disable_wrap(&old_kdebug_slowcheck, &old_kdebug_flags);
 
-       if (count > nkdbufs)
+       if (count > nkdbufs) {
                count = nkdbufs;
+       }
 
        if ((tempbuf_count = count) > KDCOPYBUF_COUNT) {
                tempbuf_count = KDCOPYBUF_COUNT;
        }
 
        /*
-        * If the buffers have wrapped, capture the earliest time where there
-        * are events for all CPUs and do not emit additional lost events for
+        * If the buffers have wrapped, do not emit additional lost events for the
         * oldest storage units.
         */
        if (wrapped) {
-               barrier_min = kd_ctrl_page.oldest_time;
                kd_ctrl_page.kdebug_flags &= ~KDBG_WRAPPED;
-               kd_ctrl_page.oldest_time = 0;
 
                for (cpu = 0, kdbp = &kdbip[0]; cpu < kd_ctrl_page.kdebug_cpus; cpu++, kdbp++) {
                        if ((kdsp = kdbp->kd_list_head).raw == KDS_PTR_NULL) {
                                continue;
                        }
                        kdsp_actual = POINTER_FROM_KDS_PTR(kdsp);
-                       kdsp_actual->kds_lostevents = FALSE;
+                       kdsp_actual->kds_lostevents = false;
                }
        }
+       /*
+        * Capture the earliest time where there are events for all CPUs and don't
+        * emit events with timestamps prior.
+        */
+       barrier_min = kd_ctrl_page.oldest_time;
 
        while (count) {
                tempbuf = kdcopybuf;
                tempbuf_number = 0;
 
                if (wrapped) {
-                       /* Trace a single lost events event for wrapping. */
+                       /*
+                        * Emit a lost events tracepoint to indicate that previous events
+                        * were lost -- the thread map cannot be trusted.  A new one must
+                        * be taken so tools can analyze the trace in a backwards-facing
+                        * fashion.
+                        */
                        kdbg_set_timestamp_and_cpu(&lostevent, barrier_min, 0);
                        *tempbuf = lostevent;
-                       wrapped = FALSE;
+                       wrapped = false;
                        goto nextevent;
                }
 
                /* While space left in merged events scratch buffer. */
                while (tempbuf_count) {
+                       bool lostevents = false;
+                       int lostcpu = 0;
                        earliest_time = UINT64_MAX;
                        min_kdbp = NULL;
                        min_cpu = 0;
 
-                       /* Check each CPU's buffers. */
+                       /* Check each CPU's buffers for the earliest event. */
                        for (cpu = 0, kdbp = &kdbip[0]; cpu < kd_ctrl_page.kdebug_cpus; cpu++, kdbp++) {
-                               /* Skip CPUs without data. */
+                               /* Skip CPUs without data in their oldest storage unit. */
                                if ((kdsp = kdbp->kd_list_head).raw == KDS_PTR_NULL) {
 next_cpu:
                                        continue;
                                }
-                               /* Debugging aid: maintain a copy of the "kdsp"
-                                * index.
-                                */
-                               volatile union kds_ptr kdsp_shadow;
-
-                               kdsp_shadow = kdsp;
-
                                /* From CPU data to buffer header to buffer. */
                                kdsp_actual = POINTER_FROM_KDS_PTR(kdsp);
 
-                               volatile struct kd_storage *kdsp_actual_shadow;
-
-                               kdsp_actual_shadow = kdsp_actual;
-
-                               /* Skip buffer if there are no events left. */
+next_event:
+                               /* The next event to be read from this buffer. */
                                rcursor = kdsp_actual->kds_readlast;
 
+                               /* Skip this buffer if there are no events left. */
                                if (rcursor == kdsp_actual->kds_bufindx) {
                                        continue;
                                }
 
+                               /*
+                                * Check that this storage unit wasn't stolen and events were
+                                * lost.  This must have happened while wrapping was disabled
+                                * in this function.
+                                */
+                               if (kdsp_actual->kds_lostevents) {
+                                       lostevents = true;
+                                       kdsp_actual->kds_lostevents = false;
+
+                                       /*
+                                        * The earliest event we can trust is the first one in this
+                                        * stolen storage unit.
+                                        */
+                                       uint64_t lost_time =
+                                           kdbg_get_timestamp(&kdsp_actual->kds_records[0]);
+                                       if (kd_ctrl_page.oldest_time < lost_time) {
+                                               /*
+                                                * If this is the first time we've seen lost events for
+                                                * this gap, record its timestamp as the oldest
+                                                * timestamp we're willing to merge for the lost events
+                                                * tracepoint.
+                                                */
+                                               kd_ctrl_page.oldest_time = barrier_min = lost_time;
+                                               lostcpu = cpu;
+                                       }
+                               }
+
                                t = kdbg_get_timestamp(&kdsp_actual->kds_records[rcursor]);
 
-                               /* Ignore events that have aged out due to wrapping. */
-                               while (t < barrier_min) {
-                                       rcursor = ++kdsp_actual->kds_readlast;
+                               if (t > barrier_max) {
+                                       if (kdbg_debug) {
+                                               printf("kdebug: FUTURE EVENT: debugid %#8x: "
+                                                   "time %lld from CPU %u "
+                                                   "(barrier at time %lld, read %lu events)\n",
+                                                   kdsp_actual->kds_records[rcursor].debugid,
+                                                   t, cpu, barrier_max, *number + tempbuf_number);
+                                       }
+                                       goto next_cpu;
+                               }
+                               if (t < kdsp_actual->kds_timestamp) {
+                                       /*
+                                        * This indicates the event emitter hasn't completed
+                                        * filling in the event (becuase we're looking at the
+                                        * buffer that the record head is using).  The max barrier
+                                        * timestamp should have saved us from seeing these kinds
+                                        * of things, but other CPUs might be slow on the up-take.
+                                        *
+                                        * Bail out so we don't get out-of-order events by
+                                        * continuing to read events from other CPUs' events.
+                                        */
+                                       out_of_events = true;
+                                       break;
+                               }
+
+                               /*
+                                * Ignore events that have aged out due to wrapping or storage
+                                * unit exhaustion while merging events.
+                                */
+                               if (t < barrier_min) {
+                                       kdsp_actual->kds_readlast++;
+                                       if (kdbg_debug) {
+                                               printf("kdebug: PAST EVENT: debugid %#8x: "
+                                                   "time %lld from CPU %u "
+                                                   "(barrier at time %lld)\n",
+                                                   kdsp_actual->kds_records[rcursor].debugid,
+                                                   t, cpu, barrier_min);
+                                       }
 
-                                       if (rcursor >= EVENTS_PER_STORAGE_UNIT) {
+                                       if (kdsp_actual->kds_readlast >= EVENTS_PER_STORAGE_UNIT) {
                                                release_storage_unit(cpu, kdsp.raw);
 
                                                if ((kdsp = kdbp->kd_list_head).raw == KDS_PTR_NULL) {
                                                        goto next_cpu;
                                                }
-                                               kdsp_shadow = kdsp;
                                                kdsp_actual = POINTER_FROM_KDS_PTR(kdsp);
-                                               kdsp_actual_shadow = kdsp_actual;
-                                               rcursor = kdsp_actual->kds_readlast;
                                        }
 
-                                       t = kdbg_get_timestamp(&kdsp_actual->kds_records[rcursor]);
+                                       goto next_event;
                                }
 
-                               if ((t > barrier_max) && (barrier_max > 0)) {
-                                       /*
-                                        * Need to flush IOPs again before we
-                                        * can sort any more data from the
-                                        * buffers.
-                                        */
-                                       out_of_events = TRUE;
-                                       break;
-                               }
-                               if (t < kdsp_actual->kds_timestamp) {
-                                       /*
-                                        * indicates we've not yet completed filling
-                                        * in this event...
-                                        * this should only occur when we're looking
-                                        * at the buf that the record head is utilizing
-                                        * we'll pick these events up on the next
-                                        * call to kdbg_read
-                                        * we bail at this point so that we don't
-                                        * get an out-of-order timestream by continuing
-                                        * to read events from the other CPUs' timestream(s)
-                                        */
-                                       out_of_events = TRUE;
-                                       break;
+                               /*
+                                * Don't worry about merging any events -- just walk through
+                                * the CPUs and find the latest timestamp of lost events.
+                                */
+                               if (lostevents) {
+                                       continue;
                                }
+
                                if (t < earliest_time) {
                                        earliest_time = t;
                                        min_kdbp = kdbp;
                                        min_cpu = cpu;
                                }
                        }
-                       if (min_kdbp == NULL || out_of_events == TRUE) {
+                       if (lostevents) {
                                /*
-                                * all buffers ran empty
+                                * If any lost events were hit in the buffers, emit an event
+                                * with the latest timestamp.
                                 */
-                               out_of_events = TRUE;
+                               kdbg_set_timestamp_and_cpu(&lostevent, barrier_min, lostcpu);
+                               *tempbuf = lostevent;
+                               tempbuf->arg1 = 1;
+                               goto nextevent;
+                       }
+                       if (min_kdbp == NULL) {
+                               /* All buffers ran empty. */
+                               out_of_events = true;
+                       }
+                       if (out_of_events) {
                                break;
                        }
 
@@ -3669,36 +4024,58 @@ next_cpu:
                        /* Copy earliest event into merged events scratch buffer. */
                        *tempbuf = kdsp_actual->kds_records[kdsp_actual->kds_readlast++];
 
-                       if (kdsp_actual->kds_readlast == EVENTS_PER_STORAGE_UNIT)
+                       if (kdsp_actual->kds_readlast == EVENTS_PER_STORAGE_UNIT) {
                                release_storage_unit(min_cpu, kdsp.raw);
+                       }
 
                        /*
-                        * Watch for out of order timestamps
+                        * Watch for out of order timestamps (from IOPs).
                         */
                        if (earliest_time < min_kdbp->kd_prev_timebase) {
                                /*
-                                * if so, use the previous timestamp + 1 cycle
+                                * If we haven't already, emit a retrograde events event.
+                                * Otherwise, ignore this event.
                                 */
-                               min_kdbp->kd_prev_timebase++;
+                               if (traced_retrograde) {
+                                       continue;
+                               }
+
                                kdbg_set_timestamp_and_cpu(tempbuf, min_kdbp->kd_prev_timebase, kdbg_get_cpu(tempbuf));
-                       } else
+                               tempbuf->arg1 = tempbuf->debugid;
+                               tempbuf->arg2 = earliest_time;
+                               tempbuf->arg3 = 0;
+                               tempbuf->arg4 = 0;
+                               tempbuf->debugid = TRACE_RETROGRADE_EVENTS;
+                               traced_retrograde = true;
+                       } else {
                                min_kdbp->kd_prev_timebase = earliest_time;
+                       }
 nextevent:
                        tempbuf_count--;
                        tempbuf_number++;
                        tempbuf++;
 
-                       if ((RAW_file_written += sizeof(kd_buf)) >= RAW_FLUSH_SIZE)
+                       if ((RAW_file_written += sizeof(kd_buf)) >= RAW_FLUSH_SIZE) {
                                break;
+                       }
                }
                if (tempbuf_number) {
+                       /*
+                        * Remember the latest timestamp of events that we've merged so we
+                        * don't think we've lost events later.
+                        */
+                       uint64_t latest_time = kdbg_get_timestamp(tempbuf - 1);
+                       if (kd_ctrl_page.oldest_time < latest_time) {
+                               kd_ctrl_page.oldest_time = latest_time;
+                       }
                        if (file_version == RAW_VERSION3) {
-                               if ( !(kdbg_write_v3_event_chunk_header(buffer, V3_RAW_EVENTS, (tempbuf_number * sizeof(kd_buf)), vp, ctx))) {
+                               if (!(kdbg_write_v3_event_chunk_header(buffer, V3_RAW_EVENTS, (tempbuf_number * sizeof(kd_buf)), vp, ctx))) {
                                        error = EFAULT;
                                        goto check_error;
                                }
-                               if (buffer)
+                               if (buffer) {
                                        buffer += (sizeof(kd_chunk_header_v3) + sizeof(uint64_t));
+                               }
 
                                assert(count >= (sizeof(kd_chunk_header_v3) + sizeof(uint64_t)));
                                count -= (sizeof(kd_chunk_header_v3) + sizeof(uint64_t));
@@ -3707,11 +4084,12 @@ nextevent:
                        if (vp) {
                                size_t write_size = tempbuf_number * sizeof(kd_buf);
                                error = kdbg_write_to_vnode((caddr_t)kdcopybuf, write_size, vp, ctx, RAW_file_offset);
-                               if (!error)
+                               if (!error) {
                                        RAW_file_offset += write_size;
-       
+                               }
+
                                if (RAW_file_written >= RAW_FLUSH_SIZE) {
-                                       cluster_push(vp, 0);
+                                       error = VNOP_FSYNC(vp, MNT_NOWAIT, ctx);
 
                                        RAW_file_written = 0;
                                }
@@ -3728,62 +4106,135 @@ check_error:
                        count   -= tempbuf_number;
                        *number += tempbuf_number;
                }
-               if (out_of_events == TRUE)
-                      /*
-                       * all trace buffers are empty
-                       */
-                       break;
+               if (out_of_events == true) {
+                       /*
+                        * all trace buffers are empty
+                        */
+                       break;
+               }
 
-               if ((tempbuf_count = count) > KDCOPYBUF_COUNT)
-                       tempbuf_count = KDCOPYBUF_COUNT;
+               if ((tempbuf_count = count) > KDCOPYBUF_COUNT) {
+                       tempbuf_count = KDCOPYBUF_COUNT;
+               }
        }
-       if ( !(old_kdebug_flags & KDBG_NOWRAP)) {
-               enable_wrap(old_kdebug_slowcheck, lostevents);
+       if (!(old_kdebug_flags & KDBG_NOWRAP)) {
+               enable_wrap(old_kdebug_slowcheck);
        }
        thread_clear_eager_preempt(current_thread());
-       return (error);
+       return error;
+}
+
+#define KDEBUG_TEST_CODE(code) BSDDBG_CODE(DBG_BSD_KDEBUG_TEST, (code))
+
+/*
+ * A test IOP for the SYNC_FLUSH callback.
+ */
+
+static int sync_flush_iop = 0;
+
+static void
+sync_flush_callback(void * __unused context, kd_callback_type reason,
+    void * __unused arg)
+{
+       assert(sync_flush_iop > 0);
+
+       if (reason == KD_CALLBACK_SYNC_FLUSH) {
+               kernel_debug_enter(sync_flush_iop, KDEBUG_TEST_CODE(0xff),
+                   kdbg_timestamp(), 0, 0, 0, 0, 0);
+       }
 }
 
+static struct kd_callback sync_flush_kdcb = {
+       .func = sync_flush_callback,
+       .iop_name = "test_sf",
+};
+
 static int
-kdbg_test(void)
+kdbg_test(size_t flavor)
 {
-#define KDEBUG_TEST_CODE(code) BSDDBG_CODE(DBG_BSD_KDEBUG_TEST, (code))
        int code = 0;
+       int dummy_iop = 0;
+
+       switch (flavor) {
+       case 1:
+               /* try each macro */
+               KDBG(KDEBUG_TEST_CODE(code)); code++;
+               KDBG(KDEBUG_TEST_CODE(code), 1); code++;
+               KDBG(KDEBUG_TEST_CODE(code), 1, 2); code++;
+               KDBG(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
+               KDBG(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
+
+               KDBG_RELEASE(KDEBUG_TEST_CODE(code)); code++;
+               KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1); code++;
+               KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1, 2); code++;
+               KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
+               KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
+
+               KDBG_FILTERED(KDEBUG_TEST_CODE(code)); code++;
+               KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1); code++;
+               KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1, 2); code++;
+               KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
+               KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
+
+               KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code)); code++;
+               KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code), 1); code++;
+               KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code), 1, 2); code++;
+               KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
+               KDBG_RELEASE_NOPROCFILT(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
+
+               KDBG_DEBUG(KDEBUG_TEST_CODE(code)); code++;
+               KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1); code++;
+               KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1, 2); code++;
+               KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
+               KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
+               break;
 
-       KDBG(KDEBUG_TEST_CODE(code)); code++;
-       KDBG(KDEBUG_TEST_CODE(code), 1); code++;
-       KDBG(KDEBUG_TEST_CODE(code), 1, 2); code++;
-       KDBG(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
-       KDBG(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
-
-       KDBG_RELEASE(KDEBUG_TEST_CODE(code)); code++;
-       KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1); code++;
-       KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1, 2); code++;
-       KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
-       KDBG_RELEASE(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
-
-       KDBG_FILTERED(KDEBUG_TEST_CODE(code)); code++;
-       KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1); code++;
-       KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1, 2); code++;
-       KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
-       KDBG_FILTERED(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
-
-       KDBG_DEBUG(KDEBUG_TEST_CODE(code)); code++;
-       KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1); code++;
-       KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1, 2); code++;
-       KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1, 2, 3); code++;
-       KDBG_DEBUG(KDEBUG_TEST_CODE(code), 1, 2, 3, 4); code++;
+       case 2:
+               if (kd_ctrl_page.kdebug_iops) {
+                       /* avoid the assertion in kernel_debug_enter for a valid IOP */
+                       dummy_iop = kd_ctrl_page.kdebug_iops[0].cpu_id;
+               }
+
+               /* ensure old timestamps are not emitted from kernel_debug_enter */
+               kernel_debug_enter(dummy_iop, KDEBUG_TEST_CODE(code),
+                   100 /* very old timestamp */, 0, 0, 0, 0, 0);
+               code++;
+               kernel_debug_enter(dummy_iop, KDEBUG_TEST_CODE(code),
+                   kdbg_timestamp(), 0, 0, 0, 0, 0);
+               code++;
+               break;
+
+       case 3:
+               if (kd_ctrl_page.kdebug_iops) {
+                       dummy_iop = kd_ctrl_page.kdebug_iops[0].cpu_id;
+               }
+               kernel_debug_enter(dummy_iop, KDEBUG_TEST_CODE(code),
+                   kdbg_timestamp() * 2 /* !!! */, 0, 0, 0, 0, 0);
+               break;
+
+       case 4:
+               if (!sync_flush_iop) {
+                       sync_flush_iop = kernel_debug_register_callback(
+                               sync_flush_kdcb);
+                       assert(sync_flush_iop > 0);
+               }
+               break;
+
+       default:
+               return ENOTSUP;
+       }
 
        return 0;
-#undef KDEBUG_TEST_CODE
 }
 
+#undef KDEBUG_TEST_CODE
+
 void
-kdebug_boot_trace(unsigned int n_events, char *filter_desc)
+kdebug_init(unsigned int n_events, char *filter_desc, bool wrapping)
 {
        assert(filter_desc != NULL);
 
-#if (defined(__i386__) || defined(__x86_64__))
+#if defined(__x86_64__)
        /* only trace MACH events when outputting kdebug to serial */
        if (kdebug_serial) {
                n_events = 1;
@@ -3793,13 +4244,13 @@ kdebug_boot_trace(unsigned int n_events, char *filter_desc)
                        filter_desc[2] = '\0';
                }
        }
-#endif
+#endif /* defined(__x86_64__) */
 
        if (log_leaks && n_events == 0) {
                n_events = 200000;
        }
 
-       kdebug_trace_start(n_events, filter_desc, FALSE);
+       kdebug_trace_start(n_events, filter_desc, wrapping, false);
 }
 
 static void
@@ -3807,7 +4258,7 @@ kdbg_set_typefilter_string(const char *filter_desc)
 {
        char *end = NULL;
 
-       lck_mtx_assert(ktrace_lock, LCK_MTX_ASSERT_OWNED);
+       ktrace_assert_lock_held();
 
        assert(filter_desc != NULL);
 
@@ -3815,7 +4266,7 @@ kdbg_set_typefilter_string(const char *filter_desc)
        typefilter_allow_class(kdbg_typefilter, DBG_TRACE);
 
        /* if the filter description starts with a number, assume it's a csc */
-       if (filter_desc[0] >= '0' && filter_desc[0] <= '9'){
+       if (filter_desc[0] >= '0' && filter_desc[0] <= '9') {
                unsigned long csc = strtoul(filter_desc, NULL, 0);
                if (filter_desc != end && csc <= KDBG_CSC_MAX) {
                        typefilter_allow_csc(kdbg_typefilter, csc);
@@ -3839,24 +4290,24 @@ kdbg_set_typefilter_string(const char *filter_desc)
                }
 
                switch (filter_type) {
-                       case 'C':
-                               if (allow_value <= KDBG_CLASS_MAX) {
-                                       typefilter_allow_class(kdbg_typefilter, allow_value);
-                               } else {
-                                       /* illegal class */
-                                       return;
-                               }
-                               break;
-                       case 'S':
-                               if (allow_value <= KDBG_CSC_MAX) {
-                                       typefilter_allow_csc(kdbg_typefilter, allow_value);
-                               } else {
-                                       /* illegal class subclass */
-                                       return;
-                               }
-                               break;
-                       default:
+               case 'C':
+                       if (allow_value <= KDBG_CLASS_MAX) {
+                               typefilter_allow_class(kdbg_typefilter, allow_value);
+                       } else {
+                               /* illegal class */
                                return;
+                       }
+                       break;
+               case 'S':
+                       if (allow_value <= KDBG_CSC_MAX) {
+                               typefilter_allow_csc(kdbg_typefilter, allow_value);
+                       } else {
+                               /* illegal class subclass */
+                               return;
+                       }
+                       break;
+               default:
+                       return;
                }
 
                /* advance to next filter entry */
@@ -3873,15 +4324,14 @@ kdbg_set_typefilter_string(const char *filter_desc)
  */
 void
 kdebug_trace_start(unsigned int n_events, const char *filter_desc,
-                   boolean_t need_map)
+    bool wrapping, bool at_wake)
 {
-       uint32_t old1, old2;
-
        if (!n_events) {
+               kd_early_done = true;
                return;
        }
 
-       lck_mtx_lock(ktrace_lock);
+       ktrace_start_single_threaded();
 
        kdbg_lock_init();
 
@@ -3891,7 +4341,7 @@ kdebug_trace_start(unsigned int n_events, const char *filter_desc,
 
        kernel_debug_string_early("start_kern_tracing");
 
-       if (kdbg_reinit(TRUE)) {
+       if (kdbg_reinit(true)) {
                printf("error from kdbg_reinit, kernel tracing not started\n");
                goto out;
        }
@@ -3900,7 +4350,10 @@ kdebug_trace_start(unsigned int n_events, const char *filter_desc,
         * Wrapping is disabled because boot and wake tracing is interested in
         * the earliest events, at the expense of later ones.
         */
-       (void)disable_wrap(&old1, &old2);
+       if (!wrapping) {
+               uint32_t old1, old2;
+               (void)disable_wrap(&old1, &old2);
+       }
 
        if (filter_desc && filter_desc[0] != '\0') {
                if (kdbg_initialize_typefilter(NULL) == KERN_SUCCESS) {
@@ -3913,21 +4366,22 @@ kdebug_trace_start(unsigned int n_events, const char *filter_desc,
         * Hold off interrupts between getting a thread map and enabling trace
         * and until the early traces are recorded.
         */
-       boolean_t s = ml_set_interrupts_enabled(FALSE);
+       bool s = ml_set_interrupts_enabled(false);
 
-       if (need_map == TRUE) {
+       if (at_wake) {
                kdbg_thrmap_init();
        }
 
-       kdbg_set_tracing_enabled(TRUE, kdebug_serial ?
-                                (KDEBUG_ENABLE_TRACE | KDEBUG_ENABLE_SERIAL) :
-                                KDEBUG_ENABLE_TRACE);
+       kdbg_set_tracing_enabled(true, KDEBUG_ENABLE_TRACE | (kdebug_serial ?
+           KDEBUG_ENABLE_SERIAL : 0));
 
-       /*
-        * Transfer all very early events from the static buffer into the real
-        * buffers.
-        */
-       kernel_debug_early_end();
+       if (!at_wake) {
+               /*
+                * Transfer all very early events from the static buffer into the real
+                * buffers.
+                */
+               kernel_debug_early_end();
+       }
 
        ml_set_interrupts_enabled(s);
 
@@ -3936,12 +4390,12 @@ kdebug_trace_start(unsigned int n_events, const char *filter_desc,
 #if KDEBUG_MOJO_TRACE
        if (kdebug_serial) {
                printf("serial output enabled with %lu named events\n",
-               sizeof(kd_events)/sizeof(kd_event_t));
+                   sizeof(kd_events) / sizeof(kd_event_t));
        }
-#endif
+#endif /* KDEBUG_MOJO_TRACE */
 
 out:
-       lck_mtx_unlock(ktrace_lock);
+       ktrace_end_single_threaded();
 }
 
 void
@@ -3950,8 +4404,9 @@ kdbg_dump_trace_to_file(const char *filename)
        vfs_context_t ctx;
        vnode_t vp;
        size_t write_size;
+       int ret;
 
-       lck_mtx_lock(ktrace_lock);
+       ktrace_lock();
 
        if (!(kdebug_enable & KDEBUG_ENABLE_TRACE)) {
                goto out;
@@ -3960,7 +4415,7 @@ kdbg_dump_trace_to_file(const char *filename)
        if (ktrace_get_owning_pid() != 0) {
                /*
                 * Another process owns ktrace and is still active, disable tracing to
-                * capture whatever was being recorded.
+                * prevent wrapping.
                 */
                kdebug_enable = 0;
                kd_ctrl_page.enabled = 0;
@@ -3968,7 +4423,7 @@ kdbg_dump_trace_to_file(const char *filename)
                goto out;
        }
 
-       KERNEL_DEBUG_CONSTANT(TRACE_PANIC | DBG_FUNC_NONE, 0, 0, 0, 0, 0);
+       KDBG_RELEASE(TRACE_WRITING_EVENTS | DBG_FUNC_START);
 
        kdebug_enable = 0;
        kd_ctrl_page.enabled = 0;
@@ -3983,36 +4438,73 @@ kdbg_dump_trace_to_file(const char *filename)
        kdbg_write_thread_map(vp, ctx);
 
        write_size = nkdbufs * sizeof(kd_buf);
-       kdbg_read(0, &write_size, vp, ctx, RAW_VERSION1);
+       ret = kdbg_read(0, &write_size, vp, ctx, RAW_VERSION1);
+       if (ret) {
+               goto out_close;
+       }
+
+       /*
+        * Wait to synchronize the file to capture the I/O in the
+        * TRACE_WRITING_EVENTS interval.
+        */
+       ret = VNOP_FSYNC(vp, MNT_WAIT, ctx);
+
+       /*
+        * Balance the starting TRACE_WRITING_EVENTS tracepoint manually.
+        */
+       kd_buf end_event = {
+               .debugid = TRACE_WRITING_EVENTS | DBG_FUNC_END,
+               .arg1 = write_size,
+               .arg2 = ret,
+               .arg5 = thread_tid(current_thread()),
+       };
+       kdbg_set_timestamp_and_cpu(&end_event, kdbg_timestamp(),
+           cpu_number());
 
+       /* this is best effort -- ignore any errors */
+       (void)kdbg_write_to_vnode((caddr_t)&end_event, sizeof(kd_buf), vp, ctx,
+           RAW_file_offset);
+
+out_close:
        vnode_close(vp, FWRITE, ctx);
        sync(current_proc(), (void *)NULL, (int *)NULL);
 
 out:
-       lck_mtx_unlock(ktrace_lock);
+       ktrace_unlock();
 }
 
-/* Helper function for filling in the BSD name for an address space
- * Defined here because the machine bindings know only Mach threads
- * and nothing about BSD processes.
- *
- * FIXME: need to grab a lock during this?
- */
-void kdbg_get_task_name(char* name_buf, int len, task_t task)
+static int
+kdbg_sysctl_continuous SYSCTL_HANDLER_ARGS
 {
-       proc_t proc;
-       
-       /* Note: we can't use thread->task (and functions that rely on it) here 
-        * because it hasn't been initialized yet when this function is called.
-        * We use the explicitly-passed task parameter instead.
-        */
-       proc = get_bsdtask_info(task);
-       if (proc != PROC_NULL)
-               snprintf(name_buf, len, "%s/%d", proc->p_comm, proc->p_pid);
-       else
-               snprintf(name_buf, len, "%p [!bsd]", task);
+#pragma unused(oidp, arg1, arg2)
+       int value = kdbg_continuous_time;
+       int ret = sysctl_io_number(req, value, sizeof(value), &value, NULL);
+
+       if (ret || !req->newptr) {
+               return ret;
+       }
+
+       kdbg_continuous_time = value;
+       return 0;
 }
 
+SYSCTL_NODE(_kern, OID_AUTO, kdbg, CTLFLAG_RD | CTLFLAG_LOCKED, 0,
+    "kdbg");
+
+SYSCTL_PROC(_kern_kdbg, OID_AUTO, experimental_continuous,
+    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, 0,
+    sizeof(int), kdbg_sysctl_continuous, "I",
+    "Set kdebug to use mach_continuous_time");
+
+SYSCTL_INT(_kern_kdbg, OID_AUTO, debug,
+    CTLFLAG_RW | CTLFLAG_LOCKED,
+    &kdbg_debug, 0, "Set kdebug debug mode");
+
+SYSCTL_QUAD(_kern_kdbg, OID_AUTO, oldest_time,
+    CTLTYPE_QUAD | CTLFLAG_RD | CTLFLAG_LOCKED,
+    &kd_ctrl_page.oldest_time,
+    "Find the oldest timestamp still in trace");
+
 #if KDEBUG_MOJO_TRACE
 static kd_event_t *
 binary_search(uint32_t id)
@@ -4020,28 +4512,28 @@ binary_search(uint32_t id)
        int low, high, mid;
 
        low = 0;
-       high = sizeof(kd_events)/sizeof(kd_event_t) - 1;
+       high = (int)(sizeof(kd_events) / sizeof(kd_event_t)) - 1;
 
-       while (TRUE)
-       {
+       while (true) {
                mid = (low + high) / 2;
 
-               if (low > high)
+               if (low > high) {
                        return NULL; /* failed */
-               else if ( low + 1 >= high) {
+               } else if (low + 1 >= high) {
                        /* We have a match */
-                       if (kd_events[high].id == id)
+                       if (kd_events[high].id == id) {
                                return &kd_events[high];
-                       else if (kd_events[low].id == id)
+                       } else if (kd_events[low].id == id) {
                                return &kd_events[low];
-                       else
+                       } else {
                                return NULL;  /* search failed */
-               }
-               else if (id < kd_events[mid].id)
+                       }
+               } else if (id < kd_events[mid].id) {
                        high = mid;
-               else
+               } else {
                        low = mid;
-       } 
+               }
+       }
 }
 
 /*
@@ -4049,47 +4541,48 @@ binary_search(uint32_t id)
  * Using a per-cpu cache of a single entry
  * before resorting to a binary search of the full table.
  */
-#define        NCACHE  1
-static kd_event_t      *last_hit[MAX_CPUS];
+#define NCACHE  1
+static kd_event_t       *last_hit[MAX_CPUS];
 static kd_event_t *
 event_lookup_cache(uint32_t cpu, uint32_t id)
 {
-       if (last_hit[cpu] == NULL || last_hit[cpu]->id != id)
+       if (last_hit[cpu] == NULL || last_hit[cpu]->id != id) {
                last_hit[cpu] = binary_search(id);
+       }
        return last_hit[cpu];
 }
 
-static uint64_t        kd_last_timstamp;
+static uint64_t kd_last_timstamp;
 
 static void
 kdebug_serial_print(
-       uint32_t        cpunum,
-       uint32_t        debugid,
-       uint64_t        timestamp,
-       uintptr_t       arg1,
-       uintptr_t       arg2,
-       uintptr_t       arg3,
-       uintptr_t       arg4,
-       uintptr_t       threadid
+       uint32_t        cpunum,
+       uint32_t        debugid,
+       uint64_t        timestamp,
+       uintptr_t       arg1,
+       uintptr_t       arg2,
+       uintptr_t       arg3,
+       uintptr_t       arg4,
+       uintptr_t       threadid
        )
 {
-       char            kprintf_line[192];
-       char            event[40];
-       uint64_t        us = timestamp / NSEC_PER_USEC;
-       uint64_t        us_tenth = (timestamp % NSEC_PER_USEC) / 100;
-       uint64_t        delta = timestamp - kd_last_timstamp;
-       uint64_t        delta_us = delta / NSEC_PER_USEC;
-       uint64_t        delta_us_tenth = (delta % NSEC_PER_USEC) / 100;
-       uint32_t        event_id = debugid & KDBG_EVENTID_MASK;
-       const char      *command;
-       const char      *bra;
-       const char      *ket;
-       kd_event_t      *ep;
+       char            kprintf_line[192];
+       char            event[40];
+       uint64_t        us = timestamp / NSEC_PER_USEC;
+       uint64_t        us_tenth = (timestamp % NSEC_PER_USEC) / 100;
+       uint64_t        delta = timestamp - kd_last_timstamp;
+       uint64_t        delta_us = delta / NSEC_PER_USEC;
+       uint64_t        delta_us_tenth = (delta % NSEC_PER_USEC) / 100;
+       uint32_t        event_id = debugid & KDBG_EVENTID_MASK;
+       const char      *command;
+       const char      *bra;
+       const char      *ket;
+       kd_event_t      *ep;
 
        /* event time and delta from last */
        snprintf(kprintf_line, sizeof(kprintf_line),
-               "%11llu.%1llu %8llu.%1llu ",
-               us, us_tenth, delta_us, delta_us_tenth);
+           "%11llu.%1llu %8llu.%1llu ",
+           us, us_tenth, delta_us, delta_us_tenth);
 
 
        /* event (id or name) - start prefixed by "[", end postfixed by "]" */
@@ -4097,60 +4590,62 @@ kdebug_serial_print(
        ket = (debugid & DBG_FUNC_END)   ? "]" : " ";
        ep = event_lookup_cache(cpunum, event_id);
        if (ep) {
-               if (strlen(ep->name) < sizeof(event) - 3)
+               if (strlen(ep->name) < sizeof(event) - 3) {
                        snprintf(event, sizeof(event), "%s%s%s",
-                                bra, ep->name, ket);
-               else
+                           bra, ep->name, ket);
+               } else {
                        snprintf(event, sizeof(event), "%s%x(name too long)%s",
-                                bra, event_id, ket);
+                           bra, event_id, ket);
+               }
        } else {
                snprintf(event, sizeof(event), "%s%x%s",
-                        bra, event_id, ket);
+                   bra, event_id, ket);
        }
        snprintf(kprintf_line + strlen(kprintf_line),
-                sizeof(kprintf_line) - strlen(kprintf_line),
-                "%-40s  ", event);
+           sizeof(kprintf_line) - strlen(kprintf_line),
+           "%-40s  ", event);
 
        /* arg1 .. arg4 with special cases for strings */
        switch (event_id) {
-           case VFS_LOOKUP:
-           case VFS_LOOKUP_DONE:
+       case VFS_LOOKUP:
+       case VFS_LOOKUP_DONE:
                if (debugid & DBG_FUNC_START) {
                        /* arg1 hex then arg2..arg4 chars */
                        snprintf(kprintf_line + strlen(kprintf_line),
-                               sizeof(kprintf_line) - strlen(kprintf_line),
-                               "%-16lx %-8s%-8s%-8s                          ",
-                               arg1, (char*)&arg2, (char*)&arg3, (char*)&arg4);
+                           sizeof(kprintf_line) - strlen(kprintf_line),
+                           "%-16lx %-8s%-8s%-8s                          ",
+                           arg1, (char*)&arg2, (char*)&arg3, (char*)&arg4);
                        break;
                }
-               /* else fall through for arg1..arg4 chars */
-           case TRACE_STRING_EXEC:
-           case TRACE_STRING_NEWTHREAD:
-           case TRACE_INFO_STRING:
+       /* else fall through for arg1..arg4 chars */
+       case TRACE_STRING_EXEC:
+       case TRACE_STRING_NEWTHREAD:
+       case TRACE_INFO_STRING:
                snprintf(kprintf_line + strlen(kprintf_line),
-                       sizeof(kprintf_line) - strlen(kprintf_line),
-                       "%-8s%-8s%-8s%-8s                                   ",
-                       (char*)&arg1, (char*)&arg2, (char*)&arg3, (char*)&arg4);
+                   sizeof(kprintf_line) - strlen(kprintf_line),
+                   "%-8s%-8s%-8s%-8s                                   ",
+                   (char*)&arg1, (char*)&arg2, (char*)&arg3, (char*)&arg4);
                break;
-           default:
+       default:
                snprintf(kprintf_line + strlen(kprintf_line),
-                       sizeof(kprintf_line) - strlen(kprintf_line),
-                       "%-16lx %-16lx %-16lx %-16lx",
-                       arg1, arg2, arg3, arg4);
+                   sizeof(kprintf_line) - strlen(kprintf_line),
+                   "%-16lx %-16lx %-16lx %-16lx",
+                   arg1, arg2, arg3, arg4);
        }
 
        /* threadid, cpu and command name */
        if (threadid == (uintptr_t)thread_tid(current_thread()) &&
            current_proc() &&
-           current_proc()->p_comm[0])
+           current_proc()->p_comm[0]) {
                command = current_proc()->p_comm;
-       else
+       } else {
                command = "-";
+       }
        snprintf(kprintf_line + strlen(kprintf_line),
-               sizeof(kprintf_line) - strlen(kprintf_line),
-               "  %-16lx  %-2d %s\n",
-               threadid, cpunum, command);
-       
+           sizeof(kprintf_line) - strlen(kprintf_line),
+           "  %-16lx  %-2d %s\n",
+           threadid, cpunum, command);
+
        kprintf("%s", kprintf_line);
        kd_last_timstamp = timestamp;
 }