xref: /xnu-8019.80.24/libkern/os/log.c (revision a325d9c4a84054e40bbe985afedcb50ab80993ea)
1 /* * Copyright (c) 2019 Apple Inc. All rights reserved. */
2 
3 #include <stddef.h>
4 #undef offset
5 
6 #include <kern/cpu_data.h>
7 #include <os/base.h>
8 #include <os/object.h>
9 #include <os/log.h>
10 #include <stdbool.h>
11 #include <stdint.h>
12 
13 #include <vm/vm_kern.h>
14 #include <mach/vm_statistics.h>
15 #include <kern/debug.h>
16 #include <libkern/libkern.h>
17 #include <libkern/kernel_mach_header.h>
18 #include <pexpert/pexpert.h>
19 #include <uuid/uuid.h>
20 #include <sys/msgbuf.h>
21 
22 #include <mach/mach_time.h>
23 #include <kern/thread.h>
24 #include <kern/simple_lock.h>
25 #include <kern/kalloc.h>
26 #include <kern/clock.h>
27 #include <kern/assert.h>
28 #include <kern/startup.h>
29 #include <kern/task.h>
30 
31 #include <firehose/tracepoint_private.h>
32 #include <firehose/chunk_private.h>
33 #include <os/firehose_buffer_private.h>
34 #include <os/firehose.h>
35 
36 #include <os/log_private.h>
37 #include "trace_internal.h"
38 
39 #include "log_encode.h"
40 #include "log_internal.h"
41 #include "log_mem.h"
42 #include "log_queue.h"
43 
44 #define OS_LOGMEM_BUF_ORDER 14
45 #define OS_LOGMEM_MIN_LOG_ORDER 9
46 #define OS_LOGMEM_MAX_LOG_ORDER 10
47 
48 struct os_log_s {
49 	int a;
50 };
51 
52 struct os_log_s _os_log_default;
53 struct os_log_s _os_log_replay;
54 struct logmem_s os_log_mem;
55 
56 extern vm_offset_t kernel_firehose_addr;
57 extern firehose_chunk_t firehose_boot_chunk;
58 
59 extern bool bsd_log_lock(bool);
60 extern void bsd_log_unlock(void);
61 extern void logwakeup(struct msgbuf *);
62 
63 extern void oslog_stream(bool, firehose_tracepoint_id_u, uint64_t, const void *, size_t);
64 extern void *OSKextKextForAddress(const void *);
65 
66 /* Counters for persistence mode */
67 SCALABLE_COUNTER_DEFINE(oslog_p_total_msgcount);
68 SCALABLE_COUNTER_DEFINE(oslog_p_metadata_saved_msgcount);
69 SCALABLE_COUNTER_DEFINE(oslog_p_metadata_dropped_msgcount);
70 SCALABLE_COUNTER_DEFINE(oslog_p_error_count);
71 SCALABLE_COUNTER_DEFINE(oslog_p_saved_msgcount);
72 SCALABLE_COUNTER_DEFINE(oslog_p_dropped_msgcount);
73 SCALABLE_COUNTER_DEFINE(oslog_p_boot_dropped_msgcount);
74 SCALABLE_COUNTER_DEFINE(oslog_p_coprocessor_total_msgcount);
75 SCALABLE_COUNTER_DEFINE(oslog_p_coprocessor_dropped_msgcount);
76 SCALABLE_COUNTER_DEFINE(oslog_p_unresolved_kc_msgcount);
77 
78 /* Counters for msgbuf logging */
79 SCALABLE_COUNTER_DEFINE(oslog_msgbuf_msgcount)
80 SCALABLE_COUNTER_DEFINE(oslog_msgbuf_dropped_msgcount)
81 
82 static bool oslog_boot_done = false;
83 static bool oslog_disabled = false;
84 
85 #ifdef XNU_KERNEL_PRIVATE
86 bool startup_serial_logging_active = true;
87 uint64_t startup_serial_num_procs = 300;
88 #endif /* XNU_KERNEL_PRIVATE */
89 
90 bool os_log_disabled(void);
91 
92 static void
93 _os_log_with_args_internal(os_log_t oslog __unused, os_log_type_t type __unused,
94     const char *format, va_list args, void *addr, void *dso, bool driverKit, bool addcr);
95 
96 static void
97 _os_log_to_msgbuf_internal(const char *format, va_list args, bool safe, bool logging, bool addcr);
98 
99 static void
100 _os_log_to_log_internal(os_log_type_t type, const char *format, va_list args, void *addr, void *dso, bool driverKit);
101 
102 __startup_func
103 static void
oslog_init(void)104 oslog_init(void)
105 {
106 	/*
107 	 * Disable kernel logging if ATM_TRACE_DISABLE set. ATM_TRACE_DISABLE
108 	 * bit is not supposed to change during a system run but nothing really
109 	 * prevents userspace from unintentionally doing so => we stash initial
110 	 * value in a dedicated variable for a later reference, just in case.
111 	 */
112 	oslog_disabled = atm_get_diagnostic_config() & ATM_TRACE_DISABLE;
113 }
114 STARTUP(OSLOG, STARTUP_RANK_FIRST, oslog_init);
115 
116 __startup_func
117 static void
oslog_init_logmem(void)118 oslog_init_logmem(void)
119 {
120 	if (os_log_disabled()) {
121 		printf("Long logs support disabled: Logging disabled by ATM\n");
122 		return;
123 	}
124 
125 	const size_t logmem_size = logmem_required_size(OS_LOGMEM_BUF_ORDER, OS_LOGMEM_MIN_LOG_ORDER);
126 	vm_offset_t addr;
127 
128 	if (kmem_alloc(kernel_map, &addr, logmem_size, VM_KERN_MEMORY_LOG) == KERN_SUCCESS) {
129 		logmem_init(&os_log_mem, (void *)addr, logmem_size,
130 		    OS_LOGMEM_BUF_ORDER, OS_LOGMEM_MIN_LOG_ORDER, OS_LOGMEM_MAX_LOG_ORDER);
131 		printf("Long logs support configured: size: %u\n", os_log_mem.lm_cnt_free);
132 	} else {
133 		printf("Long logs support disabled: Not enough memory\n");
134 	}
135 }
136 STARTUP(OSLOG, STARTUP_RANK_SECOND, oslog_init_logmem);
137 
138 static bool
os_log_safe(void)139 os_log_safe(void)
140 {
141 	return oslog_is_safe() || startup_phase < STARTUP_SUB_EARLY_BOOT;
142 }
143 
144 static bool
os_log_turned_off(void)145 os_log_turned_off(void)
146 {
147 	return oslog_disabled || (atm_get_diagnostic_config() & ATM_TRACE_OFF);
148 }
149 
150 bool
os_log_info_enabled(os_log_t log __unused)151 os_log_info_enabled(os_log_t log __unused)
152 {
153 	return !os_log_turned_off();
154 }
155 
156 bool
os_log_debug_enabled(os_log_t log __unused)157 os_log_debug_enabled(os_log_t log __unused)
158 {
159 	return !os_log_turned_off();
160 }
161 
162 bool
os_log_disabled(void)163 os_log_disabled(void)
164 {
165 	return oslog_disabled;
166 }
167 
168 os_log_t
os_log_create(const char * subsystem __unused,const char * category __unused)169 os_log_create(const char *subsystem __unused, const char *category __unused)
170 {
171 	return &_os_log_default;
172 }
173 
174 __attribute__((noinline, not_tail_called)) void
_os_log_internal(void * dso,os_log_t log,uint8_t type,const char * message,...)175 _os_log_internal(void *dso, os_log_t log, uint8_t type, const char *message, ...)
176 {
177 	va_list args;
178 	void *addr = __builtin_return_address(0);
179 
180 	va_start(args, message);
181 
182 	_os_log_with_args_internal(log, type, message, args, addr, dso, FALSE, FALSE);
183 
184 	va_end(args);
185 
186 	return;
187 }
188 
189 __attribute__((noinline, not_tail_called)) int
_os_log_internal_driverKit(void * dso,os_log_t log,uint8_t type,const char * message,...)190 _os_log_internal_driverKit(void *dso, os_log_t log, uint8_t type, const char *message, ...)
191 {
192 	va_list args;
193 	void *addr = __builtin_return_address(0);
194 	bool driverKitLog = FALSE;
195 
196 	/*
197 	 * We want to be able to identify dexts from the logs.
198 	 *
199 	 * Usually the addr is used to understand if the log line
200 	 * was generated by a kext or the kernel main executable.
201 	 * Logd uses copyKextUUIDForAddress with the addr specified
202 	 * in the log line to retrieve the kext UUID of the sender.
203 	 *
204 	 * Dext however are not loaded in kernel space so they do not
205 	 * have a kernel range of addresses.
206 	 *
207 	 * To make the same mechanism work, OSKext fakes a kernel
208 	 * address range for dexts using the loadTag,
209 	 * so we just need to use the loadTag as addr here
210 	 * to allow logd to retrieve the correct UUID.
211 	 *
212 	 * NOTE: loadTag is populated in the task when the dext is matching,
213 	 * so if log lines are generated before the matching they will be
214 	 * identified as kernel main executable.
215 	 */
216 	task_t self_task = current_task();
217 
218 	/*
219 	 * Only dextis are supposed to use this log path. Verified in log_data()
220 	 * but worth of another check here in case this function gets called
221 	 * directly.
222 	 */
223 	if (!task_is_driver(self_task)) {
224 		return EPERM;
225 	}
226 
227 	uint64_t loadTag = get_task_loadTag(self_task);
228 	if (loadTag != 0) {
229 		driverKitLog = TRUE;
230 		addr = (void*) loadTag;
231 	}
232 	va_start(args, message);
233 
234 	_os_log_with_args_internal(log, type, message, args, addr, dso, driverKitLog, true);
235 
236 	va_end(args);
237 
238 	return 0;
239 }
240 
241 #pragma mark - shim functions
242 
243 __attribute__((noinline, not_tail_called)) void
os_log_with_args(os_log_t oslog,os_log_type_t type,const char * format,va_list args,void * addr)244 os_log_with_args(os_log_t oslog, os_log_type_t type, const char *format, va_list args, void *addr)
245 {
246 	// if no address passed, look it up
247 	if (addr == NULL) {
248 		addr = __builtin_return_address(0);
249 	}
250 
251 	_os_log_with_args_internal(oslog, type, format, args, addr, NULL, FALSE, FALSE);
252 }
253 
254 static void
_os_log_with_args_internal(os_log_t oslog,os_log_type_t type,const char * format,va_list args,void * addr,void * dso,bool driverKit,bool addcr)255 _os_log_with_args_internal(os_log_t oslog, os_log_type_t type,
256     const char *format, va_list args, void *addr, void *dso, bool driverKit, bool addcr)
257 {
258 	if (format[0] == '\0') {
259 		return;
260 	}
261 
262 	/* early boot can log to dmesg for later replay (27307943) */
263 	bool safe = os_log_safe();
264 	bool logging = !os_log_turned_off();
265 
266 	if (oslog != &_os_log_replay) {
267 		_os_log_to_msgbuf_internal(format, args, safe, logging, addcr);
268 	}
269 
270 	if (safe && logging) {
271 		_os_log_to_log_internal(type, format, args, addr, dso, driverKit);
272 	}
273 }
274 
275 static void
_os_log_to_msgbuf_internal(const char * format,va_list args,bool safe,bool logging,bool addcr)276 _os_log_to_msgbuf_internal(const char *format, va_list args, bool safe, bool logging, bool addcr)
277 {
278 	/*
279 	 * The following threshold was determined empirically as the point where
280 	 * it would be more advantageous to be able to fit in more log lines than
281 	 * to know exactly when a log line was printed out. We don't want to use up
282 	 * a large percentage of the log buffer on timestamps in a memory-constricted
283 	 * environment.
284 	 */
285 	const int MSGBUF_TIMESTAMP_THRESHOLD = 4096;
286 	static int msgbufreplay = -1;
287 	static bool newlogline = true;
288 	va_list args_copy;
289 
290 	if (!bsd_log_lock(safe)) {
291 		counter_inc(&oslog_msgbuf_dropped_msgcount);
292 		return;
293 	}
294 
295 	if (!safe) {
296 		if (-1 == msgbufreplay) {
297 			msgbufreplay = msgbufp->msg_bufx;
298 		}
299 	} else if (logging && (-1 != msgbufreplay)) {
300 		uint32_t i;
301 		uint32_t localbuff_size;
302 		int newl, position;
303 		char *localbuff, *p, *s, *next, ch;
304 
305 		position = msgbufreplay;
306 		msgbufreplay = -1;
307 		localbuff_size = (msgbufp->msg_size + 2); /* + '\n' + '\0' */
308 		/* Size for non-blocking */
309 		if (localbuff_size > 4096) {
310 			localbuff_size = 4096;
311 		}
312 		bsd_log_unlock();
313 		/* Allocate a temporary non-circular buffer */
314 		localbuff = kalloc_data(localbuff_size, Z_NOWAIT);
315 		if (localbuff != NULL) {
316 			/* in between here, the log could become bigger, but that's fine */
317 			bsd_log_lock(true);
318 			/*
319 			 * The message buffer is circular; start at the replay pointer, and
320 			 * make one loop up to write pointer - 1.
321 			 */
322 			p = msgbufp->msg_bufc + position;
323 			for (i = newl = 0; p != msgbufp->msg_bufc + msgbufp->msg_bufx - 1; ++p) {
324 				if (p >= msgbufp->msg_bufc + msgbufp->msg_size) {
325 					p = msgbufp->msg_bufc;
326 				}
327 				ch = *p;
328 				if (ch == '\0') {
329 					continue;
330 				}
331 				newl = (ch == '\n');
332 				localbuff[i++] = ch;
333 				if (i >= (localbuff_size - 2)) {
334 					break;
335 				}
336 			}
337 			bsd_log_unlock();
338 
339 			if (!newl) {
340 				localbuff[i++] = '\n';
341 			}
342 			localbuff[i++] = 0;
343 
344 			s = localbuff;
345 			while ((next = strchr(s, '\n'))) {
346 				next++;
347 				ch = next[0];
348 				next[0] = 0;
349 				os_log(&_os_log_replay, "%s", s);
350 				next[0] = ch;
351 				s = next;
352 			}
353 			kfree_data(localbuff, localbuff_size);
354 		}
355 		bsd_log_lock(true);
356 	}
357 
358 	/* Do not prepend timestamps when we are memory-constricted */
359 	if (newlogline && (msgbufp->msg_size > MSGBUF_TIMESTAMP_THRESHOLD)) {
360 		clock_sec_t secs;
361 		clock_usec_t microsecs;
362 		const uint64_t timestamp = firehose_tracepoint_time(firehose_activity_flags_default);
363 		absolutetime_to_microtime(timestamp, &secs, &microsecs);
364 		printf_log_locked(FALSE, "[%5lu.%06u]: ", (unsigned long)secs, microsecs);
365 	}
366 
367 	va_copy(args_copy, args);
368 	newlogline = vprintf_log_locked(format, args_copy, addcr);
369 	va_end(args_copy);
370 
371 	bsd_log_unlock();
372 	logwakeup(msgbufp);
373 	counter_inc(&oslog_msgbuf_msgcount);
374 }
375 
376 static firehose_stream_t
firehose_stream(os_log_type_t type)377 firehose_stream(os_log_type_t type)
378 {
379 	return (type == OS_LOG_TYPE_INFO || type == OS_LOG_TYPE_DEBUG) ?
380 	       firehose_stream_memory : firehose_stream_persist;
381 }
382 
383 static void
log_payload_init(log_payload_t lp,firehose_stream_t stream,firehose_tracepoint_id_u ftid,uint64_t timestamp,size_t data_size)384 log_payload_init(log_payload_t lp, firehose_stream_t stream, firehose_tracepoint_id_u ftid,
385     uint64_t timestamp, size_t data_size)
386 {
387 	lp->lp_stream = stream;
388 	lp->lp_ftid = ftid;
389 	lp->lp_timestamp = timestamp;
390 	lp->lp_data_size = (uint16_t)data_size;
391 }
392 
393 static void
_os_log_actual(os_log_type_t type,const char * format,void * dso,void * addr,uint8_t * logdata,size_t logdata_sz,firehose_tracepoint_flags_t flags,bool driverKit)394 _os_log_actual(os_log_type_t type, const char *format, void *dso, void *addr, uint8_t *logdata, size_t logdata_sz,
395     firehose_tracepoint_flags_t flags, bool driverKit)
396 {
397 	firehose_tracepoint_id_u trace_id;
398 
399 	firehose_stream_t stream = firehose_stream(type);
400 	uint64_t timestamp = firehose_tracepoint_time(firehose_activity_flags_default);
401 
402 	if (driverKit) {
403 		// set FIREHOSE_TRACEPOINT_PC_DYNAMIC_BIT so logd will not try to find the format string in
404 		// the executable text
405 		trace_id.ftid_value = FIREHOSE_TRACE_ID_MAKE(firehose_tracepoint_namespace_log,
406 		    type, flags, (uint32_t)((uintptr_t)addr | FIREHOSE_TRACEPOINT_PC_DYNAMIC_BIT));
407 	} else {
408 		// create trace_id after we've set additional flags
409 		trace_id.ftid_value = FIREHOSE_TRACE_ID_MAKE(firehose_tracepoint_namespace_log,
410 		    type, flags, _os_trace_offset(dso, format, (_firehose_tracepoint_flags_activity_t)flags));
411 	}
412 
413 
414 	log_payload_s log;
415 	log_payload_init(&log, stream, trace_id, timestamp, logdata_sz);
416 
417 	if (!log_queue_log(&log, logdata, true)) {
418 		counter_inc(&oslog_p_dropped_msgcount);
419 	}
420 }
421 
422 static void *
resolve_dso(const char * fmt,void * dso,void * addr,bool driverKit)423 resolve_dso(const char *fmt, void *dso, void *addr, bool driverKit)
424 {
425 	kc_format_t kcformat = KCFormatUnknown;
426 
427 	if (!PE_get_primary_kc_format(&kcformat)) {
428 		return NULL;
429 	}
430 
431 	switch (kcformat) {
432 	case KCFormatStatic:
433 	case KCFormatKCGEN:
434 		dso = PE_get_kc_baseaddress(KCKindPrimary);
435 		break;
436 	case KCFormatDynamic:
437 	case KCFormatFileset:
438 		if (!dso && (dso = (void *)OSKextKextForAddress(fmt)) == NULL) {
439 			return NULL;
440 		}
441 		if (!_os_trace_addr_in_text_segment(dso, fmt)) {
442 			return NULL;
443 		}
444 		if (!driverKit && (dso != (void *)OSKextKextForAddress(addr))) {
445 			return NULL;
446 		}
447 		break;
448 	default:
449 		panic("unknown KC format type");
450 	}
451 
452 	return dso;
453 }
454 
455 static void
_os_log_to_log_internal(os_log_type_t type,const char * fmt,va_list args,void * addr,void * dso,bool driverKit)456 _os_log_to_log_internal(os_log_type_t type, const char *fmt, va_list args, void *addr, void *dso, bool driverKit)
457 {
458 	counter_inc(&oslog_p_total_msgcount);
459 
460 	if (addr == NULL) {
461 		counter_inc(&oslog_p_unresolved_kc_msgcount);
462 		return;
463 	}
464 
465 	if ((dso = resolve_dso(fmt, dso, addr, driverKit)) == NULL) {
466 		counter_inc(&oslog_p_unresolved_kc_msgcount);
467 		return;
468 	}
469 
470 	uint8_t buffer[OS_LOG_BUFFER_MAX_SIZE] __attribute__((aligned(8))) = { 0 };
471 	struct os_log_context_s ctx;
472 
473 	os_log_context_init(&ctx, &os_log_mem, buffer, sizeof(buffer));
474 
475 	if (os_log_context_encode(&ctx, fmt, args, addr, dso, driverKit)) {
476 		_os_log_actual(type, fmt, dso, addr, ctx.ctx_buffer, ctx.ctx_content_sz,
477 		    ctx.ctx_ft_flags, driverKit);
478 	} else {
479 		counter_inc(&oslog_p_error_count);
480 	}
481 
482 	os_log_context_free(&ctx);
483 }
484 
485 bool
os_log_coprocessor(void * buff,uint64_t buff_len,os_log_type_t type,const char * uuid,uint64_t timestamp,uint32_t offset,bool stream_log)486 os_log_coprocessor(void *buff, uint64_t buff_len, os_log_type_t type,
487     const char *uuid, uint64_t timestamp, uint32_t offset, bool stream_log)
488 {
489 	firehose_tracepoint_id_u trace_id;
490 	uint8_t                  pubdata[OS_LOG_BUFFER_MAX_SIZE];
491 	size_t                   wr_pos = 0;
492 
493 	if (os_log_turned_off()) {
494 		return false;
495 	}
496 
497 	if (!os_log_safe()) {
498 		counter_inc(&oslog_p_coprocessor_dropped_msgcount);
499 		return false;
500 	}
501 
502 	if (buff_len + 16 + sizeof(uint32_t) > OS_LOG_BUFFER_MAX_SIZE) {
503 		counter_inc(&oslog_p_coprocessor_dropped_msgcount);
504 		return false;
505 	}
506 
507 	firehose_stream_t stream = firehose_stream(type);
508 	// unlike kext, where pc is used to find uuid, in coprocessor logs the uuid is passed as part of the tracepoint
509 	firehose_tracepoint_flags_t flags = _firehose_tracepoint_flags_pc_style_uuid_relative;
510 
511 	memcpy(pubdata, &offset, sizeof(uint32_t));
512 	wr_pos += sizeof(uint32_t);
513 	memcpy(pubdata + wr_pos, uuid, 16);
514 	wr_pos += 16;
515 
516 	memcpy(pubdata + wr_pos, buff, buff_len);
517 
518 	// create firehose trace id
519 	trace_id.ftid_value = FIREHOSE_TRACE_ID_MAKE(firehose_tracepoint_namespace_log,
520 	    type, flags, offset);
521 
522 	counter_inc(&oslog_p_coprocessor_total_msgcount);
523 
524 	log_payload_s log;
525 	log_payload_init(&log, stream, trace_id, timestamp, buff_len + wr_pos);
526 
527 	if (!log_queue_log(&log, pubdata, stream_log)) {
528 		counter_inc(&oslog_p_coprocessor_dropped_msgcount);
529 		return false;
530 	}
531 
532 	return true;
533 }
534 
535 static firehose_tracepoint_id_t
_firehose_trace_early_boot(firehose_tracepoint_id_u ftid,uint64_t stamp,const void * pubdata,size_t publen)536 _firehose_trace_early_boot(firehose_tracepoint_id_u ftid, uint64_t stamp, const void *pubdata, size_t publen)
537 {
538 	firehose_chunk_t fbc = firehose_boot_chunk;
539 
540 	//only stream available during boot is persist
541 	long offset = firehose_chunk_tracepoint_try_reserve(fbc, stamp,
542 	    firehose_stream_persist, 0, (uint16_t)publen, 0, NULL);
543 	if (offset <= 0) {
544 		counter_inc(&oslog_p_boot_dropped_msgcount);
545 		return 0;
546 	}
547 
548 	firehose_tracepoint_t ft = firehose_chunk_tracepoint_begin(fbc, stamp, (uint16_t)publen,
549 	    thread_tid(current_thread()), offset);
550 	memcpy(ft->ft_data, pubdata, publen);
551 	firehose_chunk_tracepoint_end(fbc, ft, ftid);
552 
553 	counter_inc(&oslog_p_saved_msgcount);
554 
555 	return ftid.ftid_value;
556 }
557 
558 static inline firehose_tracepoint_id_t
_firehose_trace(firehose_stream_t stream,firehose_tracepoint_id_u ftid,uint64_t stamp,const void * data,size_t datalen)559 _firehose_trace(firehose_stream_t stream, firehose_tracepoint_id_u ftid,
560     uint64_t stamp, const void *data, size_t datalen)
561 {
562 	const uint16_t __assert_only ft_size = offsetof(struct firehose_tracepoint_s, ft_data);
563 	const size_t __assert_only _firehose_chunk_payload_size = sizeof(((struct firehose_chunk_s *)0)->fc_data);
564 	assert((ft_size + datalen) <= _firehose_chunk_payload_size);
565 
566 	firehose_tracepoint_t ft = __firehose_buffer_tracepoint_reserve(stamp, stream, (uint16_t)datalen, 0, NULL);
567 
568 	if (fastpath(ft)) {
569 		oslog_boot_done = true;
570 
571 		memcpy(ft->ft_data, data, datalen);
572 		__firehose_buffer_tracepoint_flush(ft, ftid);
573 
574 		if (stream == firehose_stream_metadata) {
575 			counter_inc(&oslog_p_metadata_saved_msgcount);
576 		} else {
577 			counter_inc(&oslog_p_saved_msgcount);
578 		}
579 
580 		return ftid.ftid_value;
581 	}
582 
583 	if (!oslog_boot_done) {
584 		return _firehose_trace_early_boot(ftid, stamp, data, datalen);
585 	}
586 
587 	return 0;
588 }
589 
590 void
os_log_coprocessor_register(const char * uuid,const char * file_path,bool copy)591 os_log_coprocessor_register(const char *uuid, const char *file_path, bool copy)
592 {
593 	// Will be removed after all user code will be updated to use os_log_coprocessor_register_with_type
594 	os_log_coprocessor_register_with_type(uuid, file_path, copy ? os_log_coproc_register_memory : os_log_coproc_register_harvest_fs_img4);
595 }
596 
597 static firehose_tracepoint_code_t
coproc_reg_type_to_firehost_code(os_log_coproc_reg_t reg_type)598 coproc_reg_type_to_firehost_code(os_log_coproc_reg_t reg_type)
599 {
600 	switch (reg_type) {
601 	case os_log_coproc_register_memory:
602 		return firehose_tracepoint_code_load_memory;
603 	case os_log_coproc_register_harvest_fs_img4:
604 		return firehose_tracepoint_code_load_filesystem;
605 	case os_log_coproc_register_harvest_fs_ftab:
606 		return firehose_tracepoint_code_load_filesystem_ftab;
607 	default:
608 		return firehose_tracepoint_code_invalid;
609 	}
610 }
611 
612 void
os_log_coprocessor_register_with_type(const char * uuid,const char * file_path,os_log_coproc_reg_t reg_type)613 os_log_coprocessor_register_with_type(const char *uuid, const char *file_path, os_log_coproc_reg_t reg_type)
614 {
615 	uint64_t                 stamp;
616 	size_t                   path_size = strlen(file_path) + 1;
617 	firehose_tracepoint_id_u trace_id;
618 	size_t                   uuid_info_len = sizeof(struct firehose_trace_uuid_info_s) + path_size;
619 	union {
620 		struct firehose_trace_uuid_info_s uuid_info;
621 		char path[PATH_MAX + sizeof(struct firehose_trace_uuid_info_s)];
622 	} buf;
623 
624 	if (os_log_disabled()) {
625 		return;
626 	}
627 
628 	if (path_size > PATH_MAX) {
629 		return;
630 	}
631 
632 	// write metadata to uuid_info
633 	memcpy(buf.uuid_info.ftui_uuid, uuid, sizeof(uuid_t));
634 	buf.uuid_info.ftui_size    = 1;
635 	buf.uuid_info.ftui_address = 1;
636 
637 	stamp = firehose_tracepoint_time(firehose_activity_flags_default);
638 
639 	// create tracepoint id
640 	trace_id.ftid_value = FIREHOSE_TRACE_ID_MAKE(firehose_tracepoint_namespace_metadata, _firehose_tracepoint_type_metadata_coprocessor,
641 	    (firehose_tracepoint_flags_t)0, coproc_reg_type_to_firehost_code(reg_type));
642 
643 	// write path to buffer
644 	memcpy(buf.uuid_info.ftui_path, file_path, path_size);
645 
646 	// send metadata tracepoint to firehose for coprocessor registration in logd
647 	firehose_trace_metadata(firehose_stream_metadata, trace_id, stamp, (void *)&buf, uuid_info_len);
648 	return;
649 }
650 
651 #ifdef KERNEL
652 void
firehose_trace_metadata(firehose_stream_t stream,firehose_tracepoint_id_u ftid,uint64_t stamp,const void * pubdata,size_t publen)653 firehose_trace_metadata(firehose_stream_t stream, firehose_tracepoint_id_u ftid,
654     uint64_t stamp, const void *pubdata, size_t publen)
655 {
656 	if (os_log_disabled()) {
657 		return;
658 	}
659 
660 	if (!os_log_safe()) {
661 		counter_inc(&oslog_p_metadata_dropped_msgcount);
662 		return;
663 	}
664 
665 	log_payload_s log;
666 	log_payload_init(&log, stream, ftid, stamp, publen);
667 
668 	if (!log_queue_log(&log, pubdata, true)) {
669 		counter_inc(&oslog_p_metadata_dropped_msgcount);
670 	}
671 }
672 #endif
673 
674 bool
log_payload_send(log_payload_t lp,const void * lp_data,bool use_stream)675 log_payload_send(log_payload_t lp, const void *lp_data, bool use_stream)
676 {
677 	if (use_stream) {
678 		bool is_metadata = (lp->lp_stream == firehose_stream_metadata);
679 		oslog_stream(is_metadata, lp->lp_ftid, lp->lp_timestamp, lp_data, lp->lp_data_size);
680 	}
681 
682 	return _firehose_trace(lp->lp_stream, lp->lp_ftid, lp->lp_timestamp,
683 	           lp_data, lp->lp_data_size);
684 }
685 
686 void
__firehose_buffer_push_to_logd(firehose_buffer_t fb __unused,bool for_io __unused)687 __firehose_buffer_push_to_logd(firehose_buffer_t fb __unused, bool for_io __unused)
688 {
689 	oslogwakeup();
690 	return;
691 }
692 
693 void
__firehose_allocate(vm_offset_t * addr,vm_size_t size __unused)694 __firehose_allocate(vm_offset_t *addr, vm_size_t size __unused)
695 {
696 	firehose_chunk_t kernel_buffer = (firehose_chunk_t)kernel_firehose_addr;
697 
698 	if (kernel_firehose_addr) {
699 		*addr = kernel_firehose_addr;
700 	} else {
701 		*addr = 0;
702 		return;
703 	}
704 	// Now that we are done adding logs to this chunk, set the number of writers to 0
705 	// Without this, logd won't flush when the page is full
706 	firehose_boot_chunk->fc_pos.fcp_refcnt = 0;
707 	memcpy(&kernel_buffer[FIREHOSE_BUFFER_KERNEL_CHUNK_COUNT - 1], (const void *)firehose_boot_chunk, FIREHOSE_CHUNK_SIZE);
708 	return;
709 }
710 // There isnt a lock held in this case.
711 void
__firehose_critical_region_enter(void)712 __firehose_critical_region_enter(void)
713 {
714 	disable_preemption();
715 	return;
716 }
717 
718 void
__firehose_critical_region_leave(void)719 __firehose_critical_region_leave(void)
720 {
721 	enable_preemption();
722 	return;
723 }
724 
725 #ifdef CONFIG_XNUPOST
726 
727 #include <tests/xnupost.h>
728 #define TESTOSLOGFMT(fn_name) "%u^%llu/%llu^kernel^0^test^" fn_name
729 #define TESTOSLOGPFX "TESTLOG:%u#"
730 #define TESTOSLOG(fn_name) TESTOSLOGPFX TESTOSLOGFMT(fn_name "#")
731 
732 extern u_int32_t RandomULong(void);
733 extern size_t find_pattern_in_buffer(const char *pattern, size_t len, size_t expected_count);
734 void test_oslog_default_helper(uint32_t uniqid, uint64_t count);
735 void test_oslog_info_helper(uint32_t uniqid, uint64_t count);
736 void test_oslog_debug_helper(uint32_t uniqid, uint64_t count);
737 void test_oslog_error_helper(uint32_t uniqid, uint64_t count);
738 void test_oslog_fault_helper(uint32_t uniqid, uint64_t count);
739 void _test_log_loop(void * arg __unused, wait_result_t wres __unused);
740 void test_oslog_handleOSLogCtl(int32_t * in, int32_t * out, int32_t len);
741 kern_return_t test_stresslog_dropmsg(uint32_t uniqid);
742 
743 kern_return_t test_os_log(void);
744 kern_return_t test_os_log_parallel(void);
745 
746 #define GENOSLOGHELPER(fname, ident, callout_f)                                                            \
747     void fname(uint32_t uniqid, uint64_t count)                                                            \
748     {                                                                                                      \
749 	int32_t datalen = 0;                                                                               \
750 	uint32_t checksum = 0;                                                                             \
751 	char databuffer[256];                                                                              \
752 	T_LOG("Doing os_log of %llu TESTLOG msgs for fn " ident, count);                                   \
753 	for (uint64_t i = 0; i < count; i++)                                                               \
754 	{                                                                                                  \
755 	    datalen = scnprintf(databuffer, sizeof(databuffer), TESTOSLOGFMT(ident), uniqid, i + 1, count); \
756 	    checksum = crc32(0, databuffer, datalen);                                                      \
757 	    callout_f(OS_LOG_DEFAULT, TESTOSLOG(ident), checksum, uniqid, i + 1, count);                   \
758 	/*T_LOG(TESTOSLOG(ident), checksum, uniqid, i + 1, count);*/                                   \
759 	}                                                                                                  \
760     }
761 
762 GENOSLOGHELPER(test_oslog_info_helper, "oslog_info_helper", os_log_info);
763 GENOSLOGHELPER(test_oslog_fault_helper, "oslog_fault_helper", os_log_fault);
764 GENOSLOGHELPER(test_oslog_debug_helper, "oslog_debug_helper", os_log_debug);
765 GENOSLOGHELPER(test_oslog_error_helper, "oslog_error_helper", os_log_error);
766 GENOSLOGHELPER(test_oslog_default_helper, "oslog_default_helper", os_log);
767 
768 kern_return_t
test_os_log()769 test_os_log()
770 {
771 	char databuffer[256];
772 	uint32_t uniqid = RandomULong();
773 	size_t match_count = 0;
774 	uint32_t checksum = 0;
775 	uint32_t total_msg = 0;
776 	uint32_t saved_msg = 0;
777 	uint32_t dropped_msg = 0;
778 	size_t datalen = 0;
779 	uint64_t a = mach_absolute_time();
780 	uint64_t seqno = 1;
781 	uint64_t total_seqno = 2;
782 
783 	os_log_t log_handle = os_log_create("com.apple.xnu.test.t1", "kpost");
784 
785 	T_ASSERT_EQ_PTR(&_os_log_default, log_handle, "os_log_create returns valid value.");
786 	T_ASSERT_EQ_INT(TRUE, os_log_info_enabled(log_handle), "os_log_info is enabled");
787 	T_ASSERT_EQ_INT(TRUE, os_log_debug_enabled(log_handle), "os_log_debug is enabled");
788 	T_ASSERT_EQ_PTR(&_os_log_default, OS_LOG_DEFAULT, "ensure OS_LOG_DEFAULT is _os_log_default");
789 
790 	total_msg = counter_load(&oslog_p_total_msgcount);
791 	saved_msg = counter_load(&oslog_p_saved_msgcount);
792 	dropped_msg = counter_load(&oslog_p_dropped_msgcount);
793 	T_LOG("oslog internal counters total %u , saved %u, dropped %u", total_msg, saved_msg, dropped_msg);
794 
795 	T_LOG("Validating with uniqid %u u64 %llu", uniqid, a);
796 	T_ASSERT_NE_UINT(0, uniqid, "random number should not be zero");
797 	T_ASSERT_NE_ULLONG(0, a, "absolute time should not be zero");
798 
799 	datalen = scnprintf(databuffer, sizeof(databuffer), TESTOSLOGFMT("printf_only"), uniqid, seqno, total_seqno);
800 	checksum = crc32(0, databuffer, datalen);
801 	printf(TESTOSLOG("printf_only") "mat%llu\n", checksum, uniqid, seqno, total_seqno, a);
802 
803 	seqno += 1;
804 	datalen = scnprintf(databuffer, sizeof(databuffer), TESTOSLOGFMT("printf_only"), uniqid, seqno, total_seqno);
805 	checksum = crc32(0, databuffer, datalen);
806 	printf(TESTOSLOG("printf_only") "mat%llu\n", checksum, uniqid, seqno, total_seqno, a);
807 
808 	datalen = scnprintf(databuffer, sizeof(databuffer), "kernel^0^test^printf_only#mat%llu", a);
809 	match_count = find_pattern_in_buffer(databuffer, datalen, total_seqno);
810 	T_EXPECT_EQ_ULONG(match_count, total_seqno, "verify printf_only goes to systemlog buffer");
811 
812 	uint32_t logging_config = atm_get_diagnostic_config();
813 	T_LOG("checking atm_diagnostic_config 0x%X", logging_config);
814 
815 	if ((logging_config & ATM_TRACE_OFF) || (logging_config & ATM_TRACE_DISABLE)) {
816 		T_LOG("ATM_TRACE_OFF / ATM_TRACE_DISABLE is set. Would not see oslog messages. skipping the rest of test.");
817 		return KERN_SUCCESS;
818 	}
819 
820 	/* for enabled logging printfs should be saved in oslog as well */
821 	T_EXPECT_GE_UINT((counter_load(&oslog_p_total_msgcount) - total_msg), 2, "atleast 2 msgs should be seen by oslog system");
822 
823 	a = mach_absolute_time();
824 	total_seqno = 1;
825 	seqno = 1;
826 	total_msg = counter_load(&oslog_p_total_msgcount);
827 	saved_msg = counter_load(&oslog_p_saved_msgcount);
828 	dropped_msg = counter_load(&oslog_p_dropped_msgcount);
829 	datalen = scnprintf(databuffer, sizeof(databuffer), TESTOSLOGFMT("oslog_info"), uniqid, seqno, total_seqno);
830 	checksum = crc32(0, databuffer, datalen);
831 	os_log_info(log_handle, TESTOSLOG("oslog_info") "mat%llu", checksum, uniqid, seqno, total_seqno, a);
832 	T_EXPECT_GE_UINT((counter_load(&oslog_p_total_msgcount) - total_msg), 1, "total message count in buffer");
833 
834 	datalen = scnprintf(databuffer, sizeof(databuffer), "kernel^0^test^oslog_info#mat%llu", a);
835 	match_count = find_pattern_in_buffer(databuffer, datalen, total_seqno);
836 	T_EXPECT_EQ_ULONG(match_count, total_seqno, "verify oslog_info does not go to systemlog buffer");
837 
838 	total_msg = counter_load(&oslog_p_total_msgcount);
839 	test_oslog_info_helper(uniqid, 10);
840 	T_EXPECT_GE_UINT(counter_load(&oslog_p_total_msgcount) - total_msg, 10, "test_oslog_info_helper: Should have seen 10 msgs");
841 
842 	total_msg = counter_load(&oslog_p_total_msgcount);
843 	test_oslog_debug_helper(uniqid, 10);
844 	T_EXPECT_GE_UINT(counter_load(&oslog_p_total_msgcount) - total_msg, 10, "test_oslog_debug_helper:Should have seen 10 msgs");
845 
846 	total_msg = counter_load(&oslog_p_total_msgcount);
847 	test_oslog_error_helper(uniqid, 10);
848 	T_EXPECT_GE_UINT(counter_load(&oslog_p_total_msgcount) - total_msg, 10, "test_oslog_error_helper:Should have seen 10 msgs");
849 
850 	total_msg = counter_load(&oslog_p_total_msgcount);
851 	test_oslog_default_helper(uniqid, 10);
852 	T_EXPECT_GE_UINT(counter_load(&oslog_p_total_msgcount) - total_msg, 10, "test_oslog_default_helper:Should have seen 10 msgs");
853 
854 	total_msg = counter_load(&oslog_p_total_msgcount);
855 	test_oslog_fault_helper(uniqid, 10);
856 	T_EXPECT_GE_UINT(counter_load(&oslog_p_total_msgcount) - total_msg, 10, "test_oslog_fault_helper:Should have seen 10 msgs");
857 
858 	T_LOG("oslog internal counters total %u , saved %u, dropped %u", counter_load(&oslog_p_total_msgcount), counter_load(&oslog_p_saved_msgcount),
859 	    counter_load(&oslog_p_dropped_msgcount));
860 
861 	return KERN_SUCCESS;
862 }
863 
864 static uint32_t _test_log_loop_count = 0;
865 void
_test_log_loop(void * arg __unused,wait_result_t wres __unused)866 _test_log_loop(void * arg __unused, wait_result_t wres __unused)
867 {
868 	uint32_t uniqid = RandomULong();
869 	test_oslog_debug_helper(uniqid, 100);
870 	os_atomic_add(&_test_log_loop_count, 100, relaxed);
871 }
872 
873 kern_return_t
test_os_log_parallel(void)874 test_os_log_parallel(void)
875 {
876 	thread_t thread[2];
877 	kern_return_t kr;
878 	uint32_t uniqid = RandomULong();
879 
880 	printf("oslog internal counters total %lld , saved %lld, dropped %lld", counter_load(&oslog_p_total_msgcount), counter_load(&oslog_p_saved_msgcount),
881 	    counter_load(&oslog_p_dropped_msgcount));
882 
883 	kr = kernel_thread_start(_test_log_loop, NULL, &thread[0]);
884 	T_ASSERT_EQ_INT(kr, KERN_SUCCESS, "kernel_thread_start returned successfully");
885 
886 	kr = kernel_thread_start(_test_log_loop, NULL, &thread[1]);
887 	T_ASSERT_EQ_INT(kr, KERN_SUCCESS, "kernel_thread_start returned successfully");
888 
889 	test_oslog_info_helper(uniqid, 100);
890 
891 	/* wait until other thread has also finished */
892 	while (_test_log_loop_count < 200) {
893 		delay(1000);
894 	}
895 
896 	thread_deallocate(thread[0]);
897 	thread_deallocate(thread[1]);
898 
899 	T_LOG("oslog internal counters total %lld , saved %lld, dropped %lld", counter_load(&oslog_p_total_msgcount), counter_load(&oslog_p_saved_msgcount),
900 	    counter_load(&oslog_p_dropped_msgcount));
901 	T_PASS("parallel_logging tests is now complete");
902 
903 	return KERN_SUCCESS;
904 }
905 
906 void
test_oslog_handleOSLogCtl(int32_t * in,int32_t * out,int32_t len)907 test_oslog_handleOSLogCtl(int32_t * in, int32_t * out, int32_t len)
908 {
909 	if (!in || !out || len != 4) {
910 		return;
911 	}
912 	switch (in[0]) {
913 	case 1:
914 	{
915 		/* send out counters */
916 		out[1] = counter_load(&oslog_p_total_msgcount);
917 		out[2] = counter_load(&oslog_p_saved_msgcount);
918 		out[3] = counter_load(&oslog_p_dropped_msgcount);
919 		out[0] = KERN_SUCCESS;
920 		break;
921 	}
922 	case 2:
923 	{
924 		/* mini stress run */
925 		out[0] = test_os_log_parallel();
926 		break;
927 	}
928 	case 3:
929 	{
930 		/* drop msg tests */
931 		out[1] = RandomULong();
932 		out[0] = test_stresslog_dropmsg(out[1]);
933 		break;
934 	}
935 	case 4:
936 	{
937 		/* invoke log helpers */
938 		uint32_t uniqid = in[3];
939 		int32_t msgcount = in[2];
940 		if (uniqid == 0 || msgcount == 0) {
941 			out[0] = KERN_INVALID_VALUE;
942 			return;
943 		}
944 
945 		switch (in[1]) {
946 		case OS_LOG_TYPE_INFO: test_oslog_info_helper(uniqid, msgcount); break;
947 		case OS_LOG_TYPE_DEBUG: test_oslog_debug_helper(uniqid, msgcount); break;
948 		case OS_LOG_TYPE_ERROR: test_oslog_error_helper(uniqid, msgcount); break;
949 		case OS_LOG_TYPE_FAULT: test_oslog_fault_helper(uniqid, msgcount); break;
950 		case OS_LOG_TYPE_DEFAULT:
951 		default: test_oslog_default_helper(uniqid, msgcount); break;
952 		}
953 		out[0] = KERN_SUCCESS;
954 		break;
955 		/* end of case 4 */
956 	}
957 	default:
958 	{
959 		out[0] = KERN_INVALID_VALUE;
960 		break;
961 	}
962 	}
963 	return;
964 }
965 
966 kern_return_t
test_stresslog_dropmsg(uint32_t uniqid)967 test_stresslog_dropmsg(uint32_t uniqid)
968 {
969 	uint32_t total, saved, dropped;
970 	total = counter_load(&oslog_p_total_msgcount);
971 	saved = counter_load(&oslog_p_saved_msgcount);
972 	dropped = counter_load(&oslog_p_dropped_msgcount);
973 	uniqid = RandomULong();
974 	test_oslog_debug_helper(uniqid, 100);
975 	while ((counter_load(&oslog_p_dropped_msgcount) - dropped) == 0) {
976 		test_oslog_debug_helper(uniqid, 100);
977 	}
978 	printf("test_stresslog_dropmsg: logged %lld msgs, saved %lld and caused a drop of %lld msgs. \n", counter_load(&oslog_p_total_msgcount) - total,
979 	    counter_load(&oslog_p_saved_msgcount) - saved, counter_load(&oslog_p_dropped_msgcount) - dropped);
980 	return KERN_SUCCESS;
981 }
982 
983 #endif
984