+struct corehdr *
+create_panic_header(unsigned int request, const char *corename,
+ unsigned length, unsigned int block)
+{
+ struct udpiphdr aligned_ui, *ui = &aligned_ui;
+ struct ip aligned_ip, *ip = &aligned_ip;
+ struct ether_header *eh;
+ struct corehdr *coreh;
+ const char *mode = "octet";
+ char modelen = strlen(mode);
+#if defined(__LP64__)
+ size_t fmask_size = sizeof(KDP_FEATURE_MASK_STRING) + sizeof(kdp_crashdump_feature_mask);
+#else
+ size_t fmask_size = 0;
+#endif
+ pkt.off = sizeof (struct ether_header);
+ pkt.len = (unsigned int)(length + ((request == KDP_WRQ) ? modelen + fmask_size : 0) +
+ (corename ? strlen(corename): 0) + sizeof(struct corehdr));
+
+#if DO_ALIGN
+ bcopy((char *)&pkt.data[pkt.off], (char *)ui, sizeof(*ui));
+#else
+ ui = (struct udpiphdr *)&pkt.data[pkt.off];
+#endif
+ ui->ui_next = ui->ui_prev = 0;
+ ui->ui_x1 = 0;
+ ui->ui_pr = IPPROTO_UDP;
+ ui->ui_len = htons((u_short)pkt.len + sizeof (struct udphdr));
+ ui->ui_src.s_addr = (uint32_t)kdp_current_ip_address;
+ /* Already in network byte order via inet_aton() */
+ ui->ui_dst.s_addr = panic_server_ip;
+ ui->ui_sport = htons(panicd_port);
+ ui->ui_dport = ((request == KDP_WRQ) ? htons(panicd_port) : last_panic_port);
+ ui->ui_ulen = ui->ui_len;
+ ui->ui_sum = 0;
+#if DO_ALIGN
+ bcopy((char *)ui, (char *)&pkt.data[pkt.off], sizeof(*ui));
+ bcopy((char *)&pkt.data[pkt.off], (char *)ip, sizeof(*ip));
+#else
+ ip = (struct ip *)&pkt.data[pkt.off];
+#endif
+ ip->ip_len = htons(sizeof (struct udpiphdr) + pkt.len);
+ ip->ip_v = IPVERSION;
+ ip->ip_id = htons(ip_id++);
+ ip->ip_hl = sizeof (struct ip) >> 2;
+ ip->ip_ttl = udp_ttl;
+ ip->ip_sum = 0;
+ ip->ip_sum = htons(~ip_sum((unsigned char *)ip, ip->ip_hl));
+#if DO_ALIGN
+ bcopy((char *)ip, (char *)&pkt.data[pkt.off], sizeof(*ip));
+#endif
+
+ pkt.len += (unsigned int)sizeof (struct udpiphdr);
+
+ pkt.off += (unsigned int)sizeof (struct udpiphdr);
+
+ coreh = (struct corehdr *) &pkt.data[pkt.off];
+ coreh->th_opcode = htons((u_short)request);
+
+ if (request == KDP_WRQ)
+ {
+ char *cp;
+
+ cp = coreh->th_u.tu_rpl;
+ cp += strlcpy (cp, corename, KDP_MAXPACKET);
+ *cp++ = '\0';
+ cp += strlcpy (cp, mode, KDP_MAXPACKET - strlen(corename));
+ *cp++ = '\0';
+#if defined(__LP64__)
+ cp += strlcpy(cp, KDP_FEATURE_MASK_STRING, sizeof(KDP_FEATURE_MASK_STRING));
+ *cp++ = '\0'; /* Redundant */
+ bcopy(&kdp_crashdump_feature_mask, cp, sizeof(kdp_crashdump_feature_mask));
+#endif
+ }
+ else
+ {
+ coreh->th_block = htonl((unsigned int) block);
+ }
+
+ pkt.off -= (unsigned int)sizeof (struct udpiphdr);
+ pkt.off -= (unsigned int)sizeof (struct ether_header);
+
+ eh = (struct ether_header *)&pkt.data[pkt.off];
+ enaddr_copy(&kdp_current_mac_address, eh->ether_shost);
+ enaddr_copy(&destination_mac, eh->ether_dhost);
+ eh->ether_type = htons(ETHERTYPE_IP);
+
+ pkt.len += (unsigned int)sizeof (struct ether_header);
+ return coreh;
+}
+
+int kdp_send_crashdump_data(unsigned int request, char *corename,
+ uint64_t length, caddr_t txstart)
+{
+ caddr_t txend = txstart + length;
+ int panic_error = 0;
+
+ if (length <= SEGSIZE) {
+ if ((panic_error = kdp_send_crashdump_pkt(request, corename, length, (caddr_t) txstart)) < 0) {
+ printf ("kdp_send_crashdump_pkt failed with error %d\n", panic_error);
+ return panic_error ;
+ }
+ }
+ else
+ {
+ while (txstart <= (txend - SEGSIZE)) {
+ if ((panic_error = kdp_send_crashdump_pkt(KDP_DATA, NULL, SEGSIZE, txstart)) < 0) {
+ printf ("kdp_send_crashdump_pkt failed with error %d\n", panic_error);
+ return panic_error;
+ }
+ txstart += SEGSIZE;
+ if (!(panic_block % 2000))
+ kdb_printf_unbuffered(".");
+ }
+ if (txstart < txend) {
+ kdp_send_crashdump_pkt(request, corename, (unsigned int)(txend - txstart), txstart);
+ }
+ }
+ return 0;
+}
+
+int
+kdp_send_crashdump_pkt(unsigned int request, char *corename,
+ uint64_t length, void *panic_data)
+{
+ struct corehdr *th = NULL;
+ int poll_count = 2500;
+
+ char rretries = 0, tretries = 0;
+
+ pkt.off = pkt.len = 0;
+
+ if (request == KDP_WRQ) /* longer timeout for initial request */
+ poll_count += 1000;
+
+TRANSMIT_RETRY:
+ tretries++;
+
+ if (tretries >=15) {
+/* The crashdump server is unreachable for some reason. This could be a network
+ * issue or, if we've been especially unfortunate, we've hit Radar 2760413,
+ * which is a long standing problem with the IOKit polled mode network driver
+ * shim which can prevent transmits/receives completely.
+ */
+ printf ("Cannot contact panic server, timing out.\n");
+ return (-3);
+ }
+
+ if (tretries > 2)
+ printf("TX retry #%d ", tretries );
+
+ th = create_panic_header(request, corename, (unsigned)length, panic_block);
+
+ if (request == KDP_DATA) {
+ if (!kdp_machine_vm_read((mach_vm_address_t)(intptr_t)panic_data, (caddr_t) th->th_data, length)) {
+ memset ((caddr_t) th->th_data, 'X', (size_t)length);
+ }
+ }
+ else if (request == KDP_SEEK) {
+#if defined(__LP64__)
+ if (kdp_feature_large_crashdumps)
+ *(uint64_t *) th->th_data = OSSwapHostToBigInt64((*(uint64_t *) panic_data));
+ else
+#endif
+ *(unsigned int *) th->th_data = htonl(*(unsigned int *) panic_data);
+ }
+
+ (*kdp_en_send_pkt)(&pkt.data[pkt.off], pkt.len);
+
+ /* Listen for the ACK */
+RECEIVE_RETRY:
+ while (!pkt.input && flag_panic_dump_in_progress && poll_count) {
+ kdp_poll();
+ poll_count--;
+ }
+
+ if (pkt.input) {
+
+ pkt.input = FALSE;
+
+ th = (struct corehdr *) &pkt.data[pkt.off];
+#if defined(__LP64__)
+ if (request == KDP_WRQ) {
+ uint16_t opcode64 = ntohs(th->th_opcode);
+ uint16_t features64 = (opcode64 & 0xFF00)>>8;
+ if ((opcode64 & 0xFF) == KDP_ACK) {
+ kdp_feature_large_crashdumps = features64 & KDP_FEATURE_LARGE_CRASHDUMPS;
+ printf("Protocol features: 0x%x\n", (uint32_t) features64);
+ th->th_opcode = htons(KDP_ACK);
+ }
+ }
+#endif
+ if (ntohs(th->th_opcode) == KDP_ACK && ntohl(th->th_block) == panic_block) {
+ }
+ else
+ if (ntohs(th->th_opcode) == KDP_ERROR) {
+ printf("Panic server returned error %d, retrying\n", ntohl(th->th_code));
+ poll_count = 1000;
+ goto TRANSMIT_RETRY;
+ }
+ else
+ if (ntohl(th->th_block) == (panic_block - 1)) {
+ printf("RX retry ");
+ if (++rretries > 1)
+ goto TRANSMIT_RETRY;
+ else
+ goto RECEIVE_RETRY;
+ }
+ }
+ else
+ if (!flag_panic_dump_in_progress) /* we received a debugging packet, bail*/
+ {
+ printf("Received a debugger packet,transferring control to debugger\n");
+ /* Configure that if not set ..*/
+ kdp_flag |= DBG_POST_CORE;
+ return (-2);
+ }
+ else /* We timed out */
+ if (0 == poll_count) {
+ poll_count = 1000;
+ kdp_us_spin ((tretries%4) * panic_timeout); /* capped linear backoff */
+ goto TRANSMIT_RETRY;
+ }
+
+ panic_block++;
+
+ if (request == KDP_EOF)
+ printf("\nTotal number of packets transmitted: %d\n", panic_block);
+
+ return 1;
+}
+
+static int
+isdigit (char c)
+{
+ return ((c > 47) && (c < 58));
+}
+/* From user mode Libc - this ought to be in a library */
+static char *
+strnstr(char *s, const char *find, size_t slen)
+{
+ char c, sc;
+ size_t len;
+
+ if ((c = *find++) != '\0') {
+ len = strlen(find);
+ do {
+ do {
+ if ((sc = *s++) == '\0' || slen-- < 1)
+ return (NULL);
+ } while (sc != c);
+ if (len > slen)
+ return (NULL);
+ } while (strncmp(s, find, len) != 0);
+ s--;
+ }
+ return (s);
+}
+
+extern char version[];
+
+/* Horrid hack to extract xnu version if possible - a much cleaner approach
+ * would be to have the integrator run a script which would copy the
+ * xnu version into a string or an int somewhere at project submission
+ * time - makes assumptions about sizeof(version), but will not fail if
+ * it changes, but may be incorrect.
+ */
+/* 2006: Incorporated a change from Darwin user P. Lovell to extract
+ * the minor kernel version numbers from the version string.
+ */
+static int
+kdp_get_xnu_version(char *versionbuf)
+{
+ char *versionpos;
+ char vstr[20];
+ int retval = -1;
+ char *vptr;
+
+ strlcpy(vstr, "custom", 10);
+ if (strlcpy(versionbuf, version, 95) < 95) {
+ versionpos = strnstr(versionbuf, "xnu-", 90);
+ if (versionpos) {
+ strncpy(vstr, versionpos, sizeof(vstr));
+ vstr[sizeof(vstr)-1] = '\0';
+ vptr = vstr + 4; /* Begin after "xnu-" */
+ while (*vptr && (isdigit(*vptr) || *vptr == '.'))
+ vptr++;
+ *vptr = '\0';
+ /* Remove trailing period, if any */
+ if (*(--vptr) == '.')
+ *vptr = '\0';
+ retval = 0;
+ }
+ }
+ strlcpy(versionbuf, vstr, KDP_MAXPACKET);
+ return retval;
+}
+
+extern char *inet_aton(const char *cp, struct in_addr *pin);
+
+/* Primary dispatch routine for the system dump */
+void
+kdp_panic_dump(void)
+{
+ char corename[50];
+ char coreprefix[10];
+ int panic_error;
+
+ uint64_t abstime;
+ uint32_t current_ip = ntohl((uint32_t)kdp_current_ip_address);
+
+ if (flag_panic_dump_in_progress) {
+ printf("System dump aborted.\n");
+ goto panic_dump_exit;
+ }
+
+ printf("Entering system dump routine\n");
+
+ if (!panicd_specified) {
+ printf("A dump server was not specified in the boot-args, terminating kernel core dump.\n");
+ goto panic_dump_exit;
+ }
+
+ flag_panic_dump_in_progress = TRUE;
+ not_in_kdp = 0;
+
+ if (pkt.input)
+ kdp_panic("kdp_panic_dump: unexpected pending input packet");
+
+ kdp_get_xnu_version((char *) &pkt.data[0]);
+
+ /* Panic log bit takes precedence over core dump bit */
+ if ((panicstr != (char *) 0) && (kdp_flag & PANIC_LOG_DUMP))
+ strncpy(coreprefix, "paniclog", sizeof(coreprefix));
+ else
+ strncpy(coreprefix, "core", sizeof(coreprefix));
+
+ abstime = mach_absolute_time();
+ pkt.data[20] = '\0';
+ snprintf (corename, sizeof(corename), "%s-%s-%d.%d.%d.%d-%x",
+ coreprefix, &pkt.data[0],
+ (current_ip & 0xff000000) >> 24,
+ (current_ip & 0xff0000) >> 16,
+ (current_ip & 0xff00) >> 8,
+ (current_ip & 0xff),
+ (unsigned int) (abstime & 0xffffffff));
+
+ if (0 == inet_aton(panicd_ip_str, (struct in_addr *) &panic_server_ip)) {
+ printf("inet_aton() failed interpreting %s as a panic server IP\n", panicd_ip_str);
+ }
+ else
+ printf("Attempting connection to panic server configured at IP %s, port %d\n", panicd_ip_str, panicd_port);
+
+ destination_mac = router_mac;
+
+ if (kdp_arp_resolve(panic_server_ip, &temp_mac)) {
+ printf("Resolved %s's (or proxy's) link level address\n", panicd_ip_str);
+ destination_mac = temp_mac;
+ }
+ else {
+ if (!flag_panic_dump_in_progress) goto panic_dump_exit;
+ if (router_specified) {
+ if (0 == inet_aton(router_ip_str, (struct in_addr *) &parsed_router_ip))
+ printf("inet_aton() failed interpreting %s as an IP\n", router_ip_str);
+ else {
+ router_ip = parsed_router_ip;
+ if (kdp_arp_resolve(router_ip, &temp_mac)) {
+ destination_mac = temp_mac;
+ printf("Routing through specified router IP %s (%d)\n", router_ip_str, router_ip);
+ }
+ }
+ }
+ }
+
+ if (!flag_panic_dump_in_progress) goto panic_dump_exit;
+
+ printf("Transmitting packets to link level address: %02x:%02x:%02x:%02x:%02x:%02x\n",
+ destination_mac.ether_addr_octet[0] & 0xff,
+ destination_mac.ether_addr_octet[1] & 0xff,
+ destination_mac.ether_addr_octet[2] & 0xff,
+ destination_mac.ether_addr_octet[3] & 0xff,
+ destination_mac.ether_addr_octet[4] & 0xff,
+ destination_mac.ether_addr_octet[5] & 0xff);
+
+ printf("Kernel map size is %llu\n", (unsigned long long) get_vmmap_size(kernel_map));
+ printf("Sending write request for %s\n", corename);
+
+ if ((panic_error = kdp_send_crashdump_pkt(KDP_WRQ, corename, 0 , NULL)) < 0) {
+ printf ("kdp_send_crashdump_pkt failed with error %d\n", panic_error);
+ goto panic_dump_exit;
+ }
+
+ /* Just the panic log requested */
+ if ((panicstr != (char *) 0) && (kdp_flag & PANIC_LOG_DUMP)) {
+ printf("Transmitting panic log, please wait: ");
+ kdp_send_crashdump_data(KDP_DATA, corename, (unsigned int)(debug_buf_ptr - debug_buf), debug_buf);
+ kdp_send_crashdump_pkt (KDP_EOF, NULL, 0, ((void *) 0));
+ printf("Please file a bug report on this panic, if possible.\n");
+ goto panic_dump_exit;
+ }
+
+ /* We want a core dump if we're here */
+ kern_dump();
+panic_dump_exit:
+ abort_panic_transfer();
+ pkt.input = FALSE;
+ pkt.len = 0;
+ kdp_reset();
+ return;
+}
+
+void
+abort_panic_transfer(void)
+{
+ flag_panic_dump_in_progress = FALSE;
+ not_in_kdp = 1;
+ panic_block = 0;
+}
+
+#if CONFIG_SERIAL_KDP
+
+static boolean_t needs_serial_init = TRUE;
+
+static void
+kdp_serial_send(void *rpkt, unsigned int rpkt_len)
+{
+ if (needs_serial_init)
+ {
+ serial_init();
+ needs_serial_init = FALSE;
+ }
+
+ // printf("tx\n");
+ kdp_serialize_packet((unsigned char *)rpkt, rpkt_len, serial_putc);
+}
+
+static void
+kdp_serial_receive(void *rpkt, unsigned int *rpkt_len, unsigned int timeout)
+{
+ int readkar;
+ uint64_t now, deadline;
+
+ if (needs_serial_init)
+ {
+ serial_init();
+ needs_serial_init = FALSE;
+ }
+
+ clock_interval_to_deadline(timeout, 1000 * 1000 /* milliseconds */, &deadline);
+
+// printf("rx\n");
+ for(clock_get_uptime(&now); now < deadline; clock_get_uptime(&now))
+ {
+ readkar = serial_getc();
+ if(readkar >= 0)
+ {
+ unsigned char *packet;
+ // printf("got char %02x\n", readkar);
+ if((packet = kdp_unserialize_packet(readkar,rpkt_len)))
+ {
+ memcpy(rpkt, packet, *rpkt_len);
+ return;
+ }
+ }
+ }
+ *rpkt_len = 0;
+}
+
+static void kdp_serial_callout(__unused void *arg, kdp_event_t event)
+{
+ /* When we stop KDP, set the bit to re-initialize the console serial port
+ * the next time we send/receive a KDP packet. We don't do it on
+ * KDP_EVENT_ENTER directly because it also gets called when we trap to KDP
+ * for non-external debugging, i.e., stackshot or core dumps.
+ *
+ * Set needs_serial_init on exit (and initialization, see above) and not
+ * enter because enter is sent multiple times and causes excess reinitialization.
+ */
+
+ switch (event)
+ {
+ case KDP_EVENT_PANICLOG:
+ case KDP_EVENT_ENTER:
+ break;
+ case KDP_EVENT_EXIT:
+ needs_serial_init = TRUE;
+ break;
+ }
+}
+
+#endif /* CONFIG_SERIAL_KDP */
+
+void
+kdp_init(void)
+{
+#if CONFIG_SERIAL_KDP
+ char kdpname[80];
+ struct in_addr ipaddr;
+ struct ether_addr macaddr;
+
+
+#if CONFIG_EMBEDDED
+ //serial will be the debugger, unless match name is explicitly provided, and it's not "serial"
+ if(PE_parse_boot_argn("kdp_match_name", kdpname, sizeof(kdpname)) && strncmp(kdpname, "serial", sizeof(kdpname)) != 0)
+ return;
+#else
+ // serial must be explicitly requested
+ if(!PE_parse_boot_argn("kdp_match_name", kdpname, sizeof(kdpname)) || strncmp(kdpname, "serial", sizeof(kdpname)) != 0)
+ return;
+#endif
+
+ kprintf("Intializing serial KDP\n");
+
+ kdp_register_callout(kdp_serial_callout, NULL);
+ kdp_register_send_receive(kdp_serial_send, kdp_serial_receive);
+
+ /* fake up an ip and mac for early serial debugging */
+ macaddr.ether_addr_octet[0] = 's';
+ macaddr.ether_addr_octet[1] = 'e';
+ macaddr.ether_addr_octet[2] = 'r';
+ macaddr.ether_addr_octet[3] = 'i';
+ macaddr.ether_addr_octet[4] = 'a';
+ macaddr.ether_addr_octet[5] = 'l';
+ ipaddr.s_addr = 0xABADBABE;
+ kdp_set_ip_and_mac_addresses(&ipaddr, &macaddr);
+#endif /* CONFIG_SERIAL_KDP */
+}