]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/netdump/netdump_client.c
netdump: Fix boot-time configuration typo
[FreeBSD/FreeBSD.git] / sys / netinet / netdump / netdump_client.c
1 /*-
2  * Copyright (c) 2005-2014 Sandvine Incorporated. All rights reserved.
3  * Copyright (c) 2000 Darrell Anderson
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 /*
29  * netdump_client.c
30  * FreeBSD subsystem supporting netdump network dumps.
31  * A dedicated server must be running to accept client dumps.
32  */
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36
37 #include <sys/param.h>
38 #include <sys/conf.h>
39 #include <sys/disk.h>
40 #include <sys/endian.h>
41 #include <sys/jail.h>
42 #include <sys/kernel.h>
43 #include <sys/kerneldump.h>
44 #include <sys/mbuf.h>
45 #include <sys/module.h>
46 #include <sys/priv.h>
47 #include <sys/proc.h>
48 #include <sys/protosw.h>
49 #include <sys/socket.h>
50 #include <sys/sysctl.h>
51 #include <sys/systm.h>
52
53 #include <net/ethernet.h>
54 #include <net/if.h>
55 #include <net/if_arp.h>
56 #include <net/if_dl.h>
57 #include <net/if_types.h>
58 #include <net/if_var.h>
59
60 #include <netinet/in.h>
61 #include <netinet/in_systm.h>
62 #include <netinet/in_var.h>
63 #include <netinet/ip.h>
64 #include <netinet/ip_var.h>
65 #include <netinet/ip_options.h>
66 #include <netinet/udp.h>
67 #include <netinet/udp_var.h>
68 #include <netinet/netdump/netdump.h>
69
70 #include <machine/in_cksum.h>
71 #include <machine/pcb.h>
72
73 #define NETDDEBUG(f, ...) do {                                          \
74         if (nd_debug > 0)                                               \
75                 printf(("%s: " f), __func__, ## __VA_ARGS__);           \
76 } while (0)
77 #define NETDDEBUG_IF(i, f, ...) do {                                    \
78         if (nd_debug > 0)                                               \
79                 if_printf((i), ("%s: " f), __func__, ## __VA_ARGS__);   \
80 } while (0)
81 #define NETDDEBUGV(f, ...) do {                                         \
82         if (nd_debug > 1)                                               \
83                 printf(("%s: " f), __func__, ## __VA_ARGS__);           \
84 } while (0)
85 #define NETDDEBUGV_IF(i, f, ...) do {                                   \
86         if (nd_debug > 1)                                               \
87                 if_printf((i), ("%s: " f), __func__, ## __VA_ARGS__);   \
88 } while (0)
89
90 static int       netdump_arp_gw(void);
91 static void      netdump_cleanup(void);
92 static int       netdump_configure(struct diocskerneldump_arg *,
93                     struct thread *);
94 static int       netdump_dumper(void *priv __unused, void *virtual,
95                     vm_offset_t physical __unused, off_t offset, size_t length);
96 static int       netdump_ether_output(struct mbuf *m, struct ifnet *ifp,
97                     struct ether_addr dst, u_short etype);
98 static void      netdump_handle_arp(struct mbuf **mb);
99 static void      netdump_handle_ip(struct mbuf **mb);
100 static int       netdump_ioctl(struct cdev *dev __unused, u_long cmd,
101                     caddr_t addr, int flags __unused, struct thread *td);
102 static int       netdump_modevent(module_t mod, int type, void *priv);
103 static void      netdump_network_poll(void);
104 static void      netdump_pkt_in(struct ifnet *ifp, struct mbuf *m);
105 static int       netdump_send(uint32_t type, off_t offset, unsigned char *data,
106                     uint32_t datalen);
107 static int       netdump_send_arp(in_addr_t dst);
108 static int       netdump_start(struct dumperinfo *di);
109 static int       netdump_udp_output(struct mbuf *m);
110
111 /* Must be at least as big as the chunks dumpsys() gives us. */
112 static unsigned char nd_buf[MAXDUMPPGS * PAGE_SIZE];
113 static uint32_t nd_seqno;
114 static int dump_failed, have_gw_mac;
115 static void (*drv_if_input)(struct ifnet *, struct mbuf *);
116 static int restore_gw_addr;
117
118 static uint64_t rcvd_acks;
119 CTASSERT(sizeof(rcvd_acks) * NBBY == NETDUMP_MAX_IN_FLIGHT);
120
121 /* Configuration parameters. */
122 static struct {
123         char             ndc_iface[IFNAMSIZ];
124         union kd_ip      ndc_server;
125         union kd_ip      ndc_client;
126         union kd_ip      ndc_gateway;
127         uint8_t          ndc_af;
128 } nd_conf;
129 #define nd_server       nd_conf.ndc_server.in4
130 #define nd_client       nd_conf.ndc_client.in4
131 #define nd_gateway      nd_conf.ndc_gateway.in4
132
133 /* General dynamic settings. */
134 static struct ether_addr nd_gw_mac;
135 static struct ifnet *nd_ifp;
136 static uint16_t nd_server_port = NETDUMP_PORT;
137
138 FEATURE(netdump, "Netdump client support");
139
140 static SYSCTL_NODE(_net, OID_AUTO, netdump, CTLFLAG_RD, NULL,
141     "netdump parameters");
142
143 static int nd_debug;
144 SYSCTL_INT(_net_netdump, OID_AUTO, debug, CTLFLAG_RWTUN,
145     &nd_debug, 0,
146     "Debug message verbosity");
147 static int nd_enabled;
148 SYSCTL_INT(_net_netdump, OID_AUTO, enabled, CTLFLAG_RD,
149     &nd_enabled, 0,
150     "netdump configuration status");
151 static char nd_path[MAXPATHLEN];
152 SYSCTL_STRING(_net_netdump, OID_AUTO, path, CTLFLAG_RW,
153     nd_path, sizeof(nd_path),
154     "Server path for output files");
155 static int nd_polls = 2000;
156 SYSCTL_INT(_net_netdump, OID_AUTO, polls, CTLFLAG_RWTUN,
157     &nd_polls, 0,
158     "Number of times to poll before assuming packet loss (0.5ms per poll)");
159 static int nd_retries = 10;
160 SYSCTL_INT(_net_netdump, OID_AUTO, retries, CTLFLAG_RWTUN,
161     &nd_retries, 0,
162     "Number of retransmit attempts before giving up");
163 static int nd_arp_retries = 3;
164 SYSCTL_INT(_net_netdump, OID_AUTO, arp_retries, CTLFLAG_RWTUN,
165     &nd_arp_retries, 0,
166     "Number of ARP attempts before giving up");
167
168 /*
169  * Checks for netdump support on a network interface
170  *
171  * Parameters:
172  *      ifp     The network interface that is being tested for support
173  *
174  * Returns:
175  *      int     1 if the interface is supported, 0 if not
176  */
177 static bool
178 netdump_supported_nic(struct ifnet *ifp)
179 {
180
181         return (ifp->if_netdump_methods != NULL);
182 }
183
184 /*-
185  * Network specific primitives.
186  * Following down the code they are divided ordered as:
187  * - Packet buffer primitives
188  * - Output primitives
189  * - Input primitives
190  * - Polling primitives
191  */
192
193 /*
194  * Handles creation of the ethernet header, then places outgoing packets into
195  * the tx buffer for the NIC
196  *
197  * Parameters:
198  *      m       The mbuf containing the packet to be sent (will be freed by
199  *              this function or the NIC driver)
200  *      ifp     The interface to send on
201  *      dst     The destination ethernet address (source address will be looked
202  *              up using ifp)
203  *      etype   The ETHERTYPE_* value for the protocol that is being sent
204  *
205  * Returns:
206  *      int     see errno.h, 0 for success
207  */
208 static int
209 netdump_ether_output(struct mbuf *m, struct ifnet *ifp, struct ether_addr dst,
210     u_short etype)
211 {
212         struct ether_header *eh;
213
214         if (((ifp->if_flags & (IFF_MONITOR | IFF_UP)) != IFF_UP) ||
215             (ifp->if_drv_flags & IFF_DRV_RUNNING) != IFF_DRV_RUNNING) {
216                 if_printf(ifp, "netdump_ether_output: interface isn't up\n");
217                 m_freem(m);
218                 return (ENETDOWN);
219         }
220
221         /* Fill in the ethernet header. */
222         M_PREPEND(m, ETHER_HDR_LEN, M_NOWAIT);
223         if (m == NULL) {
224                 printf("%s: out of mbufs\n", __func__);
225                 return (ENOBUFS);
226         }
227         eh = mtod(m, struct ether_header *);
228         memcpy(eh->ether_shost, IF_LLADDR(ifp), ETHER_ADDR_LEN);
229         memcpy(eh->ether_dhost, dst.octet, ETHER_ADDR_LEN);
230         eh->ether_type = htons(etype);
231         return ((ifp->if_netdump_methods->nd_transmit)(ifp, m));
232 }
233
234 /*
235  * Unreliable transmission of an mbuf chain to the netdump server
236  * Note: can't handle fragmentation; fails if the packet is larger than
237  *       nd_ifp->if_mtu after adding the UDP/IP headers
238  *
239  * Parameters:
240  *      m       mbuf chain
241  *
242  * Returns:
243  *      int     see errno.h, 0 for success
244  */
245 static int
246 netdump_udp_output(struct mbuf *m)
247 {
248         struct udpiphdr *ui;
249         struct ip *ip;
250
251         MPASS(nd_ifp != NULL);
252
253         M_PREPEND(m, sizeof(struct udpiphdr), M_NOWAIT);
254         if (m == NULL) {
255                 printf("%s: out of mbufs\n", __func__);
256                 return (ENOBUFS);
257         }
258
259         if (m->m_pkthdr.len > nd_ifp->if_mtu) {
260                 printf("netdump_udp_output: Packet is too big: %d > MTU %u\n",
261                     m->m_pkthdr.len, nd_ifp->if_mtu);
262                 m_freem(m);
263                 return (ENOBUFS);
264         }
265
266         ui = mtod(m, struct udpiphdr *);
267         bzero(ui->ui_x1, sizeof(ui->ui_x1));
268         ui->ui_pr = IPPROTO_UDP;
269         ui->ui_len = htons(m->m_pkthdr.len - sizeof(struct ip));
270         ui->ui_ulen = ui->ui_len;
271         ui->ui_src = nd_client;
272         ui->ui_dst = nd_server;
273         /* Use this src port so that the server can connect() the socket */
274         ui->ui_sport = htons(NETDUMP_ACKPORT);
275         ui->ui_dport = htons(nd_server_port);
276         ui->ui_sum = 0;
277         if ((ui->ui_sum = in_cksum(m, m->m_pkthdr.len)) == 0)
278                 ui->ui_sum = 0xffff;
279
280         ip = mtod(m, struct ip *);
281         ip->ip_v = IPVERSION;
282         ip->ip_hl = sizeof(struct ip) >> 2;
283         ip->ip_tos = 0;
284         ip->ip_len = htons(m->m_pkthdr.len);
285         ip->ip_id = 0;
286         ip->ip_off = htons(IP_DF);
287         ip->ip_ttl = 255;
288         ip->ip_sum = 0;
289         ip->ip_sum = in_cksum(m, sizeof(struct ip));
290
291         return (netdump_ether_output(m, nd_ifp, nd_gw_mac, ETHERTYPE_IP));
292 }
293
294 /*
295  * Builds and sends a single ARP request to locate the server
296  *
297  * Return value:
298  *      0 on success
299  *      errno on error
300  */
301 static int
302 netdump_send_arp(in_addr_t dst)
303 {
304         struct ether_addr bcast;
305         struct mbuf *m;
306         struct arphdr *ah;
307         int pktlen;
308
309         MPASS(nd_ifp != NULL);
310
311         /* Fill-up a broadcast address. */
312         memset(&bcast, 0xFF, ETHER_ADDR_LEN);
313         m = m_gethdr(M_NOWAIT, MT_DATA);
314         if (m == NULL) {
315                 printf("netdump_send_arp: Out of mbufs\n");
316                 return (ENOBUFS);
317         }
318         pktlen = arphdr_len2(ETHER_ADDR_LEN, sizeof(struct in_addr));
319         m->m_len = pktlen;
320         m->m_pkthdr.len = pktlen;
321         MH_ALIGN(m, pktlen);
322         ah = mtod(m, struct arphdr *);
323         ah->ar_hrd = htons(ARPHRD_ETHER);
324         ah->ar_pro = htons(ETHERTYPE_IP);
325         ah->ar_hln = ETHER_ADDR_LEN;
326         ah->ar_pln = sizeof(struct in_addr);
327         ah->ar_op = htons(ARPOP_REQUEST);
328         memcpy(ar_sha(ah), IF_LLADDR(nd_ifp), ETHER_ADDR_LEN);
329         ((struct in_addr *)ar_spa(ah))->s_addr = nd_client.s_addr;
330         bzero(ar_tha(ah), ETHER_ADDR_LEN);
331         ((struct in_addr *)ar_tpa(ah))->s_addr = dst;
332         return (netdump_ether_output(m, nd_ifp, bcast, ETHERTYPE_ARP));
333 }
334
335 /*
336  * Sends ARP requests to locate the server and waits for a response.
337  * We first try to ARP the server itself, and fall back to the provided
338  * gateway if the server appears to be off-link.
339  *
340  * Return value:
341  *      0 on success
342  *      errno on error
343  */
344 static int
345 netdump_arp_gw(void)
346 {
347         in_addr_t dst;
348         int error, polls, retries;
349
350         dst = nd_server.s_addr;
351 restart:
352         for (retries = 0; retries < nd_arp_retries && have_gw_mac == 0;
353             retries++) {
354                 error = netdump_send_arp(dst);
355                 if (error != 0)
356                         return (error);
357                 for (polls = 0; polls < nd_polls && have_gw_mac == 0; polls++) {
358                         netdump_network_poll();
359                         DELAY(500);
360                 }
361                 if (have_gw_mac == 0)
362                         printf("(ARP retry)");
363         }
364         if (have_gw_mac != 0)
365                 return (0);
366         if (dst == nd_server.s_addr && nd_server.s_addr != nd_gateway.s_addr) {
367                 printf("Failed to ARP server, trying to reach gateway...\n");
368                 dst = nd_gateway.s_addr;
369                 goto restart;
370         }
371
372         printf("\nARP timed out.\n");
373         return (ETIMEDOUT);
374 }
375
376 /*
377  * Dummy free function for netdump clusters.
378  */
379 static void
380 netdump_mbuf_free(struct mbuf *m __unused)
381 {
382 }
383
384 /*
385  * Construct and reliably send a netdump packet.  May fail from a resource
386  * shortage or extreme number of unacknowledged retransmissions.  Wait for
387  * an acknowledgement before returning.  Splits packets into chunks small
388  * enough to be sent without fragmentation (looks up the interface MTU)
389  *
390  * Parameters:
391  *      type    netdump packet type (HERALD, FINISHED, or VMCORE)
392  *      offset  vmcore data offset (bytes)
393  *      data    vmcore data
394  *      datalen vmcore data size (bytes)
395  *
396  * Returns:
397  *      int see errno.h, 0 for success
398  */
399 static int
400 netdump_send(uint32_t type, off_t offset, unsigned char *data, uint32_t datalen)
401 {
402         struct netdump_msg_hdr *nd_msg_hdr;
403         struct mbuf *m, *m2;
404         uint64_t want_acks;
405         uint32_t i, pktlen, sent_so_far;
406         int retries, polls, error;
407
408         want_acks = 0;
409         rcvd_acks = 0;
410         retries = 0;
411
412         MPASS(nd_ifp != NULL);
413
414 retransmit:
415         /* Chunks can be too big to fit in packets. */
416         for (i = sent_so_far = 0; sent_so_far < datalen ||
417             (i == 0 && datalen == 0); i++) {
418                 pktlen = datalen - sent_so_far;
419
420                 /* First bound: the packet structure. */
421                 pktlen = min(pktlen, NETDUMP_DATASIZE);
422
423                 /* Second bound: the interface MTU (assume no IP options). */
424                 pktlen = min(pktlen, nd_ifp->if_mtu - sizeof(struct udpiphdr) -
425                     sizeof(struct netdump_msg_hdr));
426
427                 /*
428                  * Check if it is retransmitting and this has been ACKed
429                  * already.
430                  */
431                 if ((rcvd_acks & (1 << i)) != 0) {
432                         sent_so_far += pktlen;
433                         continue;
434                 }
435
436                 /*
437                  * Get and fill a header mbuf, then chain data as an extended
438                  * mbuf.
439                  */
440                 m = m_gethdr(M_NOWAIT, MT_DATA);
441                 if (m == NULL) {
442                         printf("netdump_send: Out of mbufs\n");
443                         return (ENOBUFS);
444                 }
445                 m->m_len = sizeof(struct netdump_msg_hdr);
446                 m->m_pkthdr.len = sizeof(struct netdump_msg_hdr);
447                 MH_ALIGN(m, sizeof(struct netdump_msg_hdr));
448                 nd_msg_hdr = mtod(m, struct netdump_msg_hdr *);
449                 nd_msg_hdr->mh_seqno = htonl(nd_seqno + i);
450                 nd_msg_hdr->mh_type = htonl(type);
451                 nd_msg_hdr->mh_offset = htobe64(offset + sent_so_far);
452                 nd_msg_hdr->mh_len = htonl(pktlen);
453                 nd_msg_hdr->mh__pad = 0;
454
455                 if (pktlen != 0) {
456                         m2 = m_get(M_NOWAIT, MT_DATA);
457                         if (m2 == NULL) {
458                                 m_freem(m);
459                                 printf("netdump_send: Out of mbufs\n");
460                                 return (ENOBUFS);
461                         }
462                         MEXTADD(m2, data + sent_so_far, pktlen,
463                             netdump_mbuf_free, NULL, NULL, 0, EXT_DISPOSABLE);
464                         m2->m_len = pktlen;
465
466                         m_cat(m, m2);
467                         m->m_pkthdr.len += pktlen;
468                 }
469                 error = netdump_udp_output(m);
470                 if (error != 0)
471                         return (error);
472
473                 /* Note that we're waiting for this packet in the bitfield. */
474                 want_acks |= (1 << i);
475                 sent_so_far += pktlen;
476         }
477         if (i >= NETDUMP_MAX_IN_FLIGHT)
478                 printf("Warning: Sent more than %d packets (%d). "
479                     "Acknowledgements will fail unless the size of "
480                     "rcvd_acks/want_acks is increased.\n",
481                     NETDUMP_MAX_IN_FLIGHT, i);
482
483         /*
484          * Wait for acks.  A *real* window would speed things up considerably.
485          */
486         polls = 0;
487         while (rcvd_acks != want_acks) {
488                 if (polls++ > nd_polls) {
489                         if (retries++ > nd_retries)
490                                 return (ETIMEDOUT);
491                         printf(". ");
492                         goto retransmit;
493                 }
494                 netdump_network_poll();
495                 DELAY(500);
496         }
497         nd_seqno += i;
498         return (0);
499 }
500
501 /*
502  * Handler for IP packets: checks their sanity and then processes any netdump
503  * ACK packets it finds.
504  *
505  * It needs to replicate partially the behaviour of ip_input() and
506  * udp_input().
507  *
508  * Parameters:
509  *      mb      a pointer to an mbuf * containing the packet received
510  *              Updates *mb if m_pullup et al change the pointer
511  *              Assumes the calling function will take care of freeing the mbuf
512  */
513 static void
514 netdump_handle_ip(struct mbuf **mb)
515 {
516         struct ip *ip;
517         struct udpiphdr *udp;
518         struct netdump_ack *nd_ack;
519         struct mbuf *m;
520         int rcv_ackno;
521         unsigned short hlen;
522
523         /* IP processing. */
524         m = *mb;
525         if (m->m_pkthdr.len < sizeof(struct ip)) {
526                 NETDDEBUG("dropping packet too small for IP header\n");
527                 return;
528         }
529         if (m->m_len < sizeof(struct ip)) {
530                 m = m_pullup(m, sizeof(struct ip));
531                 *mb = m;
532                 if (m == NULL) {
533                         NETDDEBUG("m_pullup failed\n");
534                         return;
535                 }
536         }
537         ip = mtod(m, struct ip *);
538
539         /* IP version. */
540         if (ip->ip_v != IPVERSION) {
541                 NETDDEBUG("bad IP version %d\n", ip->ip_v);
542                 return;
543         }
544
545         /* Header length. */
546         hlen = ip->ip_hl << 2;
547         if (hlen < sizeof(struct ip)) {
548                 NETDDEBUG("bad IP header length (%hu)\n", hlen);
549                 return;
550         }
551         if (hlen > m->m_len) {
552                 m = m_pullup(m, hlen);
553                 *mb = m;
554                 if (m == NULL) {
555                         NETDDEBUG("m_pullup failed\n");
556                         return;
557                 }
558                 ip = mtod(m, struct ip *);
559         }
560         /* Ignore packets with IP options. */
561         if (hlen > sizeof(struct ip)) {
562                 NETDDEBUG("drop packet with IP options\n");
563                 return;
564         }
565
566 #ifdef INVARIANTS
567         if ((IN_LOOPBACK(ntohl(ip->ip_dst.s_addr)) ||
568             IN_LOOPBACK(ntohl(ip->ip_src.s_addr))) &&
569             (m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) {
570                 NETDDEBUG("Bad IP header (RFC1122)\n");
571                 return;
572         }
573 #endif
574
575         /* Checksum. */
576         if ((m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) != 0) {
577                 if ((m->m_pkthdr.csum_flags & CSUM_IP_VALID) == 0) {
578                         NETDDEBUG("bad IP checksum\n");
579                         return;
580                 }
581         } else {
582                 /* XXX */ ;
583         }
584
585         /* Convert fields to host byte order. */
586         ip->ip_len = ntohs(ip->ip_len);
587         if (ip->ip_len < hlen) {
588                 NETDDEBUG("IP packet smaller (%hu) than header (%hu)\n",
589                     ip->ip_len, hlen);
590                 return;
591         }
592         if (m->m_pkthdr.len < ip->ip_len) {
593                 NETDDEBUG("IP packet bigger (%hu) than ethernet packet (%d)\n",
594                     ip->ip_len, m->m_pkthdr.len);
595                 return;
596         }
597         if (m->m_pkthdr.len > ip->ip_len) {
598
599                 /* Truncate the packet to the IP length. */
600                 if (m->m_len == m->m_pkthdr.len) {
601                         m->m_len = ip->ip_len;
602                         m->m_pkthdr.len = ip->ip_len;
603                 } else
604                         m_adj(m, ip->ip_len - m->m_pkthdr.len);
605         }
606
607         ip->ip_off = ntohs(ip->ip_off);
608
609         /* Check that the source is the server's IP. */
610         if (ip->ip_src.s_addr != nd_server.s_addr) {
611                 NETDDEBUG("drop packet not from server (from 0x%x)\n",
612                     ip->ip_src.s_addr);
613                 return;
614         }
615
616         /* Check if the destination IP is ours. */
617         if (ip->ip_dst.s_addr != nd_client.s_addr) {
618                 NETDDEBUGV("drop packet not to our IP\n");
619                 return;
620         }
621
622         if (ip->ip_p != IPPROTO_UDP) {
623                 NETDDEBUG("drop non-UDP packet\n");
624                 return;
625         }
626
627         /* Do not deal with fragments. */
628         if ((ip->ip_off & (IP_MF | IP_OFFMASK)) != 0) {
629                 NETDDEBUG("drop fragmented packet\n");
630                 return;
631         }
632
633         /* UDP custom is to have packet length not include IP header. */
634         ip->ip_len -= hlen;
635
636         /* UDP processing. */
637
638         /* Get IP and UDP headers together, along with the netdump packet. */
639         if (m->m_pkthdr.len <
640             sizeof(struct udpiphdr) + sizeof(struct netdump_ack)) {
641                 NETDDEBUG("ignoring small packet\n");
642                 return;
643         }
644         if (m->m_len < sizeof(struct udpiphdr) + sizeof(struct netdump_ack)) {
645                 m = m_pullup(m, sizeof(struct udpiphdr) +
646                     sizeof(struct netdump_ack));
647                 *mb = m;
648                 if (m == NULL) {
649                         NETDDEBUG("m_pullup failed\n");
650                         return;
651                 }
652         }
653         udp = mtod(m, struct udpiphdr *);
654
655         if (ntohs(udp->ui_u.uh_dport) != NETDUMP_ACKPORT) {
656                 NETDDEBUG("not on the netdump port.\n");
657                 return;
658         }
659
660         /* Netdump processing. */
661
662         /*
663          * Packet is meant for us.  Extract the ack sequence number and the
664          * port number if necessary.
665          */
666         nd_ack = (struct netdump_ack *)(mtod(m, caddr_t) +
667             sizeof(struct udpiphdr));
668         rcv_ackno = ntohl(nd_ack->na_seqno);
669         if (nd_server_port == NETDUMP_PORT)
670                 nd_server_port = ntohs(udp->ui_u.uh_sport);
671         if (rcv_ackno >= nd_seqno + NETDUMP_MAX_IN_FLIGHT)
672                 printf("%s: ACK %d too far in future!\n", __func__, rcv_ackno);
673         else if (rcv_ackno >= nd_seqno) {
674                 /* We're interested in this ack. Record it. */
675                 rcvd_acks |= 1 << (rcv_ackno - nd_seqno);
676         }
677 }
678
679 /*
680  * Handler for ARP packets: checks their sanity and then
681  * 1. If the ARP is a request for our IP, respond with our MAC address
682  * 2. If the ARP is a response from our server, record its MAC address
683  *
684  * It needs to replicate partially the behaviour of arpintr() and
685  * in_arpinput().
686  *
687  * Parameters:
688  *      mb      a pointer to an mbuf * containing the packet received
689  *              Updates *mb if m_pullup et al change the pointer
690  *              Assumes the calling function will take care of freeing the mbuf
691  */
692 static void
693 netdump_handle_arp(struct mbuf **mb)
694 {
695         char buf[INET_ADDRSTRLEN];
696         struct in_addr isaddr, itaddr, myaddr;
697         struct ether_addr dst;
698         struct mbuf *m;
699         struct arphdr *ah;
700         struct ifnet *ifp;
701         uint8_t *enaddr;
702         int req_len, op;
703
704         m = *mb;
705         ifp = m->m_pkthdr.rcvif;
706         if (m->m_len < sizeof(struct arphdr)) {
707                 m = m_pullup(m, sizeof(struct arphdr));
708                 *mb = m;
709                 if (m == NULL) {
710                         NETDDEBUG("runt packet: m_pullup failed\n");
711                         return;
712                 }
713         }
714
715         ah = mtod(m, struct arphdr *);
716         if (ntohs(ah->ar_hrd) != ARPHRD_ETHER) {
717                 NETDDEBUG("unknown hardware address 0x%2D)\n",
718                     (unsigned char *)&ah->ar_hrd, "");
719                 return;
720         }
721         if (ntohs(ah->ar_pro) != ETHERTYPE_IP) {
722                 NETDDEBUG("drop ARP for unknown protocol %d\n",
723                     ntohs(ah->ar_pro));
724                 return;
725         }
726         req_len = arphdr_len2(ifp->if_addrlen, sizeof(struct in_addr));
727         if (m->m_len < req_len) {
728                 m = m_pullup(m, req_len);
729                 *mb = m;
730                 if (m == NULL) {
731                         NETDDEBUG("runt packet: m_pullup failed\n");
732                         return;
733                 }
734         }
735         ah = mtod(m, struct arphdr *);
736
737         op = ntohs(ah->ar_op);
738         memcpy(&isaddr, ar_spa(ah), sizeof(isaddr));
739         memcpy(&itaddr, ar_tpa(ah), sizeof(itaddr));
740         enaddr = (uint8_t *)IF_LLADDR(ifp);
741         myaddr = nd_client;
742
743         if (memcmp(ar_sha(ah), enaddr, ifp->if_addrlen) == 0) {
744                 NETDDEBUG("ignoring ARP from myself\n");
745                 return;
746         }
747
748         if (isaddr.s_addr == nd_client.s_addr) {
749                 printf("%s: %*D is using my IP address %s!\n", __func__,
750                     ifp->if_addrlen, (u_char *)ar_sha(ah), ":",
751                     inet_ntoa_r(isaddr, buf));
752                 return;
753         }
754
755         if (memcmp(ar_sha(ah), ifp->if_broadcastaddr, ifp->if_addrlen) == 0) {
756                 NETDDEBUG("ignoring ARP from broadcast address\n");
757                 return;
758         }
759
760         if (op == ARPOP_REPLY) {
761                 if (isaddr.s_addr != nd_gateway.s_addr &&
762                     isaddr.s_addr != nd_server.s_addr) {
763                         inet_ntoa_r(isaddr, buf);
764                         NETDDEBUG(
765                             "ignoring ARP reply from %s (not netdump server)\n",
766                             buf);
767                         return;
768                 }
769                 memcpy(nd_gw_mac.octet, ar_sha(ah),
770                     min(ah->ar_hln, ETHER_ADDR_LEN));
771                 have_gw_mac = 1;
772                 NETDDEBUG("got server MAC address %6D\n", nd_gw_mac.octet, ":");
773                 return;
774         }
775
776         if (op != ARPOP_REQUEST) {
777                 NETDDEBUG("ignoring ARP non-request/reply\n");
778                 return;
779         }
780
781         if (itaddr.s_addr != nd_client.s_addr) {
782                 NETDDEBUG("ignoring ARP not to our IP\n");
783                 return;
784         }
785
786         memcpy(ar_tha(ah), ar_sha(ah), ah->ar_hln);
787         memcpy(ar_sha(ah), enaddr, ah->ar_hln);
788         memcpy(ar_tpa(ah), ar_spa(ah), ah->ar_pln);
789         memcpy(ar_spa(ah), &itaddr, ah->ar_pln);
790         ah->ar_op = htons(ARPOP_REPLY);
791         ah->ar_pro = htons(ETHERTYPE_IP);
792         m->m_flags &= ~(M_BCAST|M_MCAST);
793         m->m_len = arphdr_len(ah);
794         m->m_pkthdr.len = m->m_len;
795
796         memcpy(dst.octet, ar_tha(ah), ETHER_ADDR_LEN);
797         netdump_ether_output(m, ifp, dst, ETHERTYPE_ARP);
798         *mb = NULL;
799 }
800
801 /*
802  * Handler for incoming packets directly from the network adapter
803  * Identifies the packet type (IP or ARP) and passes it along to one of the
804  * helper functions netdump_handle_ip or netdump_handle_arp.
805  *
806  * It needs to replicate partially the behaviour of ether_input() and
807  * ether_demux().
808  *
809  * Parameters:
810  *      ifp     the interface the packet came from (should be nd_ifp)
811  *      m       an mbuf containing the packet received
812  */
813 static void
814 netdump_pkt_in(struct ifnet *ifp, struct mbuf *m)
815 {
816         struct ifreq ifr;
817         struct ether_header *eh;
818         u_short etype;
819
820         /* Ethernet processing. */
821         if ((m->m_flags & M_PKTHDR) == 0) {
822                 NETDDEBUG_IF(ifp, "discard frame without packet header\n");
823                 goto done;
824         }
825         if (m->m_len < ETHER_HDR_LEN) {
826                 NETDDEBUG_IF(ifp,
827             "discard frame without leading eth header (len %u pktlen %u)\n",
828                     m->m_len, m->m_pkthdr.len);
829                 goto done;
830         }
831         if ((m->m_flags & M_HASFCS) != 0) {
832                 m_adj(m, -ETHER_CRC_LEN);
833                 m->m_flags &= ~M_HASFCS;
834         }
835         eh = mtod(m, struct ether_header *);
836         etype = ntohs(eh->ether_type);
837         if ((m->m_flags & M_VLANTAG) != 0 || etype == ETHERTYPE_VLAN) {
838                 NETDDEBUG_IF(ifp, "ignoring vlan packets\n");
839                 goto done;
840         }
841         if (if_gethwaddr(ifp, &ifr) != 0) {
842                 NETDDEBUG_IF(ifp, "failed to get hw addr for interface\n");
843                 goto done;
844         }
845         if (memcmp(ifr.ifr_addr.sa_data, eh->ether_dhost,
846             ETHER_ADDR_LEN) != 0) {
847                 NETDDEBUG_IF(ifp,
848                     "discard frame with incorrect destination addr\n");
849                 goto done;
850         }
851
852         /* Done ethernet processing. Strip off the ethernet header. */
853         m_adj(m, ETHER_HDR_LEN);
854         switch (etype) {
855         case ETHERTYPE_ARP:
856                 netdump_handle_arp(&m);
857                 break;
858         case ETHERTYPE_IP:
859                 netdump_handle_ip(&m);
860                 break;
861         default:
862                 NETDDEBUG_IF(ifp, "dropping unknown ethertype %hu\n", etype);
863                 break;
864         }
865 done:
866         if (m != NULL)
867                 m_freem(m);
868 }
869
870 /*
871  * After trapping, instead of assuming that most of the network stack is sane,
872  * we just poll the driver directly for packets.
873  */
874 static void
875 netdump_network_poll(void)
876 {
877
878         MPASS(nd_ifp != NULL);
879
880         nd_ifp->if_netdump_methods->nd_poll(nd_ifp, 1000);
881 }
882
883 /*-
884  * Dumping specific primitives.
885  */
886
887 /*
888  * Callback from dumpsys() to dump a chunk of memory.
889  * Copies it out to our static buffer then sends it across the network.
890  * Detects the initial KDH and makes sure it is given a special packet type.
891  *
892  * Parameters:
893  *      priv     Unused. Optional private pointer.
894  *      virtual  Virtual address (where to read the data from)
895  *      physical Unused. Physical memory address.
896  *      offset   Offset from start of core file
897  *      length   Data length
898  *
899  * Return value:
900  *      0 on success
901  *      errno on error
902  */
903 static int
904 netdump_dumper(void *priv __unused, void *virtual,
905     vm_offset_t physical __unused, off_t offset, size_t length)
906 {
907         int error;
908
909         NETDDEBUGV("netdump_dumper(NULL, %p, NULL, %ju, %zu)\n",
910             virtual, (uintmax_t)offset, length);
911
912         if (virtual == NULL) {
913                 if (dump_failed != 0)
914                         printf("failed to dump the kernel core\n");
915                 else if (netdump_send(NETDUMP_FINISHED, 0, NULL, 0) != 0)
916                         printf("failed to close the transaction\n");
917                 else
918                         printf("\nnetdump finished.\n");
919                 netdump_cleanup();
920                 return (0);
921         }
922         if (length > sizeof(nd_buf))
923                 return (ENOSPC);
924
925         memmove(nd_buf, virtual, length);
926         error = netdump_send(NETDUMP_VMCORE, offset, nd_buf, length);
927         if (error != 0) {
928                 dump_failed = 1;
929                 return (error);
930         }
931         return (0);
932 }
933
934 /*
935  * Perform any initalization needed prior to transmitting the kernel core.
936  */
937 static int
938 netdump_start(struct dumperinfo *di)
939 {
940         char *path;
941         char buf[INET_ADDRSTRLEN];
942         uint32_t len;
943         int error;
944
945         error = 0;
946
947         /* Check if the dumping is allowed to continue. */
948         if (nd_enabled == 0)
949                 return (EINVAL);
950
951         if (panicstr == NULL) {
952                 printf(
953                     "netdump_start: netdump may only be used after a panic\n");
954                 return (EINVAL);
955         }
956
957         MPASS(nd_ifp != NULL);
958
959         if (nd_server.s_addr == INADDR_ANY) {
960                 printf("netdump_start: can't netdump; no server IP given\n");
961                 return (EINVAL);
962         }
963         if (nd_client.s_addr == INADDR_ANY) {
964                 printf("netdump_start: can't netdump; no client IP given\n");
965                 return (EINVAL);
966         }
967
968         /* We start dumping at offset 0. */
969         di->dumpoff = 0;
970
971         nd_seqno = 1;
972
973         /*
974          * nd_server_port could have switched after the first ack the
975          * first time it gets called.  Adjust it accordingly.
976          */
977         nd_server_port = NETDUMP_PORT;
978
979         /* Switch to the netdump mbuf zones. */
980         netdump_mbuf_dump();
981
982         nd_ifp->if_netdump_methods->nd_event(nd_ifp, NETDUMP_START);
983
984         /* Make the card use *our* receive callback. */
985         drv_if_input = nd_ifp->if_input;
986         nd_ifp->if_input = netdump_pkt_in;
987
988         if (nd_gateway.s_addr == INADDR_ANY) {
989                 restore_gw_addr = 1;
990                 nd_gateway.s_addr = nd_server.s_addr;
991         }
992
993         printf("netdump in progress. searching for server...\n");
994         if (netdump_arp_gw()) {
995                 printf("failed to locate server MAC address\n");
996                 error = EINVAL;
997                 goto trig_abort;
998         }
999
1000         if (nd_path[0] != '\0') {
1001                 path = nd_path;
1002                 len = strlen(path) + 1;
1003         } else {
1004                 path = NULL;
1005                 len = 0;
1006         }
1007         if (netdump_send(NETDUMP_HERALD, 0, path, len) != 0) {
1008                 printf("failed to contact netdump server\n");
1009                 error = EINVAL;
1010                 goto trig_abort;
1011         }
1012         printf("netdumping to %s (%6D)\n", inet_ntoa_r(nd_server, buf),
1013             nd_gw_mac.octet, ":");
1014         return (0);
1015
1016 trig_abort:
1017         netdump_cleanup();
1018         return (error);
1019 }
1020
1021 static int
1022 netdump_write_headers(struct dumperinfo *di, struct kerneldumpheader *kdh,
1023     void *key, uint32_t keysize)
1024 {
1025         int error;
1026
1027         memcpy(nd_buf, kdh, sizeof(*kdh));
1028         error = netdump_send(NETDUMP_KDH, 0, nd_buf, sizeof(*kdh));
1029         if (error == 0 && keysize > 0) {
1030                 if (keysize > sizeof(nd_buf))
1031                         return (EINVAL);
1032                 memcpy(nd_buf, key, keysize);
1033                 error = netdump_send(NETDUMP_EKCD_KEY, 0, nd_buf, keysize);
1034         }
1035         return (error);
1036 }
1037
1038 /*
1039  * Cleanup routine for a possibly failed netdump.
1040  */
1041 static void
1042 netdump_cleanup(void)
1043 {
1044
1045         if (restore_gw_addr != 0) {
1046                 nd_gateway.s_addr = INADDR_ANY;
1047                 restore_gw_addr = 0;
1048         }
1049         if (drv_if_input != NULL) {
1050                 nd_ifp->if_input = drv_if_input;
1051                 drv_if_input = NULL;
1052         }
1053         nd_ifp->if_netdump_methods->nd_event(nd_ifp, NETDUMP_END);
1054 }
1055
1056 /*-
1057  * KLD specific code.
1058  */
1059
1060 static struct cdevsw netdump_cdevsw = {
1061         .d_version =    D_VERSION,
1062         .d_ioctl =      netdump_ioctl,
1063         .d_name =       "netdump",
1064 };
1065
1066 static struct cdev *netdump_cdev;
1067
1068 static int
1069 netdump_configure(struct diocskerneldump_arg *conf, struct thread *td)
1070 {
1071         struct epoch_tracker et;
1072         struct ifnet *ifp;
1073
1074         CURVNET_SET(TD_TO_VNET(td));
1075         if (!IS_DEFAULT_VNET(curvnet)) {
1076                 CURVNET_RESTORE();
1077                 return (EINVAL);
1078         }
1079         NET_EPOCH_ENTER(et);
1080         CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1081                 if (strcmp(ifp->if_xname, conf->kda_iface) == 0)
1082                         break;
1083         }
1084         /* XXX ref */
1085         NET_EPOCH_EXIT(et);
1086         CURVNET_RESTORE();
1087
1088         if (ifp == NULL)
1089                 return (ENOENT);
1090         if ((if_getflags(ifp) & IFF_UP) == 0)
1091                 return (ENXIO);
1092         if (!netdump_supported_nic(ifp) || ifp->if_type != IFT_ETHER)
1093                 return (ENODEV);
1094
1095         nd_ifp = ifp;
1096
1097         netdump_reinit(ifp);
1098 #define COPY_SIZED(elm) do {    \
1099         _Static_assert(sizeof(nd_conf.ndc_ ## elm) ==                   \
1100             sizeof(conf->kda_ ## elm), "elm " __XSTRING(elm) " mismatch"); \
1101         memcpy(&nd_conf.ndc_ ## elm, &conf->kda_ ## elm,                \
1102             sizeof(nd_conf.ndc_ ## elm));                               \
1103 } while (0)
1104         COPY_SIZED(iface);
1105         COPY_SIZED(server);
1106         COPY_SIZED(client);
1107         COPY_SIZED(gateway);
1108         COPY_SIZED(af);
1109 #undef COPY_SIZED
1110         nd_enabled = 1;
1111         return (0);
1112 }
1113
1114 /*
1115  * Reinitialize the mbuf pool used by drivers while dumping. This is called
1116  * from the generic ioctl handler for SIOCSIFMTU after the driver has
1117  * reconfigured itself.
1118  */
1119 void
1120 netdump_reinit(struct ifnet *ifp)
1121 {
1122         int clsize, nmbuf, ncl, nrxr;
1123
1124         if (ifp != nd_ifp)
1125                 return;
1126
1127         ifp->if_netdump_methods->nd_init(ifp, &nrxr, &ncl, &clsize);
1128         KASSERT(nrxr > 0, ("invalid receive ring count %d", nrxr));
1129
1130         /*
1131          * We need two headers per message on the transmit side. Multiply by
1132          * four to give us some breathing room.
1133          */
1134         nmbuf = ncl * (4 + nrxr);
1135         ncl *= nrxr;
1136         netdump_mbuf_reinit(nmbuf, ncl, clsize);
1137 }
1138
1139 /*
1140  * ioctl(2) handler for the netdump device. This is currently only used to
1141  * register netdump as a dump device.
1142  *
1143  * Parameters:
1144  *     dev, Unused.
1145  *     cmd, The ioctl to be handled.
1146  *     addr, The parameter for the ioctl.
1147  *     flags, Unused.
1148  *     td, The thread invoking this ioctl.
1149  *
1150  * Returns:
1151  *     0 on success, and an errno value on failure.
1152  */
1153 static int
1154 netdump_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t addr,
1155     int flags __unused, struct thread *td)
1156 {
1157         struct diocskerneldump_arg kda_copy, *conf;
1158         struct dumperinfo dumper;
1159         uint8_t *encryptedkey;
1160         int error;
1161 #ifdef COMPAT_FREEBSD11
1162         u_int u;
1163 #endif
1164 #ifdef COMPAT_FREEBSD12
1165         struct diocskerneldump_arg_freebsd12 *kda12;
1166         struct netdump_conf_freebsd12 *conf12;
1167 #endif
1168
1169         conf = NULL;
1170         error = 0;
1171         switch (cmd) {
1172 #ifdef COMPAT_FREEBSD11
1173         case DIOCSKERNELDUMP_FREEBSD11:
1174                 gone_in(13, "11.x ABI compatibility");
1175                 u = *(u_int *)addr;
1176                 if (u != 0) {
1177                         error = ENXIO;
1178                         break;
1179                 }
1180                 if (nd_enabled) {
1181                         nd_enabled = 0;
1182                         netdump_mbuf_drain();
1183                 }
1184                 break;
1185 #endif
1186 #ifdef COMPAT_FREEBSD12
1187                 /*
1188                  * Used by dumpon(8) in 12.x for clearing previous
1189                  * configuration -- then NETDUMPSCONF_FREEBSD12 is used to
1190                  * actually configure netdump.
1191                  */
1192         case DIOCSKERNELDUMP_FREEBSD12:
1193                 gone_in(14, "12.x ABI compatibility");
1194
1195                 kda12 = (void *)addr;
1196                 if (kda12->kda12_enable) {
1197                         error = ENXIO;
1198                         break;
1199                 }
1200                 if (nd_enabled) {
1201                         nd_enabled = 0;
1202                         netdump_mbuf_drain();
1203                 }
1204                 break;
1205
1206         case NETDUMPGCONF_FREEBSD12:
1207                 gone_in(14, "FreeBSD 12.x ABI compat");
1208                 conf12 = (void *)addr;
1209
1210                 if (!nd_enabled) {
1211                         error = ENXIO;
1212                         break;
1213                 }
1214                 if (nd_conf.ndc_af != AF_INET) {
1215                         error = EOPNOTSUPP;
1216                         break;
1217                 }
1218
1219                 strlcpy(conf12->ndc12_iface, nd_ifp->if_xname,
1220                     sizeof(conf12->ndc12_iface));
1221                 memcpy(&conf12->ndc12_server, &nd_server,
1222                     sizeof(conf12->ndc12_server));
1223                 memcpy(&conf12->ndc12_client, &nd_client,
1224                     sizeof(conf12->ndc12_client));
1225                 memcpy(&conf12->ndc12_gateway, &nd_gateway,
1226                     sizeof(conf12->ndc12_gateway));
1227                 break;
1228 #endif
1229         case DIOCGKERNELDUMP:
1230                 conf = (void *)addr;
1231                 /*
1232                  * For now, index is ignored; netdump doesn't support multiple
1233                  * configurations (yet).
1234                  */
1235                 if (!nd_enabled) {
1236                         error = ENXIO;
1237                         conf = NULL;
1238                         break;
1239                 }
1240
1241                 strlcpy(conf->kda_iface, nd_ifp->if_xname,
1242                     sizeof(conf->kda_iface));
1243                 memcpy(&conf->kda_server, &nd_server, sizeof(nd_server));
1244                 memcpy(&conf->kda_client, &nd_client, sizeof(nd_client));
1245                 memcpy(&conf->kda_gateway, &nd_gateway, sizeof(nd_gateway));
1246                 conf->kda_af = nd_conf.ndc_af;
1247                 conf = NULL;
1248                 break;
1249
1250 #ifdef COMPAT_FREEBSD12
1251         case NETDUMPSCONF_FREEBSD12:
1252                 gone_in(14, "FreeBSD 12.x ABI compat");
1253
1254                 conf12 = (struct netdump_conf_freebsd12 *)addr;
1255
1256                 _Static_assert(offsetof(struct diocskerneldump_arg, kda_server)
1257                     == offsetof(struct netdump_conf_freebsd12, ndc12_server),
1258                     "simplifying assumption");
1259
1260                 memset(&kda_copy, 0, sizeof(kda_copy));
1261                 memcpy(&kda_copy, conf12,
1262                     offsetof(struct diocskerneldump_arg, kda_server));
1263
1264                 /* 12.x ABI could only configure IPv4 (INET) netdump. */
1265                 kda_copy.kda_af = AF_INET;
1266                 memcpy(&kda_copy.kda_server.in4, &conf12->ndc12_server,
1267                     sizeof(struct in_addr));
1268                 memcpy(&kda_copy.kda_client.in4, &conf12->ndc12_client,
1269                     sizeof(struct in_addr));
1270                 memcpy(&kda_copy.kda_gateway.in4, &conf12->ndc12_gateway,
1271                     sizeof(struct in_addr));
1272
1273                 kda_copy.kda_index =
1274                     (conf12->ndc12_kda.kda12_enable ? 0 : KDA_REMOVE_ALL);
1275
1276                 conf = &kda_copy;
1277                 explicit_bzero(conf12, sizeof(*conf12));
1278                 /* FALLTHROUGH */
1279 #endif
1280         case DIOCSKERNELDUMP:
1281                 encryptedkey = NULL;
1282                 if (cmd == DIOCSKERNELDUMP) {
1283                         conf = (void *)addr;
1284                         memcpy(&kda_copy, conf, sizeof(kda_copy));
1285                 }
1286                 /* Netdump only supports IP4 at this time. */
1287                 if (conf->kda_af != AF_INET) {
1288                         error = EPROTONOSUPPORT;
1289                         break;
1290                 }
1291
1292                 conf->kda_iface[sizeof(conf->kda_iface) - 1] = '\0';
1293                 if (conf->kda_index == KDA_REMOVE ||
1294                     conf->kda_index == KDA_REMOVE_DEV ||
1295                     conf->kda_index == KDA_REMOVE_ALL) {
1296                         if (nd_enabled || conf->kda_index == KDA_REMOVE_ALL) {
1297                                 error = dumper_remove(conf->kda_iface, conf);
1298                                 if (error == 0) {
1299                                         nd_enabled = 0;
1300                                         netdump_mbuf_drain();
1301                                 }
1302                         }
1303                         break;
1304                 }
1305
1306                 error = netdump_configure(conf, td);
1307                 if (error != 0)
1308                         break;
1309
1310                 if (conf->kda_encryption != KERNELDUMP_ENC_NONE) {
1311                         if (conf->kda_encryptedkeysize <= 0 ||
1312                             conf->kda_encryptedkeysize >
1313                             KERNELDUMP_ENCKEY_MAX_SIZE) {
1314                                 error = EINVAL;
1315                                 break;
1316                         }
1317                         encryptedkey = malloc(conf->kda_encryptedkeysize,
1318                             M_TEMP, M_WAITOK);
1319                         error = copyin(conf->kda_encryptedkey, encryptedkey,
1320                             conf->kda_encryptedkeysize);
1321                         if (error != 0) {
1322                                 free(encryptedkey, M_TEMP);
1323                                 break;
1324                         }
1325
1326                         conf->kda_encryptedkey = encryptedkey;
1327                 }
1328
1329                 memset(&dumper, 0, sizeof(dumper));
1330                 dumper.dumper_start = netdump_start;
1331                 dumper.dumper_hdr = netdump_write_headers;
1332                 dumper.dumper = netdump_dumper;
1333                 dumper.priv = NULL;
1334                 dumper.blocksize = NETDUMP_DATASIZE;
1335                 dumper.maxiosize = MAXDUMPPGS * PAGE_SIZE;
1336                 dumper.mediaoffset = 0;
1337                 dumper.mediasize = 0;
1338
1339                 error = dumper_insert(&dumper, conf->kda_iface, conf);
1340                 if (encryptedkey != NULL) {
1341                         explicit_bzero(encryptedkey,
1342                             conf->kda_encryptedkeysize);
1343                         free(encryptedkey, M_TEMP);
1344                 }
1345                 if (error != 0) {
1346                         nd_enabled = 0;
1347                         netdump_mbuf_drain();
1348                 }
1349                 break;
1350         default:
1351                 error = ENOTTY;
1352                 break;
1353         }
1354         explicit_bzero(&kda_copy, sizeof(kda_copy));
1355         if (conf != NULL)
1356                 explicit_bzero(conf, sizeof(*conf));
1357         return (error);
1358 }
1359
1360 /*
1361  * Called upon system init or kld load.  Initializes the netdump parameters to
1362  * sane defaults (locates the first available NIC and uses the first IPv4 IP on
1363  * that card as the client IP).  Leaves the server IP unconfigured.
1364  *
1365  * Parameters:
1366  *      mod, Unused.
1367  *      what, The module event type.
1368  *      priv, Unused.
1369  *
1370  * Returns:
1371  *      int, An errno value if an error occured, 0 otherwise.
1372  */
1373 static int
1374 netdump_modevent(module_t mod __unused, int what, void *priv __unused)
1375 {
1376         struct diocskerneldump_arg conf;
1377         char *arg;
1378         int error;
1379
1380         error = 0;
1381         switch (what) {
1382         case MOD_LOAD:
1383                 error = make_dev_p(MAKEDEV_WAITOK, &netdump_cdev,
1384                     &netdump_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600, "netdump");
1385                 if (error != 0)
1386                         return (error);
1387
1388                 if ((arg = kern_getenv("net.dump.iface")) != NULL) {
1389                         strlcpy(conf.kda_iface, arg, sizeof(conf.kda_iface));
1390                         freeenv(arg);
1391
1392                         if ((arg = kern_getenv("net.dump.server")) != NULL) {
1393                                 inet_aton(arg, &conf.kda_server.in4);
1394                                 freeenv(arg);
1395                         }
1396                         if ((arg = kern_getenv("net.dump.client")) != NULL) {
1397                                 inet_aton(arg, &conf.kda_client.in4);
1398                                 freeenv(arg);
1399                         }
1400                         if ((arg = kern_getenv("net.dump.gateway")) != NULL) {
1401                                 inet_aton(arg, &conf.kda_gateway.in4);
1402                                 freeenv(arg);
1403                         }
1404                         conf.kda_af = AF_INET;
1405
1406                         /* Ignore errors; we print a message to the console. */
1407                         (void)netdump_configure(&conf, curthread);
1408                 }
1409                 break;
1410         case MOD_UNLOAD:
1411                 if (nd_enabled) {
1412                         struct diocskerneldump_arg kda;
1413
1414                         printf("netdump: disabling dump device for unload\n");
1415
1416                         bzero(&kda, sizeof(kda));
1417                         kda.kda_index = KDA_REMOVE_DEV;
1418                         (void)dumper_remove(nd_conf.ndc_iface, &kda);
1419
1420                         netdump_mbuf_drain();
1421                         nd_enabled = 0;
1422                 }
1423                 destroy_dev(netdump_cdev);
1424                 break;
1425         default:
1426                 error = EOPNOTSUPP;
1427                 break;
1428         }
1429         return (error);
1430 }
1431
1432 static moduledata_t netdump_mod = {
1433         "netdump",
1434         netdump_modevent,
1435         NULL,
1436 };
1437
1438 MODULE_VERSION(netdump, 1);
1439 DECLARE_MODULE(netdump, netdump_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);