kernel - remove mapzone
[dragonfly.git] / sys / netinet / udp_usrreq.c
blob103a5f8c94ba55cf701f494f589b0826a128ad72
1 /*
2 * Copyright (c) 2004 Jeffrey M. Hsu. All rights reserved.
3 * Copyright (c) 2004 The DragonFly Project. All rights reserved.
5 * This code is derived from software contributed to The DragonFly Project
6 * by Jeffrey M. Hsu.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of The DragonFly Project nor the names of its
17 * contributors may be used to endorse or promote products derived
18 * from this software without specific, prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
35 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
36 * The Regents of the University of California. All rights reserved.
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
40 * are met:
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. Neither the name of the University nor the names of its contributors
47 * may be used to endorse or promote products derived from this software
48 * without specific prior written permission.
50 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60 * SUCH DAMAGE.
62 * @(#)udp_usrreq.c 8.6 (Berkeley) 5/23/95
63 * $FreeBSD: src/sys/netinet/udp_usrreq.c,v 1.64.2.18 2003/01/24 05:11:34 sam Exp $
66 #include "opt_ipsec.h"
67 #include "opt_inet6.h"
69 #include <sys/param.h>
70 #include <sys/systm.h>
71 #include <sys/kernel.h>
72 #include <sys/malloc.h>
73 #include <sys/mbuf.h>
74 #include <sys/domain.h>
75 #include <sys/proc.h>
76 #include <sys/priv.h>
77 #include <sys/protosw.h>
78 #include <sys/socket.h>
79 #include <sys/socketvar.h>
80 #include <sys/sysctl.h>
81 #include <sys/syslog.h>
82 #include <sys/in_cksum.h>
83 #include <sys/ktr.h>
85 #include <sys/thread2.h>
86 #include <sys/socketvar2.h>
87 #include <sys/serialize.h>
89 #include <machine/stdarg.h>
91 #include <net/if.h>
92 #include <net/route.h>
93 #include <net/netmsg2.h>
94 #include <net/netisr2.h>
96 #include <netinet/in.h>
97 #include <netinet/in_systm.h>
98 #include <netinet/ip.h>
99 #ifdef INET6
100 #include <netinet/ip6.h>
101 #endif
102 #include <netinet/in_pcb.h>
103 #include <netinet/in_var.h>
104 #include <netinet/ip_var.h>
105 #ifdef INET6
106 #include <netinet6/ip6_var.h>
107 #endif
108 #include <netinet/ip_icmp.h>
109 #include <netinet/icmp_var.h>
110 #include <netinet/udp.h>
111 #include <netinet/udp_var.h>
113 #ifdef FAST_IPSEC
114 #include <netproto/ipsec/ipsec.h>
115 #endif
117 #ifdef IPSEC
118 #include <netinet6/ipsec.h>
119 #endif
121 #define MSGF_UDP_SEND MSGF_PROTO1
123 #define INP_DIRECT_DETACH INP_FLAG_PROTO2
125 #define UDP_KTR_STRING "inp=%p"
126 #define UDP_KTR_ARGS struct inpcb *inp
128 #ifndef KTR_UDP
129 #define KTR_UDP KTR_ALL
130 #endif
132 KTR_INFO_MASTER(udp);
133 KTR_INFO(KTR_UDP, udp, send_beg, 0, UDP_KTR_STRING, UDP_KTR_ARGS);
134 KTR_INFO(KTR_UDP, udp, send_end, 1, UDP_KTR_STRING, UDP_KTR_ARGS);
135 KTR_INFO(KTR_UDP, udp, send_ipout, 2, UDP_KTR_STRING, UDP_KTR_ARGS);
136 KTR_INFO(KTR_UDP, udp, redisp_ipout_beg, 3, UDP_KTR_STRING, UDP_KTR_ARGS);
137 KTR_INFO(KTR_UDP, udp, redisp_ipout_end, 4, UDP_KTR_STRING, UDP_KTR_ARGS);
138 KTR_INFO(KTR_UDP, udp, send_redisp, 5, UDP_KTR_STRING, UDP_KTR_ARGS);
139 KTR_INFO(KTR_UDP, udp, send_inswildcard, 6, UDP_KTR_STRING, UDP_KTR_ARGS);
141 #define logudp(name, inp) KTR_LOG(udp_##name, inp)
144 * UDP protocol implementation.
145 * Per RFC 768, August, 1980.
147 #ifndef COMPAT_42
148 static int udpcksum = 1;
149 #else
150 static int udpcksum = 0; /* XXX */
151 #endif
152 SYSCTL_INT(_net_inet_udp, UDPCTL_CHECKSUM, checksum, CTLFLAG_RW,
153 &udpcksum, 0, "Enable checksumming of UDP packets");
155 int log_in_vain = 0;
156 SYSCTL_INT(_net_inet_udp, OID_AUTO, log_in_vain, CTLFLAG_RW,
157 &log_in_vain, 0, "Log all incoming UDP packets");
159 static int blackhole = 0;
160 SYSCTL_INT(_net_inet_udp, OID_AUTO, blackhole, CTLFLAG_RW,
161 &blackhole, 0, "Do not send port unreachables for refused connects");
163 static int strict_mcast_mship = 1;
164 SYSCTL_INT(_net_inet_udp, OID_AUTO, strict_mcast_mship, CTLFLAG_RW,
165 &strict_mcast_mship, 0, "Only send multicast to member sockets");
167 int udp_sosend_async = 1;
168 SYSCTL_INT(_net_inet_udp, OID_AUTO, sosend_async, CTLFLAG_RW,
169 &udp_sosend_async, 0, "UDP asynchronized pru_send");
171 int udp_sosend_prepend = 1;
172 SYSCTL_INT(_net_inet_udp, OID_AUTO, sosend_prepend, CTLFLAG_RW,
173 &udp_sosend_prepend, 0,
174 "Prepend enough space for proto and link header in pru_send");
176 static int udp_reuseport_ext = 1;
177 SYSCTL_INT(_net_inet_udp, OID_AUTO, reuseport_ext, CTLFLAG_RW,
178 &udp_reuseport_ext, 0, "SO_REUSEPORT extension");
180 struct inpcbinfo udbinfo[MAXCPU];
182 #ifndef UDBHASHSIZE
183 #define UDBHASHSIZE 16
184 #endif
186 struct udpstat udpstat_percpu[MAXCPU] __cachealign;
188 static void udp_append(struct inpcb *last, struct ip *ip,
189 struct mbuf *n, int off, struct sockaddr_in *udp_in);
191 static int udp_connect_oncpu(struct inpcb *inp, struct sockaddr_in *sin,
192 struct sockaddr_in *if_sin);
194 static boolean_t udp_inswildcardhash(struct inpcb *inp,
195 struct netmsg_base *msg, int error);
196 static void udp_remwildcardhash(struct inpcb *inp);
198 static __inline int
199 udp_lportcpu(short lport)
201 return (ntohs(lport) & ncpus2_mask);
204 void
205 udp_init(void)
207 struct inpcbportinfo *portinfo;
208 int cpu;
210 portinfo = kmalloc_cachealign(sizeof(*portinfo) * ncpus2, M_PCB,
211 M_WAITOK);
213 for (cpu = 0; cpu < ncpus2; cpu++) {
214 struct inpcbinfo *uicb = &udbinfo[cpu];
217 * NOTE:
218 * UDP pcb list, wildcard hash table and localgroup hash
219 * table are shared.
221 in_pcbinfo_init(uicb, cpu, TRUE);
222 uicb->hashbase = hashinit(UDBHASHSIZE, M_PCB, &uicb->hashmask);
224 in_pcbportinfo_init(&portinfo[cpu], UDBHASHSIZE, cpu);
225 uicb->portinfo = portinfo;
226 uicb->portinfo_mask = ncpus2_mask;
228 uicb->wildcardhashbase = hashinit(UDBHASHSIZE, M_PCB,
229 &uicb->wildcardhashmask);
230 uicb->localgrphashbase = hashinit(UDBHASHSIZE, M_PCB,
231 &uicb->localgrphashmask);
233 uicb->ipi_size = sizeof(struct inpcb);
237 * Initialize UDP statistics counters for each CPU.
239 for (cpu = 0; cpu < ncpus; ++cpu)
240 bzero(&udpstat_percpu[cpu], sizeof(struct udpstat));
243 static int
244 sysctl_udpstat(SYSCTL_HANDLER_ARGS)
246 int cpu, error = 0;
248 for (cpu = 0; cpu < ncpus; ++cpu) {
249 if ((error = SYSCTL_OUT(req, &udpstat_percpu[cpu],
250 sizeof(struct udpstat))))
251 break;
252 if ((error = SYSCTL_IN(req, &udpstat_percpu[cpu],
253 sizeof(struct udpstat))))
254 break;
257 return (error);
259 SYSCTL_PROC(_net_inet_udp, UDPCTL_STATS, stats, (CTLTYPE_OPAQUE | CTLFLAG_RW),
260 0, 0, sysctl_udpstat, "S,udpstat", "UDP statistics");
262 void
263 udp_ctloutput(netmsg_t msg)
265 struct socket *so = msg->base.nm_so;
266 struct sockopt *sopt = msg->ctloutput.nm_sopt;
267 struct inpcb *inp = so->so_pcb;
269 if (inp == NULL) {
270 lwkt_replymsg(&msg->lmsg, EINVAL);
271 return;
274 if (sopt->sopt_level == IPPROTO_IP && sopt->sopt_dir == SOPT_SET) {
275 switch (sopt->sopt_name) {
276 case IP_MULTICAST_IF:
277 case IP_MULTICAST_VIF:
278 case IP_MULTICAST_TTL:
279 case IP_MULTICAST_LOOP:
280 case IP_ADD_MEMBERSHIP:
281 case IP_DROP_MEMBERSHIP:
283 * This pr_ctloutput msg will be forwarded
284 * to netisr0 to run; we can't do direct
285 * detaching anymore.
287 * NOTE:
288 * Don't optimize for the sockets whose
289 * current so_port is netisr0's msgport.
290 * These sockets could be connect(2)'ed
291 * later and the so_port will be changed.
293 inp->inp_flags &= ~INP_DIRECT_DETACH;
294 break;
297 return ip_ctloutput(msg);
301 * Check multicast packets to make sure they are only sent to sockets with
302 * multicast memberships for the packet's destination address and arrival
303 * interface. Multicast packets to multicast-unaware sockets are also
304 * disallowed.
306 * Returns 0 if the packet is acceptable, -1 if it is not.
308 static __inline int
309 check_multicast_membership(const struct ip *ip, const struct inpcb *inp,
310 const struct mbuf *m)
312 const struct ip_moptions *mopt;
313 int mshipno;
315 if (strict_mcast_mship == 0 ||
316 !IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
317 return (0);
320 ASSERT_IN_NETISR(0);
322 mopt = inp->inp_moptions;
323 if (mopt == NULL)
324 return (-1);
325 for (mshipno = 0; mshipno < mopt->imo_num_memberships; ++mshipno) {
326 const struct in_multi *maddr = mopt->imo_membership[mshipno];
328 if (ip->ip_dst.s_addr == maddr->inm_addr.s_addr &&
329 m->m_pkthdr.rcvif == maddr->inm_ifp) {
330 return (0);
333 return (-1);
336 struct udp_mcast_arg {
337 struct inpcb *inp;
338 struct inpcb *last;
339 struct ip *ip;
340 struct mbuf *m;
341 int iphlen;
342 struct sockaddr_in *udp_in;
345 static int
346 udp_mcast_input(struct udp_mcast_arg *arg)
348 struct inpcb *inp = arg->inp;
349 struct inpcb *last = arg->last;
350 struct ip *ip = arg->ip;
351 struct mbuf *m = arg->m;
353 if (check_multicast_membership(ip, inp, m) < 0)
354 return ERESTART; /* caller continue */
356 if (last != NULL) {
357 struct mbuf *n;
359 #ifdef IPSEC
360 /* check AH/ESP integrity. */
361 if (ipsec4_in_reject_so(m, last->inp_socket))
362 ipsecstat.in_polvio++;
363 /* do not inject data to pcb */
364 else
365 #endif /*IPSEC*/
366 #ifdef FAST_IPSEC
367 /* check AH/ESP integrity. */
368 if (ipsec4_in_reject(m, last))
370 else
371 #endif /*FAST_IPSEC*/
372 if ((n = m_copypacket(m, M_NOWAIT)) != NULL)
373 udp_append(last, ip, n,
374 arg->iphlen + sizeof(struct udphdr),
375 arg->udp_in);
377 arg->last = last = inp;
380 * Don't look for additional matches if this one does
381 * not have either the SO_REUSEPORT or SO_REUSEADDR
382 * socket options set. This heuristic avoids searching
383 * through all pcbs in the common case of a non-shared
384 * port. It * assumes that an application will never
385 * clear these options after setting them.
387 if (!(last->inp_socket->so_options &
388 (SO_REUSEPORT | SO_REUSEADDR)))
389 return EJUSTRETURN; /* caller stop */
390 return 0;
394 udp_input(struct mbuf **mp, int *offp, int proto)
396 struct sockaddr_in udp_in = { sizeof udp_in, AF_INET };
397 int iphlen;
398 struct ip *ip;
399 struct udphdr *uh;
400 struct inpcb *inp;
401 struct mbuf *m;
402 struct mbuf *opts = NULL;
403 int len, off;
404 struct ip save_ip;
405 struct inpcbinfo *pcbinfo = &udbinfo[mycpuid];
407 off = *offp;
408 m = *mp;
409 *mp = NULL;
411 iphlen = off;
412 udp_stat.udps_ipackets++;
415 * Strip IP options, if any; should skip this,
416 * make available to user, and use on returned packets,
417 * but we don't yet have a way to check the checksum
418 * with options still present.
420 if (iphlen > sizeof(struct ip)) {
421 ip_stripoptions(m);
422 iphlen = sizeof(struct ip);
426 * IP and UDP headers are together in first mbuf.
427 * Already checked and pulled up in ip_demux().
429 KASSERT(m->m_len >= iphlen + sizeof(struct udphdr),
430 ("UDP header not in one mbuf"));
432 ip = mtod(m, struct ip *);
433 uh = (struct udphdr *)((caddr_t)ip + iphlen);
435 /* destination port of 0 is illegal, based on RFC768. */
436 if (uh->uh_dport == 0)
437 goto bad;
440 * Make mbuf data length reflect UDP length.
441 * If not enough data to reflect UDP length, drop.
443 len = ntohs((u_short)uh->uh_ulen);
444 if (ip->ip_len != len) {
445 if (len > ip->ip_len || len < sizeof(struct udphdr)) {
446 udp_stat.udps_badlen++;
447 goto bad;
449 m_adj(m, len - ip->ip_len);
450 /* ip->ip_len = len; */
453 * Save a copy of the IP header in case we want restore it
454 * for sending an ICMP error message in response.
456 save_ip = *ip;
459 * Checksum extended UDP header and data.
461 if (uh->uh_sum) {
462 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
463 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
464 uh->uh_sum = m->m_pkthdr.csum_data;
465 else
466 uh->uh_sum = in_pseudo(ip->ip_src.s_addr,
467 ip->ip_dst.s_addr, htonl((u_short)len +
468 m->m_pkthdr.csum_data + IPPROTO_UDP));
469 uh->uh_sum ^= 0xffff;
470 } else {
471 char b[9];
473 bcopy(((struct ipovly *)ip)->ih_x1, b, 9);
474 bzero(((struct ipovly *)ip)->ih_x1, 9);
475 ((struct ipovly *)ip)->ih_len = uh->uh_ulen;
476 uh->uh_sum = in_cksum(m, len + sizeof(struct ip));
477 bcopy(b, ((struct ipovly *)ip)->ih_x1, 9);
479 if (uh->uh_sum) {
480 udp_stat.udps_badsum++;
481 m_freem(m);
482 return(IPPROTO_DONE);
484 } else
485 udp_stat.udps_nosum++;
487 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
488 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
489 struct inpcbhead *connhead;
490 struct inpcontainer *ic, *ic_marker;
491 struct inpcontainerhead *ichead;
492 struct udp_mcast_arg arg;
493 struct inpcb *last;
494 int error;
497 * Deliver a multicast or broadcast datagram to *all* sockets
498 * for which the local and remote addresses and ports match
499 * those of the incoming datagram. This allows more than
500 * one process to receive multi/broadcasts on the same port.
501 * (This really ought to be done for unicast datagrams as
502 * well, but that would cause problems with existing
503 * applications that open both address-specific sockets and
504 * a wildcard socket listening to the same port -- they would
505 * end up receiving duplicates of every unicast datagram.
506 * Those applications open the multiple sockets to overcome an
507 * inadequacy of the UDP socket interface, but for backwards
508 * compatibility we avoid the problem here rather than
509 * fixing the interface. Maybe 4.5BSD will remedy this?)
513 * Construct sockaddr format source address.
515 udp_in.sin_port = uh->uh_sport;
516 udp_in.sin_addr = ip->ip_src;
517 arg.udp_in = &udp_in;
519 * Locate pcb(s) for datagram.
520 * (Algorithm copied from raw_intr().)
522 last = NULL;
523 arg.iphlen = iphlen;
525 connhead = &pcbinfo->hashbase[
526 INP_PCBCONNHASH(ip->ip_src.s_addr, uh->uh_sport,
527 ip->ip_dst.s_addr, uh->uh_dport, pcbinfo->hashmask)];
528 LIST_FOREACH(inp, connhead, inp_hash) {
529 #ifdef INET6
530 if (!INP_ISIPV4(inp))
531 continue;
532 #endif
533 if (!in_hosteq(inp->inp_faddr, ip->ip_src) ||
534 !in_hosteq(inp->inp_laddr, ip->ip_dst) ||
535 inp->inp_fport != uh->uh_sport ||
536 inp->inp_lport != uh->uh_dport)
537 continue;
539 arg.inp = inp;
540 arg.last = last;
541 arg.ip = ip;
542 arg.m = m;
544 error = udp_mcast_input(&arg);
545 if (error == ERESTART)
546 continue;
547 last = arg.last;
549 if (error == EJUSTRETURN)
550 goto done;
553 ichead = &pcbinfo->wildcardhashbase[
554 INP_PCBWILDCARDHASH(uh->uh_dport,
555 pcbinfo->wildcardhashmask)];
556 ic_marker = in_pcbcontainer_marker(mycpuid);
558 GET_PCBINFO_TOKEN(pcbinfo);
559 LIST_INSERT_HEAD(ichead, ic_marker, ic_list);
560 while ((ic = LIST_NEXT(ic_marker, ic_list)) != NULL) {
561 LIST_REMOVE(ic_marker, ic_list);
562 LIST_INSERT_AFTER(ic, ic_marker, ic_list);
564 inp = ic->ic_inp;
565 if (inp->inp_flags & INP_PLACEMARKER)
566 continue;
567 #ifdef INET6
568 if (!INP_ISIPV4(inp))
569 continue;
570 #endif
571 if (inp->inp_lport != uh->uh_dport)
572 continue;
573 if (inp->inp_laddr.s_addr != INADDR_ANY &&
574 inp->inp_laddr.s_addr != ip->ip_dst.s_addr)
575 continue;
577 arg.inp = inp;
578 arg.last = last;
579 arg.ip = ip;
580 arg.m = m;
582 error = udp_mcast_input(&arg);
583 if (error == ERESTART)
584 continue;
585 last = arg.last;
587 if (error == EJUSTRETURN)
588 break;
590 LIST_REMOVE(ic_marker, ic_list);
591 REL_PCBINFO_TOKEN(pcbinfo);
592 done:
593 if (last == NULL) {
595 * No matching pcb found; discard datagram.
596 * (No need to send an ICMP Port Unreachable
597 * for a broadcast or multicast datgram.)
599 udp_stat.udps_noportbcast++;
600 goto bad;
602 #ifdef IPSEC
603 /* check AH/ESP integrity. */
604 if (ipsec4_in_reject_so(m, last->inp_socket)) {
605 ipsecstat.in_polvio++;
606 goto bad;
608 #endif /*IPSEC*/
609 #ifdef FAST_IPSEC
610 /* check AH/ESP integrity. */
611 if (ipsec4_in_reject(m, last))
612 goto bad;
613 #endif /*FAST_IPSEC*/
614 udp_append(last, ip, m, iphlen + sizeof(struct udphdr),
615 &udp_in);
616 return(IPPROTO_DONE);
619 * Locate pcb for datagram.
621 inp = in_pcblookup_pkthash(pcbinfo, ip->ip_src, uh->uh_sport,
622 ip->ip_dst, uh->uh_dport, TRUE, m->m_pkthdr.rcvif,
623 udp_reuseport_ext ? m : NULL);
624 if (inp == NULL) {
625 if (log_in_vain) {
626 char buf[sizeof "aaa.bbb.ccc.ddd"];
628 strcpy(buf, inet_ntoa(ip->ip_dst));
629 log(LOG_INFO,
630 "Connection attempt to UDP %s:%d from %s:%d\n",
631 buf, ntohs(uh->uh_dport), inet_ntoa(ip->ip_src),
632 ntohs(uh->uh_sport));
634 udp_stat.udps_noport++;
635 if (m->m_flags & (M_BCAST | M_MCAST)) {
636 udp_stat.udps_noportbcast++;
637 goto bad;
639 if (blackhole)
640 goto bad;
641 #ifdef ICMP_BANDLIM
642 if (badport_bandlim(BANDLIM_ICMP_UNREACH) < 0)
643 goto bad;
644 #endif
645 *ip = save_ip;
646 ip->ip_len += iphlen;
647 icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_PORT, 0, 0);
648 return(IPPROTO_DONE);
650 KASSERT(INP_ISIPV4(inp), ("not inet inpcb"));
651 #ifdef IPSEC
652 if (ipsec4_in_reject_so(m, inp->inp_socket)) {
653 ipsecstat.in_polvio++;
654 goto bad;
656 #endif /*IPSEC*/
657 #ifdef FAST_IPSEC
658 if (ipsec4_in_reject(m, inp))
659 goto bad;
660 #endif /*FAST_IPSEC*/
662 * Check the minimum TTL for socket.
664 if (ip->ip_ttl < inp->inp_ip_minttl)
665 goto bad;
668 * Construct sockaddr format source address.
669 * Stuff source address and datagram in user buffer.
671 udp_in.sin_port = uh->uh_sport;
672 udp_in.sin_addr = ip->ip_src;
673 if ((inp->inp_flags & INP_CONTROLOPTS) ||
674 (inp->inp_socket->so_options & SO_TIMESTAMP))
675 ip_savecontrol(inp, &opts, ip, m);
676 m_adj(m, iphlen + sizeof(struct udphdr));
678 lwkt_gettoken(&inp->inp_socket->so_rcv.ssb_token);
679 if (ssb_appendaddr(&inp->inp_socket->so_rcv,
680 (struct sockaddr *)&udp_in, m, opts) == 0) {
681 lwkt_reltoken(&inp->inp_socket->so_rcv.ssb_token);
682 udp_stat.udps_fullsock++;
683 goto bad;
685 lwkt_reltoken(&inp->inp_socket->so_rcv.ssb_token);
686 sorwakeup(inp->inp_socket);
687 return(IPPROTO_DONE);
688 bad:
689 m_freem(m);
690 if (opts)
691 m_freem(opts);
692 return(IPPROTO_DONE);
696 * subroutine of udp_input(), mainly for source code readability.
697 * caller must properly init udp_ip6 and udp_in6 beforehand.
699 static void
700 udp_append(struct inpcb *last, struct ip *ip, struct mbuf *n, int off,
701 struct sockaddr_in *udp_in)
703 struct mbuf *opts = NULL;
704 int ret;
706 KASSERT(INP_ISIPV4(last), ("not inet inpcb"));
708 if (last->inp_flags & INP_CONTROLOPTS ||
709 last->inp_socket->so_options & SO_TIMESTAMP)
710 ip_savecontrol(last, &opts, ip, n);
711 m_adj(n, off);
713 lwkt_gettoken(&last->inp_socket->so_rcv.ssb_token);
714 ret = ssb_appendaddr(&last->inp_socket->so_rcv,
715 (struct sockaddr *)udp_in, n, opts);
716 lwkt_reltoken(&last->inp_socket->so_rcv.ssb_token);
717 if (ret == 0) {
718 m_freem(n);
719 if (opts)
720 m_freem(opts);
721 udp_stat.udps_fullsock++;
722 } else {
723 sorwakeup(last->inp_socket);
728 * Notify a udp user of an asynchronous error;
729 * just wake up so that he can collect error status.
731 void
732 udp_notify(struct inpcb *inp, int error)
734 inp->inp_socket->so_error = error;
735 sorwakeup(inp->inp_socket);
736 sowwakeup(inp->inp_socket);
739 struct netmsg_udp_notify {
740 struct netmsg_base base;
741 inp_notify_t nm_notify;
742 struct in_addr nm_faddr;
743 int nm_arg;
746 static void
747 udp_notifyall_oncpu(netmsg_t msg)
749 struct netmsg_udp_notify *nm = (struct netmsg_udp_notify *)msg;
750 int nextcpu, cpu = mycpuid;
752 in_pcbnotifyall(&udbinfo[cpu], nm->nm_faddr, nm->nm_arg, nm->nm_notify);
754 nextcpu = cpu + 1;
755 if (nextcpu < ncpus2)
756 lwkt_forwardmsg(netisr_cpuport(nextcpu), &nm->base.lmsg);
757 else
758 lwkt_replymsg(&nm->base.lmsg, 0);
761 inp_notify_t
762 udp_get_inpnotify(int cmd, const struct sockaddr *sa,
763 struct ip **ip0, int *cpuid)
765 struct in_addr faddr;
766 struct ip *ip = *ip0;
767 inp_notify_t notify = udp_notify;
769 faddr = ((const struct sockaddr_in *)sa)->sin_addr;
770 if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
771 return NULL;
773 if (PRC_IS_REDIRECT(cmd)) {
774 ip = NULL;
775 notify = in_rtchange;
776 } else if (cmd == PRC_HOSTDEAD) {
777 ip = NULL;
778 } else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0) {
779 return NULL;
782 if (cpuid != NULL) {
783 if (ip == NULL) {
784 /* Go through all CPUs */
785 *cpuid = ncpus;
786 } else {
787 const struct udphdr *uh;
789 uh = (const struct udphdr *)
790 ((caddr_t)ip + (ip->ip_hl << 2));
791 *cpuid = udp_addrcpu(faddr.s_addr, uh->uh_dport,
792 ip->ip_src.s_addr, uh->uh_sport);
796 *ip0 = ip;
797 return notify;
800 void
801 udp_ctlinput(netmsg_t msg)
803 struct sockaddr *sa = msg->ctlinput.nm_arg;
804 struct ip *ip = msg->ctlinput.nm_extra;
805 int cmd = msg->ctlinput.nm_cmd, cpuid;
806 inp_notify_t notify;
807 struct in_addr faddr;
809 notify = udp_get_inpnotify(cmd, sa, &ip, &cpuid);
810 if (notify == NULL)
811 goto done;
813 faddr = ((struct sockaddr_in *)sa)->sin_addr;
814 if (ip) {
815 const struct udphdr *uh;
816 struct inpcb *inp;
818 if (cpuid != mycpuid)
819 goto done;
821 uh = (const struct udphdr *)((caddr_t)ip + (ip->ip_hl << 2));
822 inp = in_pcblookup_hash(&udbinfo[mycpuid], faddr, uh->uh_dport,
823 ip->ip_src, uh->uh_sport, 0, NULL);
824 if (inp != NULL && inp->inp_socket != NULL)
825 notify(inp, inetctlerrmap[cmd]);
826 } else if (msg->ctlinput.nm_direct) {
827 if (cpuid != ncpus && cpuid != mycpuid)
828 goto done;
829 if (mycpuid >= ncpus2)
830 goto done;
832 in_pcbnotifyall(&udbinfo[mycpuid], faddr, inetctlerrmap[cmd],
833 notify);
834 } else {
835 struct netmsg_udp_notify *nm;
837 ASSERT_IN_NETISR(0);
838 nm = kmalloc(sizeof(*nm), M_LWKTMSG, M_INTWAIT);
839 netmsg_init(&nm->base, NULL, &netisr_afree_rport,
840 0, udp_notifyall_oncpu);
841 nm->nm_faddr = faddr;
842 nm->nm_arg = inetctlerrmap[cmd];
843 nm->nm_notify = notify;
844 lwkt_sendmsg(netisr_cpuport(0), &nm->base.lmsg);
846 done:
847 lwkt_replymsg(&msg->lmsg, 0);
850 SYSCTL_PROC(_net_inet_udp, UDPCTL_PCBLIST, pcblist, CTLFLAG_RD, udbinfo, 0,
851 in_pcblist_global_ncpus2, "S,xinpcb", "List of active UDP sockets");
853 static int
854 udp_getcred(SYSCTL_HANDLER_ARGS)
856 struct sockaddr_in addrs[2];
857 struct ucred cred0, *cred = NULL;
858 struct inpcb *inp;
859 int error, cpu, origcpu;
861 error = priv_check(req->td, PRIV_ROOT);
862 if (error)
863 return (error);
864 error = SYSCTL_IN(req, addrs, sizeof addrs);
865 if (error)
866 return (error);
868 origcpu = mycpuid;
869 cpu = udp_addrcpu(addrs[1].sin_addr.s_addr, addrs[1].sin_port,
870 addrs[0].sin_addr.s_addr, addrs[0].sin_port);
872 lwkt_migratecpu(cpu);
874 inp = in_pcblookup_hash(&udbinfo[cpu],
875 addrs[1].sin_addr, addrs[1].sin_port,
876 addrs[0].sin_addr, addrs[0].sin_port, TRUE, NULL);
877 if (inp == NULL || inp->inp_socket == NULL) {
878 error = ENOENT;
879 } else if (inp->inp_socket->so_cred != NULL) {
880 cred0 = *(inp->inp_socket->so_cred);
881 cred = &cred0;
884 lwkt_migratecpu(origcpu);
886 if (error)
887 return error;
889 return SYSCTL_OUT(req, cred, sizeof(struct ucred));
891 SYSCTL_PROC(_net_inet_udp, OID_AUTO, getcred, CTLTYPE_OPAQUE|CTLFLAG_RW,
892 0, 0, udp_getcred, "S,ucred", "Get the ucred of a UDP connection");
894 static void
895 udp_send_redispatch(netmsg_t msg)
897 struct mbuf *m = msg->send.nm_m;
898 int pru_flags = msg->send.nm_flags;
899 struct inpcb *inp = msg->send.base.nm_so->so_pcb;
900 struct mbuf *m_opt = msg->send.nm_control; /* XXX save ipopt */
901 int flags = msg->send.nm_priv; /* ip_output flags */
902 int error;
904 logudp(redisp_ipout_beg, inp);
907 * - Don't use inp route cache. It should only be used in the
908 * inp owner netisr.
909 * - Access to inp_moptions should be safe, since multicast UDP
910 * datagrams are redispatched to netisr0 and inp_moptions is
911 * changed only in netisr0.
913 error = ip_output(m, m_opt, NULL, flags, inp->inp_moptions, inp);
914 if ((pru_flags & PRUS_NOREPLY) == 0)
915 lwkt_replymsg(&msg->send.base.lmsg, error);
917 if (m_opt != NULL) {
918 /* Free saved ip options, if any */
919 m_freem(m_opt);
922 logudp(redisp_ipout_end, inp);
925 static void
926 udp_send(netmsg_t msg)
928 struct socket *so = msg->send.base.nm_so;
929 struct mbuf *m = msg->send.nm_m;
930 struct sockaddr *dstaddr = msg->send.nm_addr;
931 int pru_flags = msg->send.nm_flags;
932 struct inpcb *inp = so->so_pcb;
933 struct thread *td = msg->send.nm_td;
934 int flags;
936 struct udpiphdr *ui;
937 int len = m->m_pkthdr.len;
938 struct sockaddr_in *sin; /* really is initialized before use */
939 int error = 0, cpu;
941 KKASSERT(msg->send.nm_control == NULL);
943 logudp(send_beg, inp);
945 if (inp == NULL) {
946 error = EINVAL;
947 goto release;
950 if (len + sizeof(struct udpiphdr) > IP_MAXPACKET) {
951 error = EMSGSIZE;
952 goto release;
955 if (inp->inp_lport == 0) { /* unbound socket */
956 boolean_t forwarded;
958 error = in_pcbbind(inp, NULL, td);
959 if (error)
960 goto release;
963 * Need to call udp_send again, after this inpcb is
964 * inserted into wildcard hash table.
966 msg->send.base.lmsg.ms_flags |= MSGF_UDP_SEND;
967 forwarded = udp_inswildcardhash(inp, &msg->send.base, 0);
968 if (forwarded) {
970 * The message is further forwarded, so we are
971 * done here.
973 logudp(send_inswildcard, inp);
974 return;
978 if (dstaddr != NULL) { /* destination address specified */
979 if (inp->inp_faddr.s_addr != INADDR_ANY) {
980 /* already connected */
981 error = EISCONN;
982 goto release;
984 sin = (struct sockaddr_in *)dstaddr;
985 if (!prison_remote_ip(td, (struct sockaddr *)&sin)) {
986 error = EAFNOSUPPORT; /* IPv6 only jail */
987 goto release;
989 } else {
990 if (inp->inp_faddr.s_addr == INADDR_ANY) {
991 /* no destination specified and not already connected */
992 error = ENOTCONN;
993 goto release;
995 sin = NULL;
999 * Calculate data length and get a mbuf
1000 * for UDP and IP headers.
1002 M_PREPEND(m, sizeof(struct udpiphdr), M_NOWAIT);
1003 if (m == NULL) {
1004 error = ENOBUFS;
1005 goto release;
1009 * Fill in mbuf with extended UDP header
1010 * and addresses and length put into network format.
1012 ui = mtod(m, struct udpiphdr *);
1013 bzero(ui->ui_x1, sizeof ui->ui_x1); /* XXX still needed? */
1014 ui->ui_pr = IPPROTO_UDP;
1017 * Set destination address.
1019 if (dstaddr != NULL) { /* use specified destination */
1020 ui->ui_dst = sin->sin_addr;
1021 ui->ui_dport = sin->sin_port;
1022 } else { /* use connected destination */
1023 ui->ui_dst = inp->inp_faddr;
1024 ui->ui_dport = inp->inp_fport;
1028 * Set source address.
1030 if (inp->inp_laddr.s_addr == INADDR_ANY ||
1031 IN_MULTICAST(ntohl(inp->inp_laddr.s_addr))) {
1032 struct sockaddr_in *if_sin;
1034 if (dstaddr == NULL) {
1036 * connect() had (or should have) failed because
1037 * the interface had no IP address, but the
1038 * application proceeded to call send() anyways.
1040 error = ENOTCONN;
1041 goto release;
1044 /* Look up outgoing interface. */
1045 error = in_pcbladdr_find(inp, dstaddr, &if_sin, td, 1);
1046 if (error)
1047 goto release;
1048 ui->ui_src = if_sin->sin_addr; /* use address of interface */
1049 } else {
1050 ui->ui_src = inp->inp_laddr; /* use non-null bound address */
1052 ui->ui_sport = inp->inp_lport;
1053 KASSERT(inp->inp_lport != 0, ("inp lport should have been bound"));
1056 * Release the original thread, since it is no longer used
1058 if (pru_flags & PRUS_HELDTD) {
1059 lwkt_rele(td);
1060 pru_flags &= ~PRUS_HELDTD;
1063 * Free the dest address, since it is no longer needed
1065 if (pru_flags & PRUS_FREEADDR) {
1066 kfree(dstaddr, M_SONAME);
1067 pru_flags &= ~PRUS_FREEADDR;
1070 ui->ui_ulen = htons((u_short)len + sizeof(struct udphdr));
1073 * Set up checksum and output datagram.
1075 if (udpcksum) {
1076 ui->ui_sum = in_pseudo(ui->ui_src.s_addr, ui->ui_dst.s_addr,
1077 htons((u_short)len + sizeof(struct udphdr) + IPPROTO_UDP));
1078 m->m_pkthdr.csum_flags = CSUM_UDP;
1079 m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
1080 m->m_pkthdr.csum_thlen = sizeof(struct udphdr);
1081 } else {
1082 ui->ui_sum = 0;
1084 ((struct ip *)ui)->ip_len = sizeof(struct udpiphdr) + len;
1085 ((struct ip *)ui)->ip_ttl = inp->inp_ip_ttl; /* XXX */
1086 ((struct ip *)ui)->ip_tos = inp->inp_ip_tos; /* XXX */
1087 udp_stat.udps_opackets++;
1089 flags = IP_DEBUGROUTE |
1090 (inp->inp_socket->so_options & (SO_DONTROUTE | SO_BROADCAST));
1091 if (pru_flags & PRUS_DONTROUTE)
1092 flags |= SO_DONTROUTE;
1094 if (inp->inp_flags & INP_CONNECTED) {
1096 * For connected socket, this datagram has already
1097 * been in the correct netisr; no need to rehash.
1099 goto sendit;
1102 cpu = udp_addrcpu(ui->ui_dst.s_addr, ui->ui_dport,
1103 ui->ui_src.s_addr, ui->ui_sport);
1104 if (cpu != mycpuid) {
1105 struct mbuf *m_opt = NULL;
1106 struct netmsg_pru_send *smsg;
1107 struct lwkt_port *port = netisr_cpuport(cpu);
1110 * Not on the CPU that matches this UDP datagram hash;
1111 * redispatch to the correct CPU to do the ip_output().
1113 if (inp->inp_options != NULL) {
1115 * If there are ip options, then save a copy,
1116 * since accessing inp_options on other CPUs'
1117 * is not safe.
1119 * XXX optimize this?
1121 m_opt = m_copym(inp->inp_options, 0, M_COPYALL,
1122 M_WAITOK);
1124 if ((pru_flags & PRUS_NOREPLY) == 0) {
1126 * Change some parts of the original netmsg and
1127 * forward it to the target netisr.
1129 * NOTE: so_port MUST NOT be checked in the target
1130 * netisr.
1132 smsg = &msg->send;
1133 smsg->nm_priv = flags; /* ip_output flags */
1134 smsg->nm_m = m;
1135 smsg->nm_control = m_opt; /* XXX save ipopt */
1136 smsg->base.lmsg.ms_flags |= MSGF_IGNSOPORT;
1137 smsg->base.nm_dispatch = udp_send_redispatch;
1138 lwkt_forwardmsg(port, &smsg->base.lmsg);
1139 } else {
1141 * Recreate the netmsg, since the original mbuf
1142 * could have been changed. And send it to the
1143 * target netisr.
1145 * NOTE: so_port MUST NOT be checked in the target
1146 * netisr.
1148 smsg = &m->m_hdr.mh_sndmsg;
1149 netmsg_init(&smsg->base, so, &netisr_apanic_rport,
1150 MSGF_IGNSOPORT, udp_send_redispatch);
1151 smsg->nm_priv = flags; /* ip_output flags */
1152 smsg->nm_flags = pru_flags;
1153 smsg->nm_m = m;
1154 smsg->nm_control = m_opt; /* XXX save ipopt */
1155 lwkt_sendmsg(port, &smsg->base.lmsg);
1158 /* This UDP datagram is redispatched; done */
1159 logudp(send_redisp, inp);
1160 return;
1163 sendit:
1164 logudp(send_ipout, inp);
1165 error = ip_output(m, inp->inp_options, &inp->inp_route, flags,
1166 inp->inp_moptions, inp);
1167 m = NULL;
1169 release:
1170 if (m != NULL)
1171 m_freem(m);
1173 if (pru_flags & PRUS_HELDTD)
1174 lwkt_rele(td);
1175 if (pru_flags & PRUS_FREEADDR)
1176 kfree(dstaddr, M_SONAME);
1177 if ((pru_flags & PRUS_NOREPLY) == 0)
1178 lwkt_replymsg(&msg->send.base.lmsg, error);
1180 logudp(send_end, inp);
1183 u_long udp_sendspace = 9216; /* really max datagram size */
1184 /* 40 1K datagrams */
1185 SYSCTL_INT(_net_inet_udp, UDPCTL_MAXDGRAM, maxdgram, CTLFLAG_RW,
1186 &udp_sendspace, 0, "Maximum outgoing UDP datagram size");
1188 u_long udp_recvspace = 40 * (1024 +
1189 #ifdef INET6
1190 sizeof(struct sockaddr_in6)
1191 #else
1192 sizeof(struct sockaddr_in)
1193 #endif
1195 SYSCTL_INT(_net_inet_udp, UDPCTL_RECVSPACE, recvspace, CTLFLAG_RW,
1196 &udp_recvspace, 0, "Maximum incoming UDP datagram size");
1199 * This should never happen, since UDP socket does not support
1200 * connection acception (SO_ACCEPTCONN, i.e. listen(2)).
1202 static void
1203 udp_abort(netmsg_t msg __unused)
1205 panic("udp_abort is called");
1208 static int
1209 udp_preattach(struct socket *so, int proto __unused, struct pru_attach_info *ai)
1211 return soreserve(so, udp_sendspace, udp_recvspace, ai->sb_rlimit);
1214 static void
1215 udp_attach(netmsg_t msg)
1217 struct socket *so = msg->attach.base.nm_so;
1218 struct pru_attach_info *ai = msg->attach.nm_ai;
1219 struct inpcb *inp;
1220 int error;
1222 KASSERT(so->so_pcb == NULL, ("udp socket attached"));
1224 if (ai != NULL) {
1225 error = udp_preattach(so, 0 /* don't care */, ai);
1226 if (error)
1227 goto out;
1228 } else {
1229 /* Post attach; do nothing */
1232 error = in_pcballoc(so, &udbinfo[mycpuid]);
1233 if (error)
1234 goto out;
1236 inp = so->so_pcb;
1237 inp->inp_flags |= INP_DIRECT_DETACH;
1238 inp->inp_ip_ttl = ip_defttl;
1239 error = 0;
1240 out:
1241 lwkt_replymsg(&msg->attach.base.lmsg, error);
1244 static void
1245 udp_inswildcard_replymsg(netmsg_t msg)
1247 lwkt_msg_t lmsg = &msg->lmsg;
1249 if (lmsg->ms_flags & MSGF_UDP_SEND) {
1250 udp_send(msg);
1251 /* msg is replied by udp_send() */
1252 } else {
1253 lwkt_replymsg(lmsg, lmsg->ms_error);
1257 static void
1258 udp_soreuseport_dispatch(netmsg_t msg)
1260 /* This inpcb has already been in the wildcard hash. */
1261 in_pcblink_flags(msg->base.nm_so->so_pcb, &udbinfo[mycpuid], 0);
1262 udp_inswildcard_replymsg(msg);
1265 static void
1266 udp_sosetport(struct lwkt_msg *msg, lwkt_port_t port)
1268 sosetport(((struct netmsg_base *)msg)->nm_so, port);
1271 static boolean_t
1272 udp_inswildcardhash_oncpu(struct inpcb *inp, struct netmsg_base *msg)
1274 int cpu;
1276 KASSERT(inp->inp_pcbinfo == &udbinfo[mycpuid],
1277 ("not on owner cpu"));
1279 in_pcbinswildcardhash(inp);
1280 for (cpu = 0; cpu < ncpus2; ++cpu) {
1281 if (cpu == mycpuid) {
1283 * This inpcb has been inserted by the above
1284 * in_pcbinswildcardhash().
1286 continue;
1288 in_pcbinswildcardhash_oncpu(inp, &udbinfo[cpu]);
1291 if (inp->inp_socket->so_options & SO_REUSEPORT) {
1293 * For SO_REUSEPORT socket, redistribute it based on its
1294 * local group index.
1296 cpu = inp->inp_lgrpindex & ncpus2_mask;
1297 if (cpu != mycpuid) {
1298 struct lwkt_port *port = netisr_cpuport(cpu);
1299 lwkt_msg_t lmsg = &msg->lmsg;
1302 * We are moving the protocol processing port the
1303 * socket is on, we have to unlink here and re-link
1304 * on the target cpu (this inpcb is still left in
1305 * the wildcard hash).
1307 in_pcbunlink_flags(inp, &udbinfo[mycpuid], 0);
1308 msg->nm_dispatch = udp_soreuseport_dispatch;
1311 * See the related comment in tcp_usrreq.c
1312 * tcp_connect()
1314 lwkt_setmsg_receipt(lmsg, udp_sosetport);
1315 lwkt_forwardmsg(port, lmsg);
1316 return TRUE; /* forwarded */
1319 return FALSE;
1322 static void
1323 udp_inswildcardhash_dispatch(netmsg_t msg)
1325 struct inpcb *inp = msg->base.nm_so->so_pcb;
1326 boolean_t forwarded;
1328 KASSERT(inp->inp_lport != 0, ("local port not set yet"));
1329 KASSERT(udp_lportcpu(inp->inp_lport) == mycpuid, ("not target cpu"));
1331 in_pcblink(inp, &udbinfo[mycpuid]);
1333 forwarded = udp_inswildcardhash_oncpu(inp, &msg->base);
1334 if (forwarded) {
1335 /* The message is further forwarded, so we are done here. */
1336 return;
1338 udp_inswildcard_replymsg(msg);
1341 static boolean_t
1342 udp_inswildcardhash(struct inpcb *inp, struct netmsg_base *msg, int error)
1344 lwkt_msg_t lmsg = &msg->lmsg;
1345 int cpu;
1347 ASSERT_INP_NOTINHASH(inp);
1349 /* This inpcb could no longer be directly detached */
1350 inp->inp_flags &= ~INP_DIRECT_DETACH;
1353 * Always clear the route cache, so we don't need to
1354 * worry about any owner CPU changes later.
1356 in_pcbresetroute(inp);
1358 KASSERT(inp->inp_lport != 0, ("local port not set yet"));
1359 cpu = udp_lportcpu(inp->inp_lport);
1361 lmsg->ms_error = error;
1362 if (cpu != mycpuid) {
1363 struct lwkt_port *port = netisr_cpuport(cpu);
1366 * We are moving the protocol processing port the socket
1367 * is on, we have to unlink here and re-link on the
1368 * target cpu.
1370 in_pcbunlink(inp, &udbinfo[mycpuid]);
1371 msg->nm_dispatch = udp_inswildcardhash_dispatch;
1373 /* See the related comment in tcp_usrreq.c tcp_connect() */
1374 lwkt_setmsg_receipt(lmsg, udp_sosetport);
1375 lwkt_forwardmsg(port, lmsg);
1376 return TRUE; /* forwarded */
1379 return udp_inswildcardhash_oncpu(inp, msg);
1382 static void
1383 udp_bind(netmsg_t msg)
1385 struct socket *so = msg->bind.base.nm_so;
1386 struct inpcb *inp;
1387 int error;
1389 inp = so->so_pcb;
1390 if (inp) {
1391 struct sockaddr *nam = msg->bind.nm_nam;
1392 struct thread *td = msg->bind.nm_td;
1393 struct sockaddr_in *sin;
1394 lwkt_port_t port;
1395 int cpu;
1398 * Check "already bound" here (in_pcbbind() does the same
1399 * check though), so we don't forward a connected/bound
1400 * socket randomly which would panic in the following
1401 * in_pcbunlink().
1403 if (inp->inp_lport != 0 ||
1404 inp->inp_laddr.s_addr != INADDR_ANY) {
1405 error = EINVAL; /* already bound */
1406 goto done;
1409 if (nam->sa_len != sizeof(*sin)) {
1410 error = EINVAL;
1411 goto done;
1413 sin = (struct sockaddr_in *)nam;
1415 cpu = udp_lportcpu(sin->sin_port);
1416 port = netisr_cpuport(cpu);
1419 * See the related comment in tcp_usrreq.c tcp_usr_bind().
1420 * The exception is that we use local port based netisr
1421 * to serialize in_pcbbind().
1423 if (&curthread->td_msgport != port) {
1424 lwkt_msg_t lmsg = &msg->bind.base.lmsg;
1426 KASSERT((msg->bind.nm_flags & PRUB_RELINK) == 0,
1427 ("already asked to relink"));
1429 in_pcbunlink(so->so_pcb, &udbinfo[mycpuid]);
1430 msg->bind.nm_flags |= PRUB_RELINK;
1433 * See the related comment in tcp_usrreq.c
1434 * tcp_connect().
1436 lwkt_setmsg_receipt(lmsg, udp_sosetport);
1437 lwkt_forwardmsg(port, lmsg);
1438 /* msg invalid now */
1439 return;
1441 KASSERT(so->so_port == port, ("so_port is not netisr%d", cpu));
1443 if (msg->bind.nm_flags & PRUB_RELINK) {
1444 msg->bind.nm_flags &= ~PRUB_RELINK;
1445 in_pcblink(so->so_pcb, &udbinfo[mycpuid]);
1447 KASSERT(inp->inp_pcbinfo == &udbinfo[cpu],
1448 ("pcbinfo is not udbinfo%d", cpu));
1450 error = in_pcbbind(inp, nam, td);
1451 if (error == 0) {
1452 boolean_t forwarded;
1454 if (sin->sin_addr.s_addr != INADDR_ANY)
1455 inp->inp_flags |= INP_WASBOUND_NOTANY;
1457 forwarded = udp_inswildcardhash(inp,
1458 &msg->bind.base, 0);
1459 if (forwarded) {
1461 * The message is further forwarded, so
1462 * we are done here.
1464 return;
1467 } else {
1468 error = EINVAL;
1470 done:
1471 lwkt_replymsg(&msg->bind.base.lmsg, error);
1474 static int
1475 udp_preconnect(struct socket *so, const struct sockaddr *nam __unused,
1476 struct thread *td __unused)
1478 sosetstate(so, SS_ISCONNECTED); /* XXX */
1479 return 0;
1482 static void
1483 udp_connect(netmsg_t msg)
1485 struct socket *so = msg->connect.base.nm_so;
1486 struct sockaddr *nam = msg->connect.nm_nam;
1487 struct thread *td = msg->connect.nm_td;
1488 struct inpcb *inp;
1489 struct sockaddr_in *sin = (struct sockaddr_in *)nam;
1490 struct sockaddr_in *if_sin;
1491 struct lwkt_port *port;
1492 int error;
1494 KKASSERT(msg->connect.nm_m == NULL);
1496 inp = so->so_pcb;
1497 if (inp == NULL) {
1498 error = EINVAL;
1499 goto out;
1502 if (msg->connect.nm_flags & PRUC_RECONNECT) {
1503 msg->connect.nm_flags &= ~PRUC_RECONNECT;
1504 in_pcblink(inp, &udbinfo[mycpuid]);
1507 if (inp->inp_faddr.s_addr != INADDR_ANY) {
1508 error = EISCONN;
1509 goto out;
1511 error = 0;
1514 * Bind if we have to
1516 if (inp->inp_lport == 0) {
1517 error = in_pcbbind(inp, NULL, td);
1518 if (error)
1519 goto out;
1523 * Calculate the correct protocol processing thread. The connect
1524 * operation must run there.
1526 error = in_pcbladdr(inp, nam, &if_sin, td);
1527 if (error)
1528 goto out;
1529 if (!prison_remote_ip(td, nam)) {
1530 error = EAFNOSUPPORT; /* IPv6 only jail */
1531 goto out;
1534 port = udp_addrport(sin->sin_addr.s_addr, sin->sin_port,
1535 inp->inp_laddr.s_addr != INADDR_ANY ?
1536 inp->inp_laddr.s_addr : if_sin->sin_addr.s_addr, inp->inp_lport);
1537 if (port != &curthread->td_msgport) {
1538 lwkt_msg_t lmsg = &msg->connect.base.lmsg;
1539 int nm_flags = PRUC_RECONNECT;
1542 * in_pcbladdr() may have allocated a route entry for us
1543 * on the current CPU, but we need a route entry on the
1544 * inpcb's owner CPU, so free it here.
1546 in_pcbresetroute(inp);
1548 if (inp->inp_flags & INP_WILDCARD) {
1550 * Remove this inpcb from the wildcard hash before
1551 * the socket's msgport changes.
1553 udp_remwildcardhash(inp);
1556 if (so->so_orig_port == NULL) {
1558 * First time change protocol processing port.
1559 * Save the current port for synchronization upon
1560 * udp_detach.
1562 so->so_orig_port = &curthread->td_msgport;
1563 } else {
1565 * We have changed protocol processing port more
1566 * than once. We could not do direct detach
1567 * anymore, because we lose the track of the
1568 * original protocol processing ports to perform
1569 * synchronization upon udp_detach. This should
1570 * be rare though.
1572 inp->inp_flags &= ~INP_DIRECT_DETACH;
1576 * We are moving the protocol processing port the socket
1577 * is on, we have to unlink here and re-link on the
1578 * target cpu.
1580 in_pcbunlink(inp, &udbinfo[mycpuid]);
1581 msg->connect.nm_flags |= nm_flags;
1583 /* See the related comment in tcp_usrreq.c tcp_connect() */
1584 lwkt_setmsg_receipt(lmsg, udp_sosetport);
1585 lwkt_forwardmsg(port, lmsg);
1586 /* msg invalid now */
1587 return;
1589 error = udp_connect_oncpu(inp, sin, if_sin);
1590 out:
1591 if (msg->connect.nm_flags & PRUC_HELDTD)
1592 lwkt_rele(td);
1593 if (error && (msg->connect.nm_flags & PRUC_ASYNC)) {
1594 if (inp->inp_lport == 0) {
1596 * As long as we have the local port, it is fine
1597 * for connect to fail, e.g. disconnect.
1599 so->so_error = error;
1601 soclrstate(so, SS_ISCONNECTED);
1603 * Wake up callers blocked on this socket to make sure
1604 * that they can see this error.
1606 * NOTE:
1607 * sodisconnected() can't be used here, which bricks
1608 * sending and receiving.
1610 wakeup(&so->so_timeo);
1611 sowwakeup(so);
1612 sorwakeup(so);
1614 if (error && inp != NULL && inp->inp_lport != 0 &&
1615 (inp->inp_flags & INP_WILDCARD) == 0) {
1616 boolean_t forwarded;
1618 /* Connect failed; put it to wildcard hash. */
1619 forwarded = udp_inswildcardhash(inp, &msg->connect.base,
1620 error);
1621 if (forwarded) {
1623 * The message is further forwarded, so we are done
1624 * here.
1626 return;
1629 lwkt_replymsg(&msg->connect.base.lmsg, error);
1632 static void
1633 udp_remwildcardhash(struct inpcb *inp)
1635 int cpu;
1637 KASSERT(inp->inp_pcbinfo == &udbinfo[mycpuid],
1638 ("not on owner cpu"));
1640 for (cpu = 0; cpu < ncpus2; ++cpu) {
1641 if (cpu == mycpuid) {
1643 * This inpcb will be removed by the later
1644 * in_pcbremwildcardhash().
1646 continue;
1648 in_pcbremwildcardhash_oncpu(inp, &udbinfo[cpu]);
1650 in_pcbremwildcardhash(inp);
1653 static int
1654 udp_connect_oncpu(struct inpcb *inp, struct sockaddr_in *sin,
1655 struct sockaddr_in *if_sin)
1657 struct socket *so = inp->inp_socket;
1658 struct inpcb *oinp;
1660 oinp = in_pcblookup_hash(inp->inp_pcbinfo,
1661 sin->sin_addr, sin->sin_port,
1662 inp->inp_laddr.s_addr != INADDR_ANY ?
1663 inp->inp_laddr : if_sin->sin_addr, inp->inp_lport, FALSE, NULL);
1664 if (oinp != NULL)
1665 return EADDRINUSE;
1668 * No more errors can occur, finish adjusting the socket
1669 * and change the processing port to reflect the connected
1670 * socket. Once set we can no longer safely mess with the
1671 * socket.
1674 if (inp->inp_flags & INP_WILDCARD)
1675 udp_remwildcardhash(inp);
1677 if (inp->inp_laddr.s_addr == INADDR_ANY)
1678 inp->inp_laddr = if_sin->sin_addr;
1679 inp->inp_faddr = sin->sin_addr;
1680 inp->inp_fport = sin->sin_port;
1681 in_pcbinsconnhash(inp);
1683 soisconnected(so);
1685 return 0;
1688 static void
1689 udp_detach2(struct socket *so)
1691 in_pcbdetach(so->so_pcb);
1692 sodiscard(so);
1693 sofree(so);
1696 static void
1697 udp_detach_final_dispatch(netmsg_t msg)
1699 udp_detach2(msg->base.nm_so);
1702 static void
1703 udp_detach_oncpu_dispatch(netmsg_t msg)
1705 struct netmsg_base *clomsg = &msg->base;
1706 struct socket *so = clomsg->nm_so;
1707 struct inpcb *inp = so->so_pcb;
1708 struct thread *td = curthread;
1709 int nextcpu, cpuid = mycpuid;
1711 KASSERT(td->td_type == TD_TYPE_NETISR, ("not in netisr"));
1713 if (inp->inp_flags & INP_WILDCARD) {
1715 * This inp will be removed on the inp's
1716 * owner CPU later, so don't do it now.
1718 if (&td->td_msgport != so->so_port)
1719 in_pcbremwildcardhash_oncpu(inp, &udbinfo[cpuid]);
1722 if (cpuid == 0) {
1724 * Free and clear multicast socket option,
1725 * which is only accessed in netisr0.
1727 ip_freemoptions(inp->inp_moptions);
1728 inp->inp_moptions = NULL;
1731 nextcpu = cpuid + 1;
1732 if (nextcpu < ncpus2) {
1733 lwkt_forwardmsg(netisr_cpuport(nextcpu), &clomsg->lmsg);
1734 } else {
1736 * No one could see this inpcb now; destroy this
1737 * inpcb in its owner netisr.
1739 netmsg_init(clomsg, so, &netisr_apanic_rport, 0,
1740 udp_detach_final_dispatch);
1741 lwkt_sendmsg(so->so_port, &clomsg->lmsg);
1745 static void
1746 udp_detach_syncorig_dispatch(netmsg_t msg)
1748 struct netmsg_base *clomsg = &msg->base;
1749 struct socket *so = clomsg->nm_so;
1752 * Original protocol processing port is synchronized;
1753 * destroy this inpcb in its owner netisr.
1755 netmsg_init(clomsg, so, &netisr_apanic_rport, 0,
1756 udp_detach_final_dispatch);
1757 lwkt_sendmsg(so->so_port, &clomsg->lmsg);
1760 static void
1761 udp_detach(netmsg_t msg)
1763 struct socket *so = msg->detach.base.nm_so;
1764 struct netmsg_base *clomsg;
1765 struct inpcb *inp;
1767 inp = so->so_pcb;
1768 if (inp == NULL) {
1769 lwkt_replymsg(&msg->detach.base.lmsg, EINVAL);
1770 return;
1774 * Reply EJUSTRETURN ASAP, we will call sodiscard() and
1775 * sofree() later.
1777 lwkt_replymsg(&msg->detach.base.lmsg, EJUSTRETURN);
1779 if (ncpus2 == 1) {
1780 /* Only one CPU, detach the inpcb directly. */
1781 udp_detach2(so);
1782 return;
1786 * Remove this inpcb from the inpcb list first, so that
1787 * no one could find this inpcb from the inpcb list.
1789 in_pcbofflist(inp);
1792 * Remove this inpcb from the local port hash directly
1793 * here, so that its bound local port could be recycled
1794 * timely.
1796 in_pcbremporthash(inp);
1798 if (inp->inp_flags & INP_DIRECT_DETACH) {
1800 * Direct detaching is allowed
1802 KASSERT((inp->inp_flags & INP_WILDCARD) == 0,
1803 ("in the wildcardhash"));
1804 KASSERT(inp->inp_moptions == NULL, ("has mcast options"));
1805 if (so->so_orig_port == NULL) {
1806 udp_detach2(so);
1807 } else {
1809 * Protocol processing port changed once, so
1810 * we need to make sure that there are nothing
1811 * left on the original protocol processing
1812 * port before we destroy this socket and inpcb.
1813 * This is more lightweight than going through
1814 * all UDP processing netisrs.
1816 clomsg = &so->so_clomsg;
1817 netmsg_init(clomsg, so, &netisr_apanic_rport,
1818 MSGF_IGNSOPORT, udp_detach_syncorig_dispatch);
1819 lwkt_sendmsg(so->so_orig_port, &clomsg->lmsg);
1821 return;
1825 * Go through netisrs which process UDP to make sure
1826 * no one could find this inpcb anymore.
1828 clomsg = &so->so_clomsg;
1829 netmsg_init(clomsg, so, &netisr_apanic_rport, MSGF_IGNSOPORT,
1830 udp_detach_oncpu_dispatch);
1831 lwkt_sendmsg(netisr_cpuport(0), &clomsg->lmsg);
1834 static void
1835 udp_disconnect(netmsg_t msg)
1837 struct socket *so = msg->disconnect.base.nm_so;
1838 struct inpcb *inp;
1839 boolean_t forwarded;
1840 int error = 0;
1842 inp = so->so_pcb;
1843 if (inp == NULL) {
1844 error = EINVAL;
1845 goto out;
1847 if (inp->inp_faddr.s_addr == INADDR_ANY) {
1848 error = ENOTCONN;
1849 goto out;
1852 soclrstate(so, SS_ISCONNECTED); /* XXX */
1854 in_pcbdisconnect(inp);
1857 * Follow traditional BSD behavior and retain the local port
1858 * binding. But, fix the old misbehavior of overwriting any
1859 * previously bound local address.
1861 if (!(inp->inp_flags & INP_WASBOUND_NOTANY))
1862 inp->inp_laddr.s_addr = INADDR_ANY;
1864 if (so->so_state & SS_ISCLOSING) {
1866 * If this socket is being closed, there is no need
1867 * to put this socket back into wildcard hash table.
1869 error = 0;
1870 goto out;
1873 forwarded = udp_inswildcardhash(inp, &msg->disconnect.base, 0);
1874 if (forwarded) {
1876 * The message is further forwarded, so we are done
1877 * here.
1879 return;
1881 out:
1882 lwkt_replymsg(&msg->disconnect.base.lmsg, error);
1885 void
1886 udp_shutdown(netmsg_t msg)
1888 struct socket *so = msg->shutdown.base.nm_so;
1889 struct inpcb *inp;
1890 int error;
1892 inp = so->so_pcb;
1893 if (inp) {
1894 socantsendmore(so);
1895 error = 0;
1896 } else {
1897 error = EINVAL;
1899 lwkt_replymsg(&msg->shutdown.base.lmsg, error);
1902 struct pr_usrreqs udp_usrreqs = {
1903 .pru_abort = udp_abort,
1904 .pru_accept = pr_generic_notsupp,
1905 .pru_attach = udp_attach,
1906 .pru_bind = udp_bind,
1907 .pru_connect = udp_connect,
1908 .pru_connect2 = pr_generic_notsupp,
1909 .pru_control = in_control_dispatch,
1910 .pru_detach = udp_detach,
1911 .pru_disconnect = udp_disconnect,
1912 .pru_listen = pr_generic_notsupp,
1913 .pru_peeraddr = in_setpeeraddr_dispatch,
1914 .pru_rcvd = pr_generic_notsupp,
1915 .pru_rcvoob = pr_generic_notsupp,
1916 .pru_send = udp_send,
1917 .pru_sense = pru_sense_null,
1918 .pru_shutdown = udp_shutdown,
1919 .pru_sockaddr = in_setsockaddr_dispatch,
1920 .pru_sosend = sosendudp,
1921 .pru_soreceive = soreceive,
1922 .pru_preconnect = udp_preconnect,
1923 .pru_preattach = udp_preattach