1/*
2 * Copyright (c) 2000-2008 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28
29/*
30 * Copyright (c) 1982, 1986, 1993
31 *      The Regents of the University of California.  All rights reserved.
32 */
33
34/*
35 * Kernel Debugging Protocol UDP implementation.
36 */
37
38#include <mach/boolean.h>
39#include <mach/mach_types.h>
40#include <mach/exception_types.h>
41#include <kern/cpu_data.h>
42#include <kern/debug.h>
43#include <kern/clock.h>
44
45#include <kdp/kdp_core.h>
46#include <kdp/kdp_internal.h>
47#include <kdp/kdp_en_debugger.h>
48#include <kdp/kdp_callout.h>
49#include <kdp/kdp_udp.h>
50
51#ifdef __arm__
52#define CONFIG_SERIAL_KDP 1
53#endif
54
55#if CONFIG_SERIAL_KDP
56#include <kdp/kdp_serial.h>
57#endif
58
59#include <vm/vm_map.h>
60#include <vm/vm_protos.h>
61#include <vm/vm_kern.h> /* kernel_map */
62
63#include <mach/memory_object_types.h>
64#include <machine/pal_routines.h>
65
66#include <sys/msgbuf.h>
67
68/* we just want the link status flags, so undef KERNEL_PRIVATE for this
69 * header file. */
70#undef KERNEL_PRIVATE
71#include <net/if_media.h>
72#define KERNEL_PRIVATE
73
74#include <string.h>
75
76#include <IOKit/IOPlatformExpert.h>
77#include <libkern/version.h>
78
79#define DO_ALIGN	1	      /* align all packet data accesses */
80#define KDP_SERIAL_IPADDR  0xABADBABE /* IP address used for serial KDP */
81#define LINK_UP_STATUS     (IFM_AVALID | IFM_ACTIVE)
82
83extern int kdp_getc(void);
84extern int reattach_wait;
85
86/* only used by IONetworkingFamily */
87typedef uint32_t (*kdp_link_t)(void);
88typedef boolean_t (*kdp_mode_t)(boolean_t);
89void 	kdp_register_link(kdp_link_t link, kdp_mode_t mode);
90void 	kdp_unregister_link(kdp_link_t link, kdp_mode_t mode);
91
92static u_short ip_id;                          /* ip packet ctr, for ids */
93
94/*	@(#)udp_usrreq.c	2.2 88/05/23 4.0NFSSRC SMI;	from UCB 7.1 6/5/86	*/
95
96/*
97 * UDP protocol implementation.
98 * Per RFC 768, August, 1980.
99 */
100#define UDP_TTL	60 /* deflt time to live for UDP packets */
101int	udp_ttl = UDP_TTL;
102static unsigned char	exception_seq;
103
104static struct {
105    unsigned char	data[KDP_MAXPACKET];
106    unsigned int	off, len;
107    boolean_t		input;
108} pkt, saved_reply;
109
110struct kdp_manual_pkt manual_pkt;
111
112struct {
113    struct {
114	struct in_addr		in;
115	struct ether_addr	ea;
116    } loc;
117    struct {
118	struct in_addr		in;
119	struct ether_addr	ea;
120    } rmt;
121} adr;
122
123static const char
124*exception_message[] = {
125    "Unknown",
126    "Memory access",		/* EXC_BAD_ACCESS */
127    "Failed instruction",	/* EXC_BAD_INSTRUCTION */
128    "Arithmetic",		/* EXC_ARITHMETIC */
129    "Emulation",		/* EXC_EMULATION */
130    "Software",			/* EXC_SOFTWARE */
131    "Breakpoint"		/* EXC_BREAKPOINT */
132};
133
134volatile int kdp_flag = 0;
135
136static kdp_send_t    kdp_en_send_pkt;
137static kdp_receive_t kdp_en_recv_pkt;
138static kdp_link_t    kdp_en_linkstatus;
139static kdp_mode_t    kdp_en_setmode;
140
141#if CONFIG_SERIAL_KDP
142static void kdp_serial_send(void *rpkt, unsigned int rpkt_len);
143#define KDP_SERIAL_ENABLED()  (kdp_en_send_pkt == kdp_serial_send)
144#else
145#define KDP_SERIAL_ENABLED()  (0)
146#endif
147
148static uint32_t kdp_current_ip_address = 0;
149static struct ether_addr kdp_current_mac_address = {{0, 0, 0, 0, 0, 0}};
150static void *kdp_current_ifp;
151
152static void kdp_handler( void *);
153
154static uint32_t panic_server_ip = 0;
155static uint32_t parsed_router_ip = 0;
156static uint32_t router_ip = 0;
157static uint32_t target_ip = 0;
158
159static boolean_t save_ip_in_nvram = FALSE;
160
161static volatile boolean_t panicd_specified = FALSE;
162static boolean_t router_specified = FALSE;
163static boolean_t corename_specified = FALSE;
164static unsigned int panicd_port = CORE_REMOTE_PORT;
165
166static struct ether_addr etherbroadcastaddr = {{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}};
167
168static struct ether_addr router_mac = {{0, 0, 0 , 0, 0, 0}};
169static struct ether_addr destination_mac = {{0, 0, 0 , 0, 0, 0}};
170static struct ether_addr temp_mac = {{0, 0, 0 , 0, 0, 0}};
171static struct ether_addr current_resolved_MAC = {{0, 0, 0 , 0, 0, 0}};
172
173static boolean_t flag_panic_dump_in_progress = FALSE;
174static boolean_t flag_router_mac_initialized = FALSE;
175static boolean_t flag_dont_abort_panic_dump  = FALSE;
176
177static boolean_t flag_arp_resolved = FALSE;
178
179static unsigned int panic_timeout = 100000;
180static unsigned int last_panic_port = CORE_REMOTE_PORT;
181
182#define KDP_THROTTLE_VALUE       (10ULL * NSEC_PER_SEC)
183
184uint32_t kdp_crashdump_pkt_size = 512;
185#define KDP_LARGE_CRASHDUMP_PKT_SIZE (1440 - 6 - sizeof(struct udpiphdr))
186static char panicd_ip_str[20];
187static char router_ip_str[20];
188static char corename_str[50];
189
190static unsigned int panic_block = 0;
191volatile unsigned int kdp_trigger_core_dump = 0;
192__private_extern__ volatile unsigned int flag_kdp_trigger_reboot = 0;
193
194extern unsigned int not_in_kdp;
195
196extern unsigned int disableConsoleOutput;
197
198extern void 		kdp_call(void);
199extern boolean_t 	kdp_call_kdb(void);
200extern int 		kern_dump(void);
201
202extern int inet_aton(const char *cp, struct in_addr *pin);
203extern int inet_ntoa2(struct in_addr * pin, char * cp, const int len);
204
205void *	kdp_get_interface(void);
206void    kdp_set_gateway_mac(void *gatewaymac);
207void 	kdp_set_ip_and_mac_addresses(struct in_addr *ipaddr, struct ether_addr *);
208void 	kdp_set_interface(void *interface, const struct ether_addr *macaddr);
209
210void 			kdp_disable_arp(void);
211static void 		kdp_arp_reply(struct ether_arp *);
212static void 		kdp_process_arp_reply(struct ether_arp *);
213static boolean_t 	kdp_arp_resolve(uint32_t, struct ether_addr *);
214
215static volatile unsigned	kdp_reentry_deadline;
216
217static uint32_t kdp_crashdump_feature_mask = KDP_FEATURE_LARGE_CRASHDUMPS | KDP_FEATURE_LARGE_PKT_SIZE;
218uint32_t kdp_feature_large_crashdumps, kdp_feature_large_pkt_size;
219
220char kdp_kernelversion_string[256];
221
222static boolean_t	gKDPDebug = FALSE;
223#define KDP_DEBUG(...) if (gKDPDebug) printf(__VA_ARGS__);
224
225int kdp_snapshot = 0;
226static int stack_snapshot_ret = 0;
227static unsigned stack_snapshot_bytes_traced = 0;
228
229static void *stack_snapshot_buf;
230static uint32_t stack_snapshot_bufsize;
231static int stack_snapshot_pid;
232static uint32_t stack_snapshot_flags;
233static uint32_t stack_snapshot_dispatch_offset;
234
235static unsigned int old_debugger;
236
237#define SBLOCKSZ (2048)
238uint64_t kdp_dump_start_time = 0;
239uint64_t kdp_min_superblock_dump_time = ~1ULL;
240uint64_t kdp_max_superblock_dump_time = 0;
241uint64_t kdp_superblock_dump_time = 0;
242uint64_t kdp_superblock_dump_start_time = 0;
243
244void
245kdp_snapshot_preflight(int pid, void * tracebuf, uint32_t tracebuf_size,
246    uint32_t flags, uint32_t dispatch_offset);
247
248void
249kdp_snapshot_postflight(void);
250
251extern int
252kdp_stackshot(int pid, void *tracebuf, uint32_t tracebuf_size,
253    uint32_t flags, uint32_t dispatch_offset, uint32_t *pbytesTraced);
254
255int
256kdp_stack_snapshot_geterror(void);
257
258int
259kdp_stack_snapshot_bytes_traced(void);
260
261static thread_call_t
262kdp_timer_call;
263
264static void
265kdp_ml_enter_debugger_wrapper(__unused void *param0, __unused void *param1) {
266	kdp_ml_enter_debugger();
267}
268
269static void
270kdp_timer_callout_init(void) {
271	kdp_timer_call = thread_call_allocate(kdp_ml_enter_debugger_wrapper, NULL);
272}
273
274
275/* only send/receive data if the link is up */
276inline static void wait_for_link(void)
277{
278    static int first = 0;
279
280    if (!kdp_en_linkstatus)
281        return;
282
283    while (((*kdp_en_linkstatus)() & LINK_UP_STATUS) != LINK_UP_STATUS) {
284        if (first)
285            continue;
286
287        first = 1;
288        printf("Waiting for link to become available.\n");
289        kprintf("Waiting for link to become available.\n");
290    }
291}
292
293
294inline static void kdp_send_data(void *packet, unsigned int len)
295{
296    wait_for_link();
297    (*kdp_en_send_pkt)(packet, len);
298}
299
300
301inline static void kdp_receive_data(void *packet, unsigned int *len,
302                                    unsigned int timeout)
303{
304    wait_for_link();
305    (*kdp_en_recv_pkt)(packet, len, timeout);
306}
307
308
309void kdp_register_link(kdp_link_t link, kdp_mode_t mode)
310{
311        kdp_en_linkstatus = link;
312        kdp_en_setmode    = mode;
313}
314
315void kdp_unregister_link(__unused kdp_link_t link, __unused kdp_mode_t mode)
316{
317        kdp_en_linkstatus = NULL;
318        kdp_en_setmode    = NULL;
319}
320
321void
322kdp_register_send_receive(
323	kdp_send_t	send,
324	kdp_receive_t	receive)
325{
326	unsigned int	debug = 0;
327
328	PE_parse_boot_argn("debug", &debug, sizeof (debug));
329
330	if (!debug)
331		return;
332
333	kdp_en_send_pkt   = send;
334	kdp_en_recv_pkt   = receive;
335
336	if (debug & DB_KDP_BP_DIS)
337		kdp_flag |= KDP_BP_DIS;
338	if (debug & DB_KDP_GETC_ENA)
339		kdp_flag |= KDP_GETC_ENA;
340	if (debug & DB_ARP)
341		kdp_flag |= KDP_ARP;
342
343	if (debug & DB_KERN_DUMP_ON_PANIC)
344		kdp_flag |= KDP_PANIC_DUMP_ENABLED;
345	if (debug & DB_KERN_DUMP_ON_NMI)
346		kdp_flag |= PANIC_CORE_ON_NMI;
347
348	if (debug & DB_DBG_POST_CORE)
349		kdp_flag |= DBG_POST_CORE;
350
351	if (debug & DB_PANICLOG_DUMP)
352		kdp_flag |= PANIC_LOG_DUMP;
353
354	if (PE_parse_boot_argn("_panicd_ip", panicd_ip_str, sizeof (panicd_ip_str)))
355		panicd_specified = TRUE;
356
357	if ((debug & DB_REBOOT_POST_CORE) && (panicd_specified == TRUE))
358		kdp_flag |= REBOOT_POST_CORE;
359
360	if (PE_parse_boot_argn("_router_ip", router_ip_str, sizeof (router_ip_str)))
361		router_specified = TRUE;
362
363	if (!PE_parse_boot_argn("panicd_port", &panicd_port, sizeof (panicd_port)))
364		panicd_port = CORE_REMOTE_PORT;
365
366	if (PE_parse_boot_argn("_panicd_corename", &corename_str, sizeof (corename_str)))
367		corename_specified = TRUE;
368
369	kdp_flag |= KDP_READY;
370	if (current_debugger == NO_CUR_DB)
371		current_debugger = KDP_CUR_DB;
372	if ((kdp_current_ip_address != 0) && halt_in_debugger) {
373		kdp_call();
374		halt_in_debugger=0;
375	}
376}
377
378void
379kdp_unregister_send_receive(
380	__unused kdp_send_t	send,
381	__unused kdp_receive_t	receive)
382{
383	if (current_debugger == KDP_CUR_DB)
384		current_debugger = NO_CUR_DB;
385	kdp_flag &= ~KDP_READY;
386	kdp_en_send_pkt   = NULL;
387	kdp_en_recv_pkt   = NULL;
388}
389
390/* Cache stack snapshot parameters in preparation for a trace */
391void
392kdp_snapshot_preflight(int pid, void * tracebuf, uint32_t tracebuf_size, uint32_t flags, uint32_t dispatch_offset)
393{
394	stack_snapshot_pid = pid;
395	stack_snapshot_buf = tracebuf;
396	stack_snapshot_bufsize = tracebuf_size;
397	stack_snapshot_flags = flags;
398	stack_snapshot_dispatch_offset = dispatch_offset;
399	kdp_snapshot++;
400	/* Mark this debugger as active, since the polled mode driver that
401	 * ordinarily does this may not be enabled (yet), or since KDB may be
402	 * the primary debugger.
403	 */
404	old_debugger = current_debugger;
405	if (old_debugger != KDP_CUR_DB) {
406		current_debugger = KDP_CUR_DB;
407	}
408}
409
410void
411kdp_snapshot_postflight(void)
412{
413	kdp_snapshot--;
414	if ((kdp_en_send_pkt == NULL) || (old_debugger == KDB_CUR_DB))
415		current_debugger = old_debugger;
416}
417
418int
419kdp_stack_snapshot_geterror(void)
420{
421	return stack_snapshot_ret;
422}
423
424int
425kdp_stack_snapshot_bytes_traced(void)
426{
427	return stack_snapshot_bytes_traced;
428}
429
430static void
431kdp_schedule_debugger_reentry(unsigned interval) {
432	uint64_t deadline;;
433
434	clock_interval_to_deadline(interval, 1000 * 1000, &deadline);
435	thread_call_enter_delayed(kdp_timer_call, deadline);
436}
437
438static void
439enaddr_copy(
440	void	*src,
441	void	*dst
442)
443{
444	bcopy((char *)src, (char *)dst, sizeof (struct ether_addr));
445}
446
447static unsigned short
448ip_sum(
449	unsigned char	*c,
450	unsigned int	hlen
451	)
452{
453	unsigned int	high, low, sum;
454
455	high = low = 0;
456	while (hlen-- > 0) {
457		low += c[1] + c[3];
458		high += c[0] + c[2];
459
460		c += sizeof (int);
461	}
462
463	sum = (high << 8) + low;
464	sum = (sum >> 16) + (sum & 65535);
465
466	return (sum > 65535 ? sum - 65535 : sum);
467}
468
469static void
470kdp_reply(
471          unsigned short		reply_port,
472          const boolean_t         sideband
473          )
474{
475	struct udpiphdr		aligned_ui, *ui = &aligned_ui;
476	struct ip		aligned_ip, *ip = &aligned_ip;
477	struct in_addr		tmp_ipaddr;
478	struct ether_addr	tmp_enaddr;
479	struct ether_header	*eh = NULL;
480
481	if (!pkt.input)
482		kdp_panic("kdp_reply");
483
484	pkt.off -= (unsigned int)sizeof (struct udpiphdr);
485
486#if DO_ALIGN
487	bcopy((char *)&pkt.data[pkt.off], (char *)ui, sizeof(*ui));
488#else
489	ui = (struct udpiphdr *)&pkt.data[pkt.off];
490#endif
491	ui->ui_next = ui->ui_prev = 0;
492	ui->ui_x1 = 0;
493	ui->ui_pr = IPPROTO_UDP;
494	ui->ui_len = htons((u_short)pkt.len + sizeof (struct udphdr));
495	tmp_ipaddr = ui->ui_src;
496	ui->ui_src = ui->ui_dst;
497	ui->ui_dst = tmp_ipaddr;
498	ui->ui_sport = htons(KDP_REMOTE_PORT);
499	ui->ui_dport = reply_port;
500	ui->ui_ulen = ui->ui_len;
501	ui->ui_sum = 0;
502#if DO_ALIGN
503	bcopy((char *)ui, (char *)&pkt.data[pkt.off], sizeof(*ui));
504	bcopy((char *)&pkt.data[pkt.off], (char *)ip, sizeof(*ip));
505#else
506	ip = (struct ip *)&pkt.data[pkt.off];
507#endif
508	ip->ip_len = htons(sizeof (struct udpiphdr) + pkt.len);
509	ip->ip_v = IPVERSION;
510	ip->ip_id = htons(ip_id++);
511	ip->ip_hl = sizeof (struct ip) >> 2;
512	ip->ip_ttl = udp_ttl;
513	ip->ip_sum = 0;
514	ip->ip_sum = htons(~ip_sum((unsigned char *)ip, ip->ip_hl));
515#if DO_ALIGN
516	bcopy((char *)ip, (char *)&pkt.data[pkt.off], sizeof(*ip));
517#endif
518
519	pkt.len += (unsigned int)sizeof (struct udpiphdr);
520
521	pkt.off -= (unsigned int)sizeof (struct ether_header);
522
523	eh = (struct ether_header *)&pkt.data[pkt.off];
524	enaddr_copy(eh->ether_shost, &tmp_enaddr);
525	enaddr_copy(eh->ether_dhost, eh->ether_shost);
526	enaddr_copy(&tmp_enaddr, eh->ether_dhost);
527	eh->ether_type = htons(ETHERTYPE_IP);
528
529	pkt.len += (unsigned int)sizeof (struct ether_header);
530
531	// save reply for possible retransmission
532	assert(pkt.len <= KDP_MAXPACKET);
533	if (!sideband)
534		bcopy((char *)&pkt, (char *)&saved_reply, sizeof(saved_reply));
535
536	kdp_send_data(&pkt.data[pkt.off], pkt.len);
537
538	// increment expected sequence number
539	if (!sideband)
540		exception_seq++;
541}
542
543static void
544kdp_send(
545    unsigned short		remote_port
546)
547{
548    struct udpiphdr		aligned_ui, *ui = &aligned_ui;
549    struct ip			aligned_ip, *ip = &aligned_ip;
550    struct ether_header		*eh;
551
552    if (pkt.input)
553	kdp_panic("kdp_send");
554
555    pkt.off -= (unsigned int)sizeof (struct udpiphdr);
556
557#if DO_ALIGN
558    bcopy((char *)&pkt.data[pkt.off], (char *)ui, sizeof(*ui));
559#else
560    ui = (struct udpiphdr *)&pkt.data[pkt.off];
561#endif
562    ui->ui_next = ui->ui_prev = 0;
563    ui->ui_x1 = 0;
564    ui->ui_pr = IPPROTO_UDP;
565    ui->ui_len = htons((u_short)pkt.len + sizeof (struct udphdr));
566    ui->ui_src = adr.loc.in;
567    ui->ui_dst = adr.rmt.in;
568    ui->ui_sport = htons(KDP_REMOTE_PORT);
569    ui->ui_dport = remote_port;
570    ui->ui_ulen = ui->ui_len;
571    ui->ui_sum = 0;
572#if DO_ALIGN
573    bcopy((char *)ui, (char *)&pkt.data[pkt.off], sizeof(*ui));
574    bcopy((char *)&pkt.data[pkt.off], (char *)ip, sizeof(*ip));
575#else
576    ip = (struct ip *)&pkt.data[pkt.off];
577#endif
578    ip->ip_len = htons(sizeof (struct udpiphdr) + pkt.len);
579    ip->ip_v = IPVERSION;
580    ip->ip_id = htons(ip_id++);
581    ip->ip_hl = sizeof (struct ip) >> 2;
582    ip->ip_ttl = udp_ttl;
583    ip->ip_sum = 0;
584    ip->ip_sum = htons(~ip_sum((unsigned char *)ip, ip->ip_hl));
585#if DO_ALIGN
586    bcopy((char *)ip, (char *)&pkt.data[pkt.off], sizeof(*ip));
587#endif
588
589    pkt.len += (unsigned int)sizeof (struct udpiphdr);
590
591    pkt.off -= (unsigned int)sizeof (struct ether_header);
592
593    eh = (struct ether_header *)&pkt.data[pkt.off];
594    enaddr_copy(&adr.loc.ea, eh->ether_shost);
595    enaddr_copy(&adr.rmt.ea, eh->ether_dhost);
596    eh->ether_type = htons(ETHERTYPE_IP);
597
598    pkt.len += (unsigned int)sizeof (struct ether_header);
599    kdp_send_data(&pkt.data[pkt.off], pkt.len);
600}
601
602
603inline static void debugger_if_necessary(void)
604{
605    if ((current_debugger == KDP_CUR_DB) && halt_in_debugger) {
606        kdp_call();
607        halt_in_debugger=0;
608    }
609}
610
611
612/* We don't interpret this pointer, we just give it to the bsd stack
613   so it can decide when to set the MAC and IP info. We'll
614   early initialize the MAC/IP info if we can so that we can use
615   KDP early in boot. These values may subsequently get over-written
616   when the interface gets initialized for real.
617*/
618void
619kdp_set_interface(void *ifp, const struct ether_addr *macaddr)
620{
621	char kdpstr[80];
622        struct in_addr addr = { 0 };
623        unsigned int len;
624
625	kdp_current_ifp = ifp;
626
627        if (PE_parse_boot_argn("kdp_ip_addr", kdpstr, sizeof(kdpstr))) {
628            /* look for a static ip address */
629            if (inet_aton(kdpstr, &addr) == FALSE)
630                goto done;
631
632            goto config_network;
633        }
634
635        /* use saved ip address */
636        save_ip_in_nvram = TRUE;
637
638        len = sizeof(kdpstr);
639        if (PEReadNVRAMProperty("_kdp_ipstr", kdpstr, &len) == FALSE)
640            goto done;
641
642        kdpstr[len < sizeof(kdpstr) ? len : sizeof(kdpstr) - 1] = '\0';
643        if (inet_aton(kdpstr, &addr) == FALSE)
644            goto done;
645
646config_network:
647        kdp_current_ip_address = addr.s_addr;
648        if (macaddr)
649            kdp_current_mac_address = *macaddr;
650
651        /* we can't drop into the debugger at this point because the
652           link will likely not be up. when getDebuggerLinkStatus() support gets
653           added to the appropriate network drivers, adding the
654           following will enable this capability:
655           debugger_if_necessary();
656        */
657done:
658        return;
659}
660
661void *
662kdp_get_interface(void)
663{
664	return kdp_current_ifp;
665}
666
667void
668kdp_set_ip_and_mac_addresses(
669	struct in_addr		*ipaddr,
670	struct ether_addr	*macaddr)
671{
672        static uint64_t last_time    = (uint64_t) -1;
673        static uint64_t throttle_val = 0;
674        uint64_t cur_time;
675        char addr[16];
676
677        if (kdp_current_ip_address == ipaddr->s_addr)
678            goto done;
679
680        /* don't replace if serial debugging is configured */
681        if (!KDP_SERIAL_ENABLED() ||
682            (kdp_current_ip_address != KDP_SERIAL_IPADDR)) {
683            kdp_current_mac_address = *macaddr;
684            kdp_current_ip_address  = ipaddr->s_addr;
685        }
686
687        if (save_ip_in_nvram == FALSE)
688            goto done;
689
690        if (inet_ntoa2(ipaddr, addr, sizeof(addr)) == FALSE)
691            goto done;
692
693        /* throttle writes if needed */
694        if (!throttle_val)
695            nanoseconds_to_absolutetime(KDP_THROTTLE_VALUE, &throttle_val);
696
697        cur_time = mach_absolute_time();
698        if (last_time == (uint64_t) -1 ||
699            ((cur_time - last_time) > throttle_val)) {
700            PEWriteNVRAMProperty("_kdp_ipstr", addr,
701                                 (const unsigned int) strlen(addr));
702        }
703        last_time = cur_time;
704
705done:
706        debugger_if_necessary();
707}
708
709void
710kdp_set_gateway_mac(void *gatewaymac)
711{
712    router_mac = *(struct ether_addr *)gatewaymac;
713    flag_router_mac_initialized = TRUE;
714}
715
716struct ether_addr
717kdp_get_mac_addr(void)
718{
719  return kdp_current_mac_address;
720}
721
722unsigned int
723kdp_get_ip_address(void)
724{
725  return (unsigned int)kdp_current_ip_address;
726}
727
728void
729kdp_disable_arp(void)
730{
731	kdp_flag &= ~(DB_ARP);
732}
733
734static void
735kdp_arp_dispatch(void)
736{
737	struct ether_arp	aligned_ea, *ea = &aligned_ea;
738	unsigned		arp_header_offset;
739
740	arp_header_offset = (unsigned)sizeof(struct ether_header) + pkt.off;
741	memcpy((void *)ea, (void *)&pkt.data[arp_header_offset], sizeof(*ea));
742
743	switch(ntohs(ea->arp_op)) {
744	case ARPOP_REQUEST:
745		kdp_arp_reply(ea);
746		break;
747	case ARPOP_REPLY:
748		kdp_process_arp_reply(ea);
749		break;
750	default:
751		return;
752	}
753}
754
755static void
756kdp_process_arp_reply(struct ether_arp *ea)
757{
758	/* Are we interested in ARP replies? */
759	if (flag_arp_resolved == TRUE)
760		return;
761
762	/* Did we receive a reply from the right source? */
763	if (((struct in_addr *)(ea->arp_spa))->s_addr != target_ip)
764	  return;
765
766	flag_arp_resolved = TRUE;
767	current_resolved_MAC = *(struct ether_addr *) (ea->arp_sha);
768
769	return;
770}
771
772/* ARP responses are enabled when the DB_ARP bit of the debug boot arg
773 * is set.
774 */
775
776static void
777kdp_arp_reply(struct ether_arp *ea)
778{
779	struct ether_header	*eh;
780
781	struct in_addr 		isaddr, itaddr, myaddr;
782	struct ether_addr	my_enaddr;
783
784	eh = (struct ether_header *)&pkt.data[pkt.off];
785	pkt.off += (unsigned int)sizeof(struct ether_header);
786
787	if(ntohs(ea->arp_op) != ARPOP_REQUEST)
788	  return;
789
790	myaddr.s_addr = kdp_get_ip_address();
791	my_enaddr = kdp_get_mac_addr();
792
793	if ((ntohl(myaddr.s_addr) == 0) ||
794	    ((my_enaddr.ether_addr_octet[0] & 0xff) == 0
795		 && (my_enaddr.ether_addr_octet[1] & 0xff) == 0
796		 && (my_enaddr.ether_addr_octet[2] & 0xff) == 0
797		 && (my_enaddr.ether_addr_octet[3] & 0xff) == 0
798		 && (my_enaddr.ether_addr_octet[4] & 0xff) == 0
799		 && (my_enaddr.ether_addr_octet[5] & 0xff) == 0
800		 ))
801		return;
802
803	(void)memcpy((void *)&isaddr, (void *)ea->arp_spa, sizeof (isaddr));
804	(void)memcpy((void *)&itaddr, (void *)ea->arp_tpa, sizeof (itaddr));
805
806	if (itaddr.s_addr == myaddr.s_addr) {
807		(void)memcpy((void *)ea->arp_tha, (void *)ea->arp_sha, sizeof(ea->arp_sha));
808		(void)memcpy((void *)ea->arp_sha, (void *)&my_enaddr, sizeof(ea->arp_sha));
809
810		(void)memcpy((void *)ea->arp_tpa, (void *) ea->arp_spa, sizeof(ea->arp_spa));
811		(void)memcpy((void *)ea->arp_spa, (void *) &itaddr, sizeof(ea->arp_spa));
812
813		ea->arp_op = htons(ARPOP_REPLY);
814		ea->arp_pro = htons(ETHERTYPE_IP);
815		(void)memcpy(eh->ether_dhost, ea->arp_tha, sizeof(eh->ether_dhost));
816		(void)memcpy(eh->ether_shost, &my_enaddr, sizeof(eh->ether_shost));
817		eh->ether_type = htons(ETHERTYPE_ARP);
818		(void)memcpy(&pkt.data[pkt.off], ea, sizeof(*ea));
819		pkt.off -= (unsigned int)sizeof (struct ether_header);
820		/* pkt.len is still the length we want, ether_header+ether_arp */
821		kdp_send_data(&pkt.data[pkt.off], pkt.len);
822	}
823}
824
825static void
826kdp_poll(void)
827{
828	struct ether_header	*eh = NULL;
829	struct udpiphdr		aligned_ui, *ui = &aligned_ui;
830	struct ip		aligned_ip, *ip = &aligned_ip;
831	static int		msg_printed;
832
833	if (pkt.input)
834		kdp_panic("kdp_poll");
835
836	if (!kdp_en_recv_pkt || !kdp_en_send_pkt) {
837		if( msg_printed == 0) {
838			msg_printed = 1;
839			printf("kdp_poll: no debugger device\n");
840		}
841		return;
842	}
843
844	pkt.off = pkt.len = 0;
845	kdp_receive_data(pkt.data, &pkt.len, 3/* ms */);
846
847	if (pkt.len == 0)
848		return;
849
850	if (pkt.len >= sizeof(struct ether_header))
851	{
852		eh = (struct ether_header *)&pkt.data[pkt.off];
853
854		if (kdp_flag & KDP_ARP)
855		{
856			if (ntohs(eh->ether_type) == ETHERTYPE_ARP)
857			{
858				kdp_arp_dispatch();
859				return;
860			}
861		}
862	}
863
864	if (pkt.len < (sizeof (struct ether_header) + sizeof (struct udpiphdr)))
865		return;
866
867	pkt.off += (unsigned int)sizeof (struct ether_header);
868	if (ntohs(eh->ether_type) != ETHERTYPE_IP) {
869		return;
870	}
871
872#if DO_ALIGN
873	bcopy((char *)&pkt.data[pkt.off], (char *)ui, sizeof(*ui));
874	bcopy((char *)&pkt.data[pkt.off], (char *)ip, sizeof(*ip));
875#else
876	ui = (struct udpiphdr *)&pkt.data[pkt.off];
877	ip = (struct ip *)&pkt.data[pkt.off];
878#endif
879
880	pkt.off += (unsigned int)sizeof (struct udpiphdr);
881	if (ui->ui_pr != IPPROTO_UDP) {
882		return;
883	}
884
885	if (ip->ip_hl > (sizeof (struct ip) >> 2)) {
886		return;
887	}
888
889	if (ntohs(ui->ui_dport) != KDP_REMOTE_PORT) {
890		if (panicd_port == (ntohs(ui->ui_dport)) &&
891		    flag_panic_dump_in_progress) {
892			last_panic_port = ui->ui_sport;
893		}
894		else
895			return;
896	}
897	/* If we receive a kernel debugging packet whilst a
898	 * core dump is in progress, abort the transfer and
899	 * enter the debugger if not told otherwise.
900	 */
901	else
902		if (flag_panic_dump_in_progress)
903		{
904			if (!flag_dont_abort_panic_dump) {
905				abort_panic_transfer();
906			}
907			return;
908		}
909
910	if (!kdp.is_conn && !flag_panic_dump_in_progress) {
911		enaddr_copy(eh->ether_dhost, &adr.loc.ea);
912		adr.loc.in = ui->ui_dst;
913
914		enaddr_copy(eh->ether_shost, &adr.rmt.ea);
915		adr.rmt.in = ui->ui_src;
916	}
917
918	/*
919	 * Calculate kdp packet length.
920	 */
921	pkt.len = ntohs((u_short)ui->ui_ulen) - (unsigned int)sizeof (struct udphdr);
922	pkt.input = TRUE;
923}
924
925/* Create and transmit an ARP resolution request for the target IP address.
926 * This is modeled on ether_inet_arp()/RFC 826.
927 */
928
929static void
930transmit_ARP_request(uint32_t ip_addr)
931{
932	struct ether_header	*eh = (struct ether_header *) &pkt.data[0];
933	struct ether_arp	*ea = (struct ether_arp *) &pkt.data[sizeof(struct ether_header)];
934
935 	KDP_DEBUG("Transmitting ARP request\n");
936	/* Populate the ether_header */
937	eh->ether_type = htons(ETHERTYPE_ARP);
938	enaddr_copy(&kdp_current_mac_address, eh->ether_shost);
939	enaddr_copy(&etherbroadcastaddr, eh->ether_dhost);
940
941	/* Populate the ARP header */
942	ea->arp_pro = htons(ETHERTYPE_IP);
943	ea->arp_hln = sizeof(ea->arp_sha);
944	ea->arp_pln = sizeof(ea->arp_spa);
945	ea->arp_hrd = htons(ARPHRD_ETHER);
946	ea->arp_op = htons(ARPOP_REQUEST);
947
948	/* Target fields */
949	enaddr_copy(&etherbroadcastaddr, ea->arp_tha);
950	memcpy(ea->arp_tpa, (void *) &ip_addr, sizeof(ip_addr));
951
952	/* Source fields */
953	enaddr_copy(&kdp_current_mac_address, ea->arp_sha);
954	memcpy(ea->arp_spa, (void *) &kdp_current_ip_address, sizeof(kdp_current_ip_address));
955
956	pkt.off = 0;
957	pkt.len = sizeof(struct ether_header) + sizeof(struct ether_arp);
958	/* Transmit */
959	kdp_send_data(&pkt.data[pkt.off], pkt.len);
960}
961
962static boolean_t
963kdp_arp_resolve(uint32_t arp_target_ip, struct ether_addr *resolved_MAC)
964{
965	int poll_count = 256; /* ~770 ms modulo broadcast/delayed traffic? */
966	char tretries = 0;
967
968#define NUM_ARP_TX_RETRIES 5
969
970	target_ip = arp_target_ip;
971	flag_arp_resolved = FALSE;
972
973TRANSMIT_RETRY:
974	pkt.off = pkt.len = 0;
975
976	tretries++;
977
978	if (tretries >= NUM_ARP_TX_RETRIES) {
979		return FALSE;
980	}
981
982	KDP_DEBUG("ARP TX attempt #%d \n", tretries);
983
984	transmit_ARP_request(arp_target_ip);
985
986	while (!pkt.input && !flag_arp_resolved && flag_panic_dump_in_progress && --poll_count) {
987		kdp_poll();
988	}
989
990	if (flag_arp_resolved) {
991		*resolved_MAC = current_resolved_MAC;
992		return TRUE;
993	}
994
995	if (!flag_panic_dump_in_progress || pkt.input) /* we received a debugging packet, bail*/
996	{
997		printf("Received a debugger packet,transferring control to debugger\n");
998		/* Indicate that we should wait in the debugger when we return */
999		kdp_flag |= DBG_POST_CORE;
1000		pkt.input = FALSE;
1001		return FALSE;
1002	}
1003	else /* We timed out */
1004		if (0 == poll_count) {
1005			poll_count = 256;
1006			goto TRANSMIT_RETRY;
1007		}
1008	return FALSE;
1009}
1010
1011static void
1012kdp_handler(
1013    void	*saved_state
1014)
1015{
1016    unsigned short		reply_port;
1017    kdp_hdr_t			aligned_hdr, *hdr = &aligned_hdr;
1018
1019    kdp.saved_state = saved_state;  // see comment in kdp_raise_exception
1020
1021    do {
1022	while (!pkt.input)
1023	    kdp_poll();
1024
1025#if DO_ALIGN
1026	bcopy((char *)&pkt.data[pkt.off], (char *)hdr, sizeof(*hdr));
1027#else
1028	hdr = (kdp_hdr_t *)&pkt.data[pkt.off];
1029#endif
1030
1031	// ignore replies -- we're not expecting them anyway.
1032	if (hdr->is_reply) {
1033	    goto again;
1034	}
1035
1036	if (hdr->request == KDP_REATTACH)
1037	  exception_seq = hdr->seq;
1038
1039	// check for retransmitted request
1040	if (hdr->seq == (exception_seq - 1)) {
1041	    /* retransmit last reply */
1042	    kdp_send_data(&saved_reply.data[saved_reply.off],
1043                          saved_reply.len);
1044	    goto again;
1045	} else if ((hdr->seq != exception_seq) &&
1046                   (hdr->request != KDP_CONNECT)) {
1047	    printf("kdp: bad sequence %d (want %d)\n",
1048			hdr->seq, exception_seq);
1049	    goto again;
1050	}
1051
1052	/* This is a manual side-channel to the main KDP protocol.
1053	 * A client like GDB/kgmacros can manually construct
1054	 * a request, set the input flag, issue a dummy KDP request,
1055	 * and then manually collect the result
1056	 */
1057	if (manual_pkt.input) {
1058	  kdp_hdr_t *manual_hdr = (kdp_hdr_t *)&manual_pkt.data;
1059	  unsigned short manual_port_unused = 0;
1060	  if (!manual_hdr->is_reply) {
1061	    /* process */
1062	    kdp_packet((unsigned char *)&manual_pkt.data,
1063		       (int *)&manual_pkt.len,
1064		       &manual_port_unused);
1065	  }
1066	  manual_pkt.input = 0;
1067	}
1068
1069	if (kdp_packet((unsigned char*)&pkt.data[pkt.off],
1070			(int *)&pkt.len,
1071			(unsigned short *)&reply_port)) {
1072            boolean_t sideband = FALSE;
1073
1074            /* if it's an already connected error message,
1075             * send a sideband reply for that. for successful connects,
1076             * make sure the sequence number is correct. */
1077            if (hdr->request == KDP_CONNECT) {
1078                kdp_connect_reply_t *rp =
1079			(kdp_connect_reply_t *) &pkt.data[pkt.off];
1080                kdp_error_t err = rp->error;
1081
1082                if (err == KDPERR_NO_ERROR) {
1083                    exception_seq = hdr->seq;
1084                } else if (err == KDPERR_ALREADY_CONNECTED) {
1085                    sideband = TRUE;
1086                }
1087            }
1088
1089	    kdp_reply(reply_port, sideband);
1090	}
1091
1092again:
1093	pkt.input = FALSE;
1094    } while (kdp.is_halted);
1095}
1096
1097static void
1098kdp_connection_wait(void)
1099{
1100	unsigned short		reply_port;
1101	struct ether_addr	kdp_mac_addr = kdp_get_mac_addr();
1102	unsigned int		ip_addr = ntohl(kdp_get_ip_address());
1103
1104	/*
1105	 * Do both a printf() and a kprintf() of the MAC and IP so that
1106	 * they will print out on headless machines but not be added to
1107	 * the panic.log
1108	 */
1109
1110#ifdef __arm__
1111	 /* Serial KDP must be enabled always. */
1112	 if(!KDP_SERIAL_ENABLED())
1113	 	return;
1114#endif
1115
1116        if (KDP_SERIAL_ENABLED()) {
1117            printf("Using serial KDP.\n");
1118            kprintf("Using serial KDP.\n");
1119        } else {
1120            printf( "ethernet MAC address: %02x:%02x:%02x:%02x:%02x:%02x\n",
1121                    kdp_mac_addr.ether_addr_octet[0] & 0xff,
1122                    kdp_mac_addr.ether_addr_octet[1] & 0xff,
1123                    kdp_mac_addr.ether_addr_octet[2] & 0xff,
1124                    kdp_mac_addr.ether_addr_octet[3] & 0xff,
1125                    kdp_mac_addr.ether_addr_octet[4] & 0xff,
1126                    kdp_mac_addr.ether_addr_octet[5] & 0xff);
1127
1128            kprintf( "ethernet MAC address: %02x:%02x:%02x:%02x:%02x:%02x\n",
1129                     kdp_mac_addr.ether_addr_octet[0] & 0xff,
1130                     kdp_mac_addr.ether_addr_octet[1] & 0xff,
1131                     kdp_mac_addr.ether_addr_octet[2] & 0xff,
1132                     kdp_mac_addr.ether_addr_octet[3] & 0xff,
1133                     kdp_mac_addr.ether_addr_octet[4] & 0xff,
1134                     kdp_mac_addr.ether_addr_octet[5] & 0xff);
1135
1136            printf( "ip address: %d.%d.%d.%d\n",
1137                    (ip_addr & 0xff000000) >> 24,
1138                    (ip_addr & 0xff0000) >> 16,
1139                    (ip_addr & 0xff00) >> 8,
1140                    (ip_addr & 0xff));
1141
1142            kprintf( "ip address: %d.%d.%d.%d\n",
1143                     (ip_addr & 0xff000000) >> 24,
1144                     (ip_addr & 0xff0000) >> 16,
1145                     (ip_addr & 0xff00) >> 8,
1146                     (ip_addr & 0xff));
1147        }
1148
1149	printf("\nWaiting for remote debugger connection.\n");
1150	kprintf("\nWaiting for remote debugger connection.\n");
1151
1152#ifdef __arm__
1153	printf("\nPlease go to http://github.com/winocm/xnu to report this panic.\n");
1154	kprintf("\nPlease go to http://github.com/winocm/xnu to report this panic.\n");
1155#endif
1156
1157	if (reattach_wait == 0) {
1158		if((kdp_flag & KDP_GETC_ENA) && (0 != kdp_getc()))
1159		{
1160			printf("Options.....    Type\n");
1161			printf("------------    ----\n");
1162			printf("continue....    'c'\n");
1163			printf("reboot......    'r'\n");
1164		}
1165	} else
1166		reattach_wait = 0;
1167
1168	exception_seq = 0;
1169
1170	do {
1171		kdp_hdr_t aligned_hdr, *hdr = &aligned_hdr;
1172
1173		while (!pkt.input) {
1174			if (kdp_flag & KDP_GETC_ENA) {
1175				switch(kdp_getc()) {
1176				case 'c':
1177					printf("Continuing...\n");
1178					return;
1179				case 'r':
1180					printf("Rebooting...\n");
1181					kdp_machine_reboot();
1182					break;
1183				default:
1184					break;
1185		    		}
1186			}
1187			kdp_poll();
1188		}
1189
1190#if DO_ALIGN
1191		bcopy((char *)&pkt.data[pkt.off], (char *)hdr, sizeof(*hdr));
1192#else
1193		hdr = (kdp_hdr_t *)&pkt.data[pkt.off];
1194#endif
1195		if (hdr->request == KDP_HOSTREBOOT) {
1196			kdp_machine_reboot();
1197			/* should not return! */
1198		}
1199		if (((hdr->request == KDP_CONNECT) || (hdr->request == KDP_REATTACH)) &&
1200			!hdr->is_reply && (hdr->seq == exception_seq)) {
1201		    if (kdp_packet((unsigned char *)&pkt.data[pkt.off],
1202				(int *)&pkt.len,
1203				(unsigned short *)&reply_port))
1204			    kdp_reply(reply_port, FALSE);
1205		    if (hdr->request == KDP_REATTACH) {
1206				reattach_wait = 0;
1207				hdr->request=KDP_DISCONNECT;
1208				exception_seq = 0;
1209			}
1210		}
1211
1212		pkt.input = FALSE;
1213	} while (!kdp.is_conn);
1214
1215	if (current_debugger == KDP_CUR_DB)
1216		active_debugger=1;
1217	printf("Connected to remote debugger.\n");
1218	kprintf("Connected to remote debugger.\n");
1219}
1220
1221static void
1222kdp_send_exception(
1223    unsigned int		exception,
1224    unsigned int		code,
1225    unsigned int		subcode
1226)
1227{
1228    unsigned short		remote_port;
1229    unsigned int		timeout_count = 100;
1230    unsigned int                poll_timeout;
1231
1232    do {
1233	pkt.off = sizeof (struct ether_header) + sizeof (struct udpiphdr);
1234	kdp_exception((unsigned char *)&pkt.data[pkt.off],
1235			(int *)&pkt.len,
1236			(unsigned short *)&remote_port,
1237			(unsigned int)exception,
1238			(unsigned int)code,
1239			(unsigned int)subcode);
1240
1241	kdp_send(remote_port);
1242
1243	poll_timeout = 50;
1244	while(!pkt.input && poll_timeout)
1245	  {
1246	    kdp_poll();
1247	    poll_timeout--;
1248	  }
1249
1250	if (pkt.input) {
1251	    if (!kdp_exception_ack(&pkt.data[pkt.off], pkt.len)) {
1252		pkt.input = FALSE;
1253	    }
1254	}
1255
1256	pkt.input = FALSE;
1257
1258	if (kdp.exception_ack_needed)
1259	    kdp_us_spin(250000);
1260
1261    } while (kdp.exception_ack_needed && timeout_count--);
1262
1263    if (kdp.exception_ack_needed) {
1264	// give up & disconnect
1265	printf("kdp: exception ack timeout\n");
1266	if (current_debugger == KDP_CUR_DB)
1267    	active_debugger=0;
1268	kdp_reset();
1269    }
1270}
1271
1272void
1273kdp_raise_exception(
1274    unsigned int		exception,
1275    unsigned int		code,
1276    unsigned int		subcode,
1277    void			*saved_state
1278)
1279{
1280    int			index;
1281    unsigned int	initial_not_in_kdp = not_in_kdp;
1282
1283    not_in_kdp = 0;
1284    /* Was a system trace requested ? */
1285    if (kdp_snapshot && (!panic_active()) && (panic_caller == 0)) {
1286	    stack_snapshot_ret = kdp_stackshot(stack_snapshot_pid,
1287	    stack_snapshot_buf, stack_snapshot_bufsize,
1288	    stack_snapshot_flags, stack_snapshot_dispatch_offset,
1289		&stack_snapshot_bytes_traced);
1290	    not_in_kdp = initial_not_in_kdp;
1291	    return;
1292    }
1293
1294    disable_preemption();
1295
1296    if (saved_state == 0)
1297	printf("kdp_raise_exception with NULL state\n");
1298
1299    index = exception;
1300    if (exception != EXC_BREAKPOINT) {
1301	if (exception > EXC_BREAKPOINT || exception < EXC_BAD_ACCESS) {
1302	    index = 0;
1303	}
1304	printf("%s exception (%x,%x,%x)\n",
1305		exception_message[index],
1306		exception, code, subcode);
1307    }
1308
1309    kdp_sync_cache();
1310
1311    /* XXX WMG it seems that sometimes it doesn't work to let kdp_handler
1312     * do this. I think the client and the host can get out of sync.
1313     */
1314    kdp.saved_state = saved_state;
1315    kdp.kdp_cpu = cpu_number();
1316    kdp.kdp_thread = current_thread();
1317
1318    if (kdp_en_setmode)
1319        (*kdp_en_setmode)(TRUE); /* enabling link mode */
1320
1321    if (pkt.input)
1322	kdp_panic("kdp_raise_exception");
1323
1324    if (((kdp_flag & KDP_PANIC_DUMP_ENABLED) || (kdp_flag & PANIC_LOG_DUMP))
1325	&& (panicstr != (char *) 0)) {
1326	    kdp_panic_dump();
1327	    if (kdp_flag & REBOOT_POST_CORE)
1328		    kdp_machine_reboot();
1329      }
1330    else
1331      if ((kdp_flag & PANIC_CORE_ON_NMI) && (panicstr == (char *) 0) &&
1332	  !kdp.is_conn) {
1333
1334	disable_debug_output = disableConsoleOutput = FALSE;
1335	kdp_panic_dump();
1336
1337	if (!(kdp_flag & DBG_POST_CORE))
1338	  goto exit_raise_exception;
1339      }
1340
1341 again:
1342    if (!kdp.is_conn)
1343	kdp_connection_wait();
1344    else {
1345	kdp_send_exception(exception, code, subcode);
1346	if (kdp.exception_ack_needed) {
1347	    kdp.exception_ack_needed = FALSE;
1348	    kdp_remove_all_breakpoints();
1349	    printf("Remote debugger disconnected.\n");
1350	  }
1351      }
1352
1353    if (kdp.is_conn) {
1354	kdp.is_halted = TRUE;		/* XXX */
1355	kdp_handler(saved_state);
1356	if (!kdp.is_conn)
1357	  {
1358	    kdp_remove_all_breakpoints();
1359	    printf("Remote debugger disconnected.\n");
1360	  }
1361    }
1362    /* Allow triggering a panic core dump when connected to the machine
1363     * Continuing after setting kdp_trigger_core_dump should do the
1364     * trick.
1365     */
1366
1367    if (1 == kdp_trigger_core_dump) {
1368	kdp_flag |= KDP_PANIC_DUMP_ENABLED;
1369	kdp_panic_dump();
1370	if (kdp_flag & REBOOT_POST_CORE)
1371		kdp_machine_reboot();
1372	kdp_trigger_core_dump = 0;
1373      }
1374
1375/* Trigger a reboot if the user has set this flag through the
1376 * debugger.Ideally, this would be done through the HOSTREBOOT packet
1377 * in the protocol,but that will need gdb support,and when it's
1378 * available, it should work automatically.
1379 */
1380    if (1 == flag_kdp_trigger_reboot) {
1381	    kdp_machine_reboot();
1382	    /* If we're still around, reset the flag */
1383	    flag_kdp_trigger_reboot = 0;
1384    }
1385
1386    if (kdp_reentry_deadline) {
1387	    kdp_schedule_debugger_reentry(kdp_reentry_deadline);
1388	    printf("Debugger re-entry scheduled in %d milliseconds\n", kdp_reentry_deadline);
1389	    kdp_reentry_deadline = 0;
1390    }
1391
1392    kdp_sync_cache();
1393
1394    if (reattach_wait == 1)
1395      goto again;
1396
1397exit_raise_exception:
1398    if (kdp_en_setmode)
1399        (*kdp_en_setmode)(FALSE); /* link cleanup */
1400
1401    not_in_kdp = initial_not_in_kdp;
1402
1403    enable_preemption();
1404}
1405
1406void
1407kdp_reset(void)
1408{
1409	kdp.reply_port = kdp.exception_port = 0;
1410	kdp.is_halted = kdp.is_conn = FALSE;
1411	kdp.exception_seq = kdp.conn_seq = 0;
1412	kdp.session_key = 0;
1413	pkt.input = manual_pkt.input = FALSE;
1414	pkt.len = pkt.off = manual_pkt.len = 0;
1415}
1416
1417struct corehdr *
1418create_panic_header(unsigned int request, const char *corename,
1419    unsigned length, unsigned int block)
1420{
1421	struct udpiphdr		aligned_ui, *ui = &aligned_ui;
1422	struct ip		aligned_ip, *ip = &aligned_ip;
1423	struct ether_header	*eh;
1424	struct corehdr		*coreh;
1425	const char		*mode = "octet";
1426	char			modelen  = strlen(mode) + 1;
1427
1428	size_t			fmask_size = sizeof(KDP_FEATURE_MASK_STRING) + sizeof(kdp_crashdump_feature_mask);
1429
1430	pkt.off = sizeof (struct ether_header);
1431	pkt.len = (unsigned int)(length + ((request == KDP_WRQ) ? modelen + fmask_size : 0) +
1432	(corename ? (strlen(corename) + 1 ): 0) + sizeof(struct corehdr));
1433
1434#if DO_ALIGN
1435	bcopy((char *)&pkt.data[pkt.off], (char *)ui, sizeof(*ui));
1436#else
1437	ui = (struct udpiphdr *)&pkt.data[pkt.off];
1438#endif
1439	ui->ui_next = ui->ui_prev = 0;
1440	ui->ui_x1 = 0;
1441	ui->ui_pr = IPPROTO_UDP;
1442	ui->ui_len = htons((u_short)pkt.len + sizeof (struct udphdr));
1443	ui->ui_src.s_addr = (uint32_t)kdp_current_ip_address;
1444	/* Already in network byte order via inet_aton() */
1445	ui->ui_dst.s_addr = panic_server_ip;
1446	ui->ui_sport = htons(panicd_port);
1447	ui->ui_dport = ((request == KDP_WRQ) ? htons(panicd_port) : last_panic_port);
1448	ui->ui_ulen = ui->ui_len;
1449	ui->ui_sum = 0;
1450#if DO_ALIGN
1451	bcopy((char *)ui, (char *)&pkt.data[pkt.off], sizeof(*ui));
1452	bcopy((char *)&pkt.data[pkt.off], (char *)ip, sizeof(*ip));
1453#else
1454	ip = (struct ip *)&pkt.data[pkt.off];
1455#endif
1456	ip->ip_len = htons(sizeof (struct udpiphdr) + pkt.len);
1457	ip->ip_v = IPVERSION;
1458	ip->ip_id = htons(ip_id++);
1459	ip->ip_hl = sizeof (struct ip) >> 2;
1460	ip->ip_ttl = udp_ttl;
1461	ip->ip_sum = 0;
1462	ip->ip_sum = htons(~ip_sum((unsigned char *)ip, ip->ip_hl));
1463#if DO_ALIGN
1464	bcopy((char *)ip, (char *)&pkt.data[pkt.off], sizeof(*ip));
1465#endif
1466
1467	pkt.len += (unsigned int)sizeof (struct udpiphdr);
1468
1469	pkt.off += (unsigned int)sizeof (struct udpiphdr);
1470
1471	coreh = (struct corehdr *) &pkt.data[pkt.off];
1472	coreh->th_opcode = htons((u_short)request);
1473
1474	if (request == KDP_WRQ)
1475	{
1476		char *cp;
1477
1478		cp = coreh->th_u.tu_rpl;
1479		cp += strlcpy (cp, corename, KDP_MAXPACKET);
1480		*cp++ = '\0';
1481		cp += strlcpy (cp, mode, KDP_MAXPACKET - strlen(corename));
1482		*cp++ = '\0';
1483		cp += strlcpy(cp, KDP_FEATURE_MASK_STRING, sizeof(KDP_FEATURE_MASK_STRING));
1484		*cp++ = '\0'; /* Redundant */
1485		bcopy(&kdp_crashdump_feature_mask, cp, sizeof(kdp_crashdump_feature_mask));
1486		kdp_crashdump_pkt_size = KDP_LARGE_CRASHDUMP_PKT_SIZE;
1487		PE_parse_boot_argn("kdp_crashdump_pkt_size", &kdp_crashdump_pkt_size, sizeof(kdp_crashdump_pkt_size));
1488		cp += sizeof(kdp_crashdump_feature_mask);
1489		*(uint32_t *)cp = htonl(kdp_crashdump_pkt_size);
1490	}
1491	else
1492	{
1493		coreh->th_block = htonl((unsigned int) block);
1494	}
1495
1496	pkt.off -= (unsigned int)sizeof (struct udpiphdr);
1497	pkt.off -= (unsigned int)sizeof (struct ether_header);
1498
1499	eh = (struct ether_header *)&pkt.data[pkt.off];
1500	enaddr_copy(&kdp_current_mac_address, eh->ether_shost);
1501	enaddr_copy(&destination_mac, eh->ether_dhost);
1502	eh->ether_type = htons(ETHERTYPE_IP);
1503
1504	pkt.len += (unsigned int)sizeof (struct ether_header);
1505	return coreh;
1506}
1507
1508static int kdp_send_crashdump_seek(char *corename, uint64_t seek_off)
1509{
1510	int panic_error;
1511
1512	if (kdp_feature_large_crashdumps) {
1513		panic_error = kdp_send_crashdump_pkt(KDP_SEEK, corename,
1514						     sizeof(seek_off),
1515						     &seek_off);
1516	} else {
1517		uint32_t off = (uint32_t) seek_off;
1518		panic_error = kdp_send_crashdump_pkt(KDP_SEEK, corename,
1519						     sizeof(off), &off);
1520	}
1521
1522	if (panic_error < 0) {
1523		printf ("kdp_send_crashdump_pkt failed with error %d\n",
1524			panic_error);
1525		return panic_error;
1526	}
1527
1528	return 0;
1529}
1530
1531int kdp_send_crashdump_data(unsigned int request, char *corename,
1532    int64_t length, caddr_t txstart)
1533{
1534	int panic_error = 0;
1535
1536	while (length > 0) {
1537		uint64_t chunk = MIN(kdp_crashdump_pkt_size, length);
1538
1539		panic_error = kdp_send_crashdump_pkt(request, corename, chunk,
1540							txstart);
1541		if (panic_error < 0) {
1542			printf ("kdp_send_crashdump_pkt failed with error %d\n", panic_error);
1543			return panic_error;
1544		}
1545
1546		txstart += chunk;
1547		length  -= chunk;
1548	}
1549	return 0;
1550}
1551
1552uint32_t kdp_crashdump_short_pkt;
1553
1554int
1555kdp_send_crashdump_pkt(unsigned int request, char *corename,
1556    uint64_t length, void *panic_data)
1557{
1558	int poll_count;
1559	struct corehdr *th = NULL;
1560	char rretries, tretries;
1561
1562	if (kdp_dump_start_time == 0) {
1563		kdp_dump_start_time = mach_absolute_time();
1564		kdp_superblock_dump_start_time = kdp_dump_start_time;
1565	}
1566
1567	tretries = rretries = 0;
1568	poll_count = KDP_CRASHDUMP_POLL_COUNT;
1569	pkt.off = pkt.len = 0;
1570	if (request == KDP_WRQ) /* longer timeout for initial request */
1571		poll_count += 1000;
1572
1573TRANSMIT_RETRY:
1574	tretries++;
1575
1576	if (tretries >=15) {
1577/* The crashdump server is unreachable for some reason. This could be a network
1578 * issue or, if we've been especially unfortunate, we've hit Radar 2760413,
1579 * which is a long standing problem with the IOKit polled mode network driver
1580 * shim which can prevent transmits/receives completely.
1581 */
1582		printf ("Cannot contact panic server, timing out.\n");
1583		return (-3);
1584	}
1585
1586	if (tretries > 2)
1587		printf("TX retry #%d ", tretries );
1588
1589	th = create_panic_header(request, corename, (unsigned)length, panic_block);
1590
1591	if (request == KDP_DATA) {
1592		/* as all packets are kdp_crashdump_pkt_size in length, the last packet
1593		 * may end up with trailing bits. make sure that those
1594		 * bits aren't confusing. */
1595		if (length < kdp_crashdump_pkt_size) {
1596			kdp_crashdump_short_pkt++;
1597			memset(th->th_data + length, 'Y',
1598                               kdp_crashdump_pkt_size - (uint32_t) length);
1599		}
1600
1601		if (!kdp_machine_vm_read((mach_vm_address_t)(uintptr_t)panic_data, (caddr_t) th->th_data, length)) {
1602			uintptr_t next_page = round_page((uintptr_t)panic_data);
1603			memset((caddr_t) th->th_data, 'X', (size_t)length);
1604			if ((next_page - ((uintptr_t) panic_data)) < length) {
1605				uint64_t resid = length - (next_page - (intptr_t) panic_data);
1606				if (!kdp_machine_vm_read((mach_vm_address_t)(uintptr_t)next_page, (caddr_t) th->th_data + (length - resid), resid)) {
1607					memset((caddr_t) th->th_data + (length - resid), 'X', (size_t)resid);
1608				}
1609			}
1610		}
1611	}
1612	else if (request == KDP_SEEK) {
1613		if (kdp_feature_large_crashdumps)
1614			*(uint64_t *) th->th_data = OSSwapHostToBigInt64((*(uint64_t *) panic_data));
1615		else
1616			*(unsigned int *) th->th_data = htonl(*(unsigned int *) panic_data);
1617	}
1618
1619	kdp_send_data(&pkt.data[pkt.off], pkt.len);
1620
1621	/* Listen for the ACK */
1622RECEIVE_RETRY:
1623	while (!pkt.input && flag_panic_dump_in_progress && poll_count) {
1624		kdp_poll();
1625		poll_count--;
1626	}
1627
1628	if (pkt.input) {
1629
1630		pkt.input = FALSE;
1631
1632		th = (struct corehdr *) &pkt.data[pkt.off];
1633		if (request == KDP_WRQ) {
1634			uint16_t opcode64 = ntohs(th->th_opcode);
1635			uint16_t features64 = (opcode64 & 0xFF00)>>8;
1636			if ((opcode64 & 0xFF) == KDP_ACK) {
1637				kdp_feature_large_crashdumps = features64 & KDP_FEATURE_LARGE_CRASHDUMPS;
1638				if (features64 & KDP_FEATURE_LARGE_PKT_SIZE) {
1639					kdp_feature_large_pkt_size = 1;
1640				}
1641				else {
1642					kdp_feature_large_pkt_size = 0;
1643					kdp_crashdump_pkt_size = 512;
1644				}
1645				printf("Protocol features: 0x%x\n", (uint32_t) features64);
1646				th->th_opcode = htons(KDP_ACK);
1647			}
1648		}
1649		if (ntohs(th->th_opcode) == KDP_ACK && ntohl(th->th_block) == panic_block) {
1650		}
1651		else
1652			if (ntohs(th->th_opcode) == KDP_ERROR) {
1653				printf("Panic server returned error %d, retrying\n", ntohl(th->th_code));
1654				poll_count = 1000;
1655				goto TRANSMIT_RETRY;
1656			}
1657			else
1658				if (ntohl(th->th_block) == (panic_block - 1)) {
1659					printf("RX retry ");
1660					if (++rretries > 1)
1661						goto TRANSMIT_RETRY;
1662					else
1663						goto RECEIVE_RETRY;
1664				}
1665	}
1666	else
1667		if (!flag_panic_dump_in_progress) /* we received a debugging packet, bail*/
1668		{
1669			printf("Received a debugger packet,transferring control to debugger\n");
1670			/* Configure that if not set ..*/
1671			kdp_flag |= DBG_POST_CORE;
1672			return (-2);
1673		}
1674		else /* We timed out */
1675			if (0 == poll_count) {
1676				poll_count = 1000;
1677				kdp_us_spin ((tretries%4) * panic_timeout); /* capped linear backoff */
1678				goto TRANSMIT_RETRY;
1679			}
1680
1681	if (!(++panic_block % SBLOCKSZ)) {
1682		uint64_t ctime;
1683		kdb_printf_unbuffered(".");
1684		ctime = mach_absolute_time();
1685		kdp_superblock_dump_time = ctime - kdp_superblock_dump_start_time;
1686		kdp_superblock_dump_start_time = ctime;
1687		if (kdp_superblock_dump_time > kdp_max_superblock_dump_time)
1688			kdp_max_superblock_dump_time = kdp_superblock_dump_time;
1689		if (kdp_superblock_dump_time < kdp_min_superblock_dump_time)
1690			kdp_min_superblock_dump_time = kdp_superblock_dump_time;
1691	}
1692
1693	if (request == KDP_EOF) {
1694		printf("\nTotal number of packets transmitted: %d\n", panic_block);
1695		printf("Avg. superblock transfer abstime 0x%llx\n", ((mach_absolute_time() - kdp_dump_start_time) / panic_block) * SBLOCKSZ);
1696		printf("Minimum superblock transfer abstime: 0x%llx\n", kdp_min_superblock_dump_time);
1697		printf("Maximum superblock transfer abstime: 0x%llx\n", kdp_max_superblock_dump_time);
1698	}
1699	return 1;
1700}
1701
1702static int
1703isdigit (char c)
1704{
1705  return ((c > 47) && (c < 58));
1706}
1707/* From user mode Libc - this ought to be in a library */
1708static char *
1709strnstr(char *s, const char *find, size_t slen)
1710{
1711  char c, sc;
1712  size_t len;
1713
1714  if ((c = *find++) != '\0') {
1715    len = strlen(find);
1716    do {
1717      do {
1718	if ((sc = *s++) == '\0' || slen-- < 1)
1719	  return (NULL);
1720      } while (sc != c);
1721      if (len > slen)
1722	return (NULL);
1723    } while (strncmp(s, find, len) != 0);
1724    s--;
1725  }
1726  return (s);
1727}
1728
1729/* Horrid hack to extract xnu version if possible - a much cleaner approach
1730 * would be to have the integrator run a script which would copy the
1731 * xnu version into a string or an int somewhere at project submission
1732 * time - makes assumptions about sizeof(version), but will not fail if
1733 * it changes, but may be incorrect.
1734 */
1735/* 2006: Incorporated a change from Darwin user P. Lovell to extract
1736 * the minor kernel version numbers from the version string.
1737 */
1738static int
1739kdp_get_xnu_version(char *versionbuf)
1740{
1741	char *versionpos;
1742	char vstr[20];
1743	int retval = -1;
1744	char *vptr;
1745
1746	strlcpy(vstr, "custom", 10);
1747	if (kdp_machine_vm_read((mach_vm_address_t)(uintptr_t)version, versionbuf, 128)) {
1748		versionbuf[127] = '\0';
1749		versionpos = strnstr(versionbuf, "xnu-", 115);
1750		if (versionpos) {
1751			strncpy(vstr, versionpos, sizeof(vstr));
1752			vstr[sizeof(vstr)-1] = '\0';
1753			vptr = vstr + 4; /* Begin after "xnu-" */
1754			while (*vptr && (isdigit(*vptr) || *vptr == '.'))
1755				vptr++;
1756			*vptr = '\0';
1757			/* Remove trailing period, if any */
1758			if (*(--vptr) == '.')
1759				*vptr = '\0';
1760			retval = 0;
1761		}
1762	}
1763	strlcpy(versionbuf, vstr, KDP_MAXPACKET);
1764	return retval;
1765}
1766
1767void
1768kdp_set_dump_info(const uint32_t flags, const char *filename,
1769                  const char *destipstr, const char *routeripstr,
1770                  const uint32_t port)
1771{
1772	uint32_t cmd;
1773
1774	if (destipstr && (destipstr[0] != '\0')) {
1775		strlcpy(panicd_ip_str, destipstr, sizeof(panicd_ip_str));
1776		panicd_specified = 1;
1777	}
1778
1779	if (routeripstr && (routeripstr[0] != '\0')) {
1780		strlcpy(router_ip_str, routeripstr, sizeof(router_ip_str));
1781		router_specified = 1;
1782	}
1783
1784	if (filename && (filename[0] != '\0')) {
1785		strlcpy(corename_str, filename, sizeof(corename_str));
1786		corename_specified = TRUE;
1787	} else {
1788		corename_specified = FALSE;
1789	}
1790
1791	if (port)
1792		panicd_port = port;
1793
1794        /* on a disconnect, should we stay in KDP or not? */
1795        noresume_on_disconnect = (flags & KDP_DUMPINFO_NORESUME) ? 1 : 0;
1796
1797	if ((flags & KDP_DUMPINFO_DUMP) == 0)
1798		return;
1799
1800	/* the rest of the commands can modify kdp_flags */
1801	cmd = flags & KDP_DUMPINFO_MASK;
1802        if (cmd == KDP_DUMPINFO_DISABLE) {
1803		kdp_flag &= ~KDP_PANIC_DUMP_ENABLED;
1804		panicd_specified       = 0;
1805		kdp_trigger_core_dump  = 0;
1806		return;
1807        }
1808
1809	kdp_flag &= ~REBOOT_POST_CORE;
1810	if (flags & KDP_DUMPINFO_REBOOT)
1811            kdp_flag |= REBOOT_POST_CORE;
1812
1813	kdp_flag &= ~PANIC_LOG_DUMP;
1814	if (cmd == KDP_DUMPINFO_PANICLOG)
1815            kdp_flag |= PANIC_LOG_DUMP;
1816
1817	kdp_flag &= ~SYSTEM_LOG_DUMP;
1818	if (cmd == KDP_DUMPINFO_SYSTEMLOG)
1819            kdp_flag |= SYSTEM_LOG_DUMP;
1820
1821	/* trigger a dump */
1822	kdp_flag |= DBG_POST_CORE;
1823
1824	flag_dont_abort_panic_dump = (flags & KDP_DUMPINFO_NOINTR) ?
1825		TRUE : FALSE;
1826
1827	reattach_wait          = 1;
1828	logPanicDataToScreen   = 1;
1829	disableConsoleOutput   = 0;
1830	disable_debug_output   = 0;
1831	kdp_trigger_core_dump  = 1;
1832}
1833
1834void
1835kdp_get_dump_info(uint32_t *flags, char *filename, char *destipstr,
1836                  char *routeripstr, uint32_t *port)
1837{
1838	if (destipstr) {
1839		if (panicd_specified)
1840			strlcpy(destipstr, panicd_ip_str,
1841                                sizeof(panicd_ip_str));
1842		else
1843			destipstr[0] = '\0';
1844	}
1845
1846	if (routeripstr) {
1847		if (router_specified)
1848			strlcpy(routeripstr, router_ip_str,
1849                                sizeof(router_ip_str));
1850		else
1851			routeripstr[0] = '\0';
1852	}
1853
1854	if (filename) {
1855		if (corename_specified)
1856			strlcpy(filename, corename_str,
1857                                sizeof(corename_str));
1858		else
1859			filename[0] = '\0';
1860
1861	}
1862
1863	if (port)
1864		*port = panicd_port;
1865
1866	if (flags) {
1867		*flags = 0;
1868                if (!panicd_specified)
1869			*flags |= KDP_DUMPINFO_DISABLE;
1870                else if (kdp_flag & PANIC_LOG_DUMP)
1871			*flags |= KDP_DUMPINFO_PANICLOG;
1872		else
1873			*flags |= KDP_DUMPINFO_CORE;
1874
1875		if (noresume_on_disconnect)
1876			*flags |= KDP_DUMPINFO_NORESUME;
1877	}
1878}
1879
1880
1881/* Primary dispatch routine for the system dump */
1882void
1883kdp_panic_dump(void)
1884{
1885	char coreprefix[10];
1886	int panic_error;
1887
1888	uint64_t        abstime;
1889	uint32_t	current_ip = ntohl((uint32_t)kdp_current_ip_address);
1890
1891	if (flag_panic_dump_in_progress) {
1892		kdb_printf("System dump aborted.\n");
1893		goto panic_dump_exit;
1894	}
1895
1896	printf("Entering system dump routine\n");
1897
1898	if (!kdp_en_recv_pkt || !kdp_en_send_pkt) {
1899			kdb_printf("Error: No transport device registered for kernel crashdump\n");
1900			return;
1901	}
1902
1903	if (!panicd_specified) {
1904		kdb_printf("A dump server was not specified in the boot-args, terminating kernel core dump.\n");
1905		goto panic_dump_exit;
1906	}
1907
1908	flag_panic_dump_in_progress = TRUE;
1909
1910	if (pkt.input)
1911		kdp_panic("kdp_panic_dump: unexpected pending input packet");
1912
1913	kdp_get_xnu_version((char *) &pkt.data[0]);
1914
1915        if (!corename_specified) {
1916            /* Panic log bit takes precedence over core dump bit */
1917            if ((panicstr != (char *) 0) && (kdp_flag & PANIC_LOG_DUMP))
1918		strlcpy(coreprefix, "paniclog", sizeof(coreprefix));
1919            else if (kdp_flag & SYSTEM_LOG_DUMP)
1920		strlcpy(coreprefix, "systemlog", sizeof(coreprefix));
1921	    else
1922		strlcpy(coreprefix, "core", sizeof(coreprefix));
1923
1924            abstime = mach_absolute_time();
1925	    pkt.data[20] = '\0';
1926	    snprintf (corename_str, sizeof(corename_str), "%s-%s-%d.%d.%d.%d-%x",
1927		      coreprefix, &pkt.data[0],
1928		      (current_ip & 0xff000000) >> 24,
1929		      (current_ip & 0xff0000) >> 16,
1930		      (current_ip & 0xff00) >> 8,
1931		      (current_ip & 0xff),
1932		      (unsigned int) (abstime & 0xffffffff));
1933        }
1934
1935	if (0 == inet_aton(panicd_ip_str, (struct in_addr *) &panic_server_ip)) {
1936		kdb_printf("inet_aton() failed interpreting %s as a panic server IP\n", panicd_ip_str);
1937	}
1938	else
1939		kdb_printf("Attempting connection to panic server configured at IP %s, port %d\n", panicd_ip_str, panicd_port);
1940
1941	destination_mac = router_mac;
1942
1943	if (kdp_arp_resolve(panic_server_ip, &temp_mac)) {
1944		kdb_printf("Resolved %s's (or proxy's) link level address\n", panicd_ip_str);
1945		destination_mac = temp_mac;
1946	}
1947	else {
1948		if (!flag_panic_dump_in_progress) goto panic_dump_exit;
1949		if (router_specified) {
1950			if (0 == inet_aton(router_ip_str, (struct in_addr *) &parsed_router_ip))
1951				kdb_printf("inet_aton() failed interpreting %s as an IP\n", router_ip_str);
1952			else {
1953				router_ip = parsed_router_ip;
1954				if (kdp_arp_resolve(router_ip, &temp_mac)) {
1955					destination_mac = temp_mac;
1956					kdb_printf("Routing through specified router IP %s (%d)\n", router_ip_str, router_ip);
1957				}
1958			}
1959		}
1960	}
1961
1962	if (!flag_panic_dump_in_progress) goto panic_dump_exit;
1963
1964	kdb_printf("Transmitting packets to link level address: %02x:%02x:%02x:%02x:%02x:%02x\n",
1965	    destination_mac.ether_addr_octet[0] & 0xff,
1966	    destination_mac.ether_addr_octet[1] & 0xff,
1967	    destination_mac.ether_addr_octet[2] & 0xff,
1968	    destination_mac.ether_addr_octet[3] & 0xff,
1969	    destination_mac.ether_addr_octet[4] & 0xff,
1970	    destination_mac.ether_addr_octet[5] & 0xff);
1971
1972	kdb_printf("Kernel map size is %llu\n", (unsigned long long) get_vmmap_size(kernel_map));
1973	kdb_printf("Sending write request for %s\n", corename_str);
1974
1975	if ((panic_error = kdp_send_crashdump_pkt(KDP_WRQ, corename_str, 0 , NULL)) < 0) {
1976		kdb_printf ("kdp_send_crashdump_pkt failed with error %d\n", panic_error);
1977		goto panic_dump_exit;
1978	}
1979
1980	/* Just the panic log requested */
1981	if ((panicstr != (char *) 0) && (kdp_flag & PANIC_LOG_DUMP)) {
1982		kdb_printf_unbuffered("Transmitting panic log, please wait: ");
1983		kdp_send_crashdump_data(KDP_DATA, corename_str,
1984					debug_buf_ptr - debug_buf,
1985					debug_buf);
1986		kdp_send_crashdump_pkt (KDP_EOF, NULL, 0, ((void *) 0));
1987		printf("Please file a bug report on this panic, if possible.\n");
1988		goto panic_dump_exit;
1989	}
1990
1991	/* maybe we wanted the systemlog */
1992        if (kdp_flag & SYSTEM_LOG_DUMP) {
1993		long start_off = msgbufp->msg_bufx;
1994                long len;
1995
1996		kdb_printf_unbuffered("Transmitting system log, please wait: ");
1997		if (start_off >= msgbufp->msg_bufr) {
1998			len = msgbufp->msg_size - start_off;
1999			kdp_send_crashdump_data(KDP_DATA, corename_str, len,
2000						msgbufp->msg_bufc + start_off);
2001			/* seek to remove trailing bytes */
2002			kdp_send_crashdump_seek(corename_str, len);
2003			start_off  = 0;
2004		}
2005
2006		if (start_off != msgbufp->msg_bufr) {
2007			len = msgbufp->msg_bufr - start_off;
2008			kdp_send_crashdump_data(KDP_DATA, corename_str, len,
2009						msgbufp->msg_bufc + start_off);
2010		}
2011
2012		kdp_send_crashdump_pkt (KDP_EOF, NULL, 0, ((void *) 0));
2013		goto panic_dump_exit;
2014        }
2015
2016	/* We want a core dump if we're here */
2017	kern_dump();
2018
2019panic_dump_exit:
2020	abort_panic_transfer();
2021	kdp_reset();
2022	return;
2023}
2024
2025void
2026abort_panic_transfer(void)
2027{
2028	flag_panic_dump_in_progress = FALSE;
2029	flag_dont_abort_panic_dump  = FALSE;
2030	panic_block = 0;
2031}
2032
2033static boolean_t needs_serial_init = TRUE;
2034
2035static void
2036kdp_serial_send(void *rpkt, unsigned int rpkt_len)
2037{
2038	//	printf("tx\n");
2039	kdp_serialize_packet((unsigned char *)rpkt, rpkt_len, pal_serial_putc);
2040}
2041
2042static void
2043kdp_serial_receive(void *rpkt, unsigned int *rpkt_len, unsigned int timeout)
2044{
2045	int readkar;
2046	uint64_t now, deadline;
2047
2048	clock_interval_to_deadline(timeout, 1000 * 1000 /* milliseconds */, &deadline);
2049
2050//	printf("rx\n");
2051	for(clock_get_uptime(&now); now < deadline; clock_get_uptime(&now))
2052	{
2053		readkar = pal_serial_getc();
2054		if(readkar >= 0)
2055		{
2056			unsigned char *packet;
2057			//			printf("got char %02x\n", readkar);
2058			if((packet = kdp_unserialize_packet(readkar,rpkt_len)))
2059			{
2060				memcpy(rpkt, packet, *rpkt_len);
2061				return;
2062			}
2063		}
2064	}
2065	*rpkt_len = 0;
2066}
2067
2068static boolean_t
2069kdp_serial_setmode(boolean_t active)
2070{
2071        if (active == FALSE) /* leaving KDP */
2072            return TRUE;
2073
2074	if (!needs_serial_init)
2075            return TRUE;
2076
2077        pal_serial_init();
2078
2079        needs_serial_init = FALSE;
2080        return TRUE;
2081}
2082
2083
2084static void kdp_serial_callout(__unused void *arg, kdp_event_t event)
2085{
2086    /* When we stop KDP, set the bit to re-initialize the console serial port
2087     * the next time we send/receive a KDP packet.  We don't do it on
2088     * KDP_EVENT_ENTER directly because it also gets called when we trap to KDP
2089     * for non-external debugging, i.e., stackshot or core dumps.
2090     *
2091     * Set needs_serial_init on exit (and initialization, see above) and not
2092     * enter because enter is sent multiple times and causes excess reinitialization.
2093     */
2094
2095    switch (event)
2096    {
2097		case KDP_EVENT_PANICLOG:
2098		case KDP_EVENT_ENTER:
2099			break;
2100		case KDP_EVENT_EXIT:
2101			needs_serial_init = TRUE;
2102			break;
2103    }
2104}
2105
2106void
2107kdp_init(void)
2108{
2109	strlcpy(kdp_kernelversion_string, version, sizeof(kdp_kernelversion_string));
2110
2111	/* Relies on platform layer calling panic_init() before kdp_init() */
2112	if (kernel_uuid[0] != '\0') {
2113		/*
2114		 * Update kdp_kernelversion_string with our UUID
2115		 * generated at link time.
2116		 */
2117
2118		strlcat(kdp_kernelversion_string, "; UUID=", sizeof(kdp_kernelversion_string));
2119		strlcat(kdp_kernelversion_string, kernel_uuid, sizeof(kdp_kernelversion_string));
2120	}
2121
2122#if defined(__x86_64__) || defined(__arm__)
2123	debug_log_init();
2124
2125	if (vm_kernel_slide) {
2126		char	KASLR_stext[19];
2127		strlcat(kdp_kernelversion_string, "; stext=", sizeof(kdp_kernelversion_string));
2128		snprintf(KASLR_stext, sizeof(KASLR_stext), "%p", (void *) vm_kernel_stext);
2129		strlcat(kdp_kernelversion_string, KASLR_stext, sizeof(kdp_kernelversion_string));
2130	}
2131#endif
2132
2133	if (debug_boot_arg & DB_REBOOT_POST_CORE)
2134		kdp_flag |= REBOOT_POST_CORE;
2135#if	defined(__x86_64__) || defined(__arm__)
2136	kdp_machine_init();
2137#endif
2138
2139	kdp_timer_callout_init();
2140	kdp_crashdump_feature_mask = htonl(kdp_crashdump_feature_mask);
2141
2142	char kdpname[80];
2143	struct in_addr ipaddr;
2144	struct ether_addr macaddr;
2145
2146
2147	//serial will be the debugger, unless match name is explicitly provided, and it's not "serial"
2148	if(PE_parse_boot_argn("kdp_match_name", kdpname, sizeof(kdpname)) && strncmp(kdpname, "serial", sizeof(kdpname)) != 0)
2149		return;
2150
2151	kprintf("Initializing serial KDP\n");
2152
2153	kdp_register_callout(kdp_serial_callout, NULL);
2154        kdp_register_link(NULL, kdp_serial_setmode);
2155	kdp_register_send_receive(kdp_serial_send, kdp_serial_receive);
2156
2157	/* fake up an ip and mac for early serial debugging */
2158	macaddr.ether_addr_octet[0] = 's';
2159	macaddr.ether_addr_octet[1] = 'e';
2160	macaddr.ether_addr_octet[2] = 'r';
2161	macaddr.ether_addr_octet[3] = 'i';
2162	macaddr.ether_addr_octet[4] = 'a';
2163	macaddr.ether_addr_octet[5] = 'l';
2164	ipaddr.s_addr = KDP_SERIAL_IPADDR;
2165	kdp_set_ip_and_mac_addresses(&ipaddr, &macaddr);
2166
2167}
2168