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