PageRenderTime 68ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/sys/kern/uipc_socket.c

https://github.com/brauceunix/libuinet
C | 3902 lines | 2830 code | 357 blank | 715 comment | 768 complexity | 567e0eb2b3bb65b01dd0a33ff9a26120 MD5 | raw file
Possible License(s): 0BSD, BSD-2-Clause, MIT

Large files files are truncated, but you can click here to view the full file

  1. /*-
  2. * Copyright (c) 1982, 1986, 1988, 1990, 1993
  3. * The Regents of the University of California.
  4. * Copyright (c) 2004 The FreeBSD Foundation
  5. * Copyright (c) 2004-2008 Robert N. M. Watson
  6. * All rights reserved.
  7. *
  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. * 4. Neither the name of the University nor the names of its contributors
  17. * may be used to endorse or promote products derived from this software
  18. * without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  21. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  23. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  24. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  25. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  26. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  27. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  28. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  29. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  30. * SUCH DAMAGE.
  31. *
  32. * @(#)uipc_socket.c 8.3 (Berkeley) 4/15/94
  33. */
  34. /*
  35. * Comments on the socket life cycle:
  36. *
  37. * soalloc() sets of socket layer state for a socket, called only by
  38. * socreate() and sonewconn(). Socket layer private.
  39. *
  40. * sodealloc() tears down socket layer state for a socket, called only by
  41. * sofree() and sonewconn(). Socket layer private.
  42. *
  43. * pru_attach() associates protocol layer state with an allocated socket;
  44. * called only once, may fail, aborting socket allocation. This is called
  45. * from socreate() and sonewconn(). Socket layer private.
  46. *
  47. * pru_detach() disassociates protocol layer state from an attached socket,
  48. * and will be called exactly once for sockets in which pru_attach() has
  49. * been successfully called. If pru_attach() returned an error,
  50. * pru_detach() will not be called. Socket layer private.
  51. *
  52. * pru_abort() and pru_close() notify the protocol layer that the last
  53. * consumer of a socket is starting to tear down the socket, and that the
  54. * protocol should terminate the connection. Historically, pru_abort() also
  55. * detached protocol state from the socket state, but this is no longer the
  56. * case.
  57. *
  58. * socreate() creates a socket and attaches protocol state. This is a public
  59. * interface that may be used by socket layer consumers to create new
  60. * sockets.
  61. *
  62. * sonewconn() creates a socket and attaches protocol state. This is a
  63. * public interface that may be used by protocols to create new sockets when
  64. * a new connection is received and will be available for accept() on a
  65. * listen socket.
  66. *
  67. * soclose() destroys a socket after possibly waiting for it to disconnect.
  68. * This is a public interface that socket consumers should use to close and
  69. * release a socket when done with it.
  70. *
  71. * soabort() destroys a socket without waiting for it to disconnect (used
  72. * only for incoming connections that are already partially or fully
  73. * connected). This is used internally by the socket layer when clearing
  74. * listen socket queues (due to overflow or close on the listen socket), but
  75. * is also a public interface protocols may use to abort connections in
  76. * their incomplete listen queues should they no longer be required. Sockets
  77. * placed in completed connection listen queues should not be aborted for
  78. * reasons described in the comment above the soclose() implementation. This
  79. * is not a general purpose close routine, and except in the specific
  80. * circumstances described here, should not be used.
  81. *
  82. * sofree() will free a socket and its protocol state if all references on
  83. * the socket have been released, and is the public interface to attempt to
  84. * free a socket when a reference is removed. This is a socket layer private
  85. * interface.
  86. *
  87. * NOTE: In addition to socreate() and soclose(), which provide a single
  88. * socket reference to the consumer to be managed as required, there are two
  89. * calls to explicitly manage socket references, soref(), and sorele().
  90. * Currently, these are generally required only when transitioning a socket
  91. * from a listen queue to a file descriptor, in order to prevent garbage
  92. * collection of the socket at an untimely moment. For a number of reasons,
  93. * these interfaces are not preferred, and should be avoided.
  94. *
  95. * NOTE: With regard to VNETs the general rule is that callers do not set
  96. * curvnet. Exceptions to this rule include soabort(), sodisconnect(),
  97. * sofree() (and with that sorele(), sotryfree()), as well as sonewconn()
  98. * and sorflush(), which are usually called from a pre-set VNET context.
  99. * sopoll() currently does not need a VNET context to be set.
  100. */
  101. #include <sys/cdefs.h>
  102. __FBSDID("$FreeBSD: release/9.1.0/sys/kern/uipc_socket.c 233353 2012-03-23 11:26:54Z kib $");
  103. #include "opt_inet.h"
  104. #include "opt_inet6.h"
  105. #include "opt_zero.h"
  106. #include "opt_compat.h"
  107. #include "opt_passiveinet.h"
  108. #include "opt_promiscinet.h"
  109. #include <sys/param.h>
  110. #include <sys/systm.h>
  111. #include <sys/fcntl.h>
  112. #include <sys/limits.h>
  113. #include <sys/lock.h>
  114. #include <sys/mac.h>
  115. #include <sys/malloc.h>
  116. #include <sys/mbuf.h>
  117. #include <sys/mutex.h>
  118. #include <sys/domain.h>
  119. #include <sys/file.h> /* for struct knote */
  120. #include <sys/kernel.h>
  121. #include <sys/event.h>
  122. #include <sys/eventhandler.h>
  123. #include <sys/poll.h>
  124. #include <sys/proc.h>
  125. #include <sys/protosw.h>
  126. #include <sys/socket.h>
  127. #include <sys/socketvar.h>
  128. #include <sys/resourcevar.h>
  129. #include <net/route.h>
  130. #include <sys/signalvar.h>
  131. #include <sys/stat.h>
  132. #include <sys/sx.h>
  133. #include <sys/sysctl.h>
  134. #include <sys/uio.h>
  135. #include <sys/jail.h>
  136. #include <net/vnet.h>
  137. #ifdef MAC
  138. #include <security/mac/mac_framework.h>
  139. #endif /* MAC */
  140. #ifdef PROMISCUOUS_INET
  141. #include <netinet/in_promisc.h>
  142. #endif
  143. #include <vm/uma.h>
  144. #ifdef COMPAT_FREEBSD32
  145. #include <sys/mount.h>
  146. #include <sys/sysent.h>
  147. #include <compat/freebsd32/freebsd32.h>
  148. #endif
  149. static int soreceive_rcvoob(struct socket *so, struct uio *uio,
  150. int flags);
  151. static void filt_sordetach(struct knote *kn);
  152. static int filt_soread(struct knote *kn, long hint);
  153. static void filt_sowdetach(struct knote *kn);
  154. static int filt_sowrite(struct knote *kn, long hint);
  155. static int filt_solisten(struct knote *kn, long hint);
  156. static struct filterops solisten_filtops = {
  157. .f_isfd = 1,
  158. .f_detach = filt_sordetach,
  159. .f_event = filt_solisten,
  160. };
  161. static struct filterops soread_filtops = {
  162. .f_isfd = 1,
  163. .f_detach = filt_sordetach,
  164. .f_event = filt_soread,
  165. };
  166. static struct filterops sowrite_filtops = {
  167. .f_isfd = 1,
  168. .f_detach = filt_sowdetach,
  169. .f_event = filt_sowrite,
  170. };
  171. uma_zone_t socket_zone;
  172. so_gen_t so_gencnt; /* generation count for sockets */
  173. int maxsockets;
  174. MALLOC_DEFINE(M_SONAME, "soname", "socket name");
  175. MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
  176. #define VNET_SO_ASSERT(so) \
  177. VNET_ASSERT(curvnet != NULL, \
  178. ("%s:%d curvnet is NULL, so=%p", __func__, __LINE__, (so)));
  179. static int somaxconn = SOMAXCONN;
  180. static int sysctl_somaxconn(SYSCTL_HANDLER_ARGS);
  181. /* XXX: we dont have SYSCTL_USHORT */
  182. SYSCTL_PROC(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLTYPE_UINT | CTLFLAG_RW,
  183. 0, sizeof(int), sysctl_somaxconn, "I", "Maximum pending socket connection "
  184. "queue size");
  185. static int numopensockets;
  186. SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
  187. &numopensockets, 0, "Number of open sockets");
  188. #ifdef ZERO_COPY_SOCKETS
  189. /* These aren't static because they're used in other files. */
  190. int so_zero_copy_send = 1;
  191. int so_zero_copy_receive = 1;
  192. SYSCTL_NODE(_kern_ipc, OID_AUTO, zero_copy, CTLFLAG_RD, 0,
  193. "Zero copy controls");
  194. SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, receive, CTLFLAG_RW,
  195. &so_zero_copy_receive, 0, "Enable zero copy receive");
  196. SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, send, CTLFLAG_RW,
  197. &so_zero_copy_send, 0, "Enable zero copy send");
  198. #endif /* ZERO_COPY_SOCKETS */
  199. /*
  200. * accept_mtx locks down per-socket fields relating to accept queues. See
  201. * socketvar.h for an annotation of the protected fields of struct socket.
  202. */
  203. struct mtx accept_mtx;
  204. MTX_SYSINIT(accept_mtx, &accept_mtx, "accept", MTX_DEF);
  205. /*
  206. * so_global_mtx protects so_gencnt, numopensockets, and the per-socket
  207. * so_gencnt field.
  208. */
  209. static struct mtx so_global_mtx;
  210. MTX_SYSINIT(so_global_mtx, &so_global_mtx, "so_glabel", MTX_DEF);
  211. /*
  212. * General IPC sysctl name space, used by sockets and a variety of other IPC
  213. * types.
  214. */
  215. SYSCTL_NODE(_kern, KERN_IPC, ipc, CTLFLAG_RW, 0, "IPC");
  216. /*
  217. * Sysctl to get and set the maximum global sockets limit. Notify protocols
  218. * of the change so that they can update their dependent limits as required.
  219. */
  220. static int
  221. sysctl_maxsockets(SYSCTL_HANDLER_ARGS)
  222. {
  223. int error, newmaxsockets;
  224. newmaxsockets = maxsockets;
  225. error = sysctl_handle_int(oidp, &newmaxsockets, 0, req);
  226. if (error == 0 && req->newptr) {
  227. if (newmaxsockets > maxsockets) {
  228. maxsockets = newmaxsockets;
  229. if (maxsockets > ((maxfiles / 4) * 3)) {
  230. maxfiles = (maxsockets * 5) / 4;
  231. maxfilesperproc = (maxfiles * 9) / 10;
  232. }
  233. EVENTHANDLER_INVOKE(maxsockets_change);
  234. } else
  235. error = EINVAL;
  236. }
  237. return (error);
  238. }
  239. SYSCTL_PROC(_kern_ipc, OID_AUTO, maxsockets, CTLTYPE_INT|CTLFLAG_RW,
  240. &maxsockets, 0, sysctl_maxsockets, "IU",
  241. "Maximum number of sockets avaliable");
  242. /*
  243. * Initialise maxsockets. This SYSINIT must be run after
  244. * tunable_mbinit().
  245. */
  246. static void
  247. init_maxsockets(void *ignored)
  248. {
  249. TUNABLE_INT_FETCH("kern.ipc.maxsockets", &maxsockets);
  250. maxsockets = imax(maxsockets, imax(maxfiles, nmbclusters));
  251. }
  252. SYSINIT(param, SI_SUB_TUNABLES, SI_ORDER_ANY, init_maxsockets, NULL);
  253. /*
  254. * Socket operation routines. These routines are called by the routines in
  255. * sys_socket.c or from a system process, and implement the semantics of
  256. * socket operations by switching out to the protocol specific routines.
  257. */
  258. /*
  259. * Get a socket structure from our zone, and initialize it. Note that it
  260. * would probably be better to allocate socket and PCB at the same time, but
  261. * I'm not convinced that all the protocols can be easily modified to do
  262. * this.
  263. *
  264. * soalloc() returns a socket with a ref count of 0.
  265. */
  266. static struct socket *
  267. soalloc(struct vnet *vnet)
  268. {
  269. struct socket *so;
  270. so = uma_zalloc(socket_zone, M_NOWAIT | M_ZERO);
  271. if (so == NULL)
  272. return (NULL);
  273. #ifdef MAC
  274. if (mac_socket_init(so, M_NOWAIT) != 0) {
  275. uma_zfree(socket_zone, so);
  276. return (NULL);
  277. }
  278. #endif
  279. #ifdef PROMISCUOUS_INET
  280. if (in_promisc_socket_init(so, M_NOWAIT) != 0) {
  281. #ifdef MAC
  282. mac_socket_destroy(so);
  283. #endif
  284. uma_zfree(socket_zone, so);
  285. return (NULL);
  286. }
  287. #endif /* PROMISCUOUS_INET */
  288. SOCKBUF_LOCK_INIT(&so->so_snd, "so_snd");
  289. SOCKBUF_LOCK_INIT(&so->so_rcv, "so_rcv");
  290. sx_init(&so->so_snd.sb_sx, "so_snd_sx");
  291. sx_init(&so->so_rcv.sb_sx, "so_rcv_sx");
  292. TAILQ_INIT(&so->so_aiojobq);
  293. mtx_lock(&so_global_mtx);
  294. so->so_gencnt = ++so_gencnt;
  295. ++numopensockets;
  296. #ifdef VIMAGE
  297. VNET_ASSERT(vnet != NULL, ("%s:%d vnet is NULL, so=%p",
  298. __func__, __LINE__, so));
  299. vnet->vnet_sockcnt++;
  300. so->so_vnet = vnet;
  301. #endif
  302. mtx_unlock(&so_global_mtx);
  303. return (so);
  304. }
  305. /*
  306. * Free the storage associated with a socket at the socket layer, tear down
  307. * locks, labels, etc. All protocol state is assumed already to have been
  308. * torn down (and possibly never set up) by the caller.
  309. */
  310. static void
  311. sodealloc(struct socket *so)
  312. {
  313. KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
  314. KASSERT(so->so_pcb == NULL, ("sodealloc(): so_pcb != NULL"));
  315. mtx_lock(&so_global_mtx);
  316. so->so_gencnt = ++so_gencnt;
  317. --numopensockets; /* Could be below, but faster here. */
  318. #ifdef VIMAGE
  319. VNET_ASSERT(so->so_vnet != NULL, ("%s:%d so_vnet is NULL, so=%p",
  320. __func__, __LINE__, so));
  321. so->so_vnet->vnet_sockcnt--;
  322. #endif
  323. mtx_unlock(&so_global_mtx);
  324. if (so->so_rcv.sb_hiwat)
  325. (void)chgsbsize(so->so_cred->cr_uidinfo,
  326. &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
  327. if (so->so_snd.sb_hiwat)
  328. (void)chgsbsize(so->so_cred->cr_uidinfo,
  329. &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
  330. #ifdef INET
  331. /* remove acccept filter if one is present. */
  332. if (so->so_accf != NULL)
  333. do_setopt_accept_filter(so, NULL);
  334. #endif
  335. #ifdef PROMISCUOUS_INET
  336. in_promisc_socket_destroy(so);
  337. #endif
  338. #ifdef MAC
  339. mac_socket_destroy(so);
  340. #endif
  341. crfree(so->so_cred);
  342. sx_destroy(&so->so_snd.sb_sx);
  343. sx_destroy(&so->so_rcv.sb_sx);
  344. SOCKBUF_LOCK_DESTROY(&so->so_snd);
  345. SOCKBUF_LOCK_DESTROY(&so->so_rcv);
  346. uma_zfree(socket_zone, so);
  347. }
  348. /*
  349. * socreate returns a socket with a ref count of 1. The socket should be
  350. * closed with soclose().
  351. */
  352. int
  353. socreate(int dom, struct socket **aso, int type, int proto,
  354. struct ucred *cred, struct thread *td)
  355. {
  356. struct protosw *prp;
  357. struct socket *so;
  358. int error;
  359. if (proto)
  360. prp = pffindproto(dom, proto, type);
  361. else
  362. prp = pffindtype(dom, type);
  363. if (prp == NULL || prp->pr_usrreqs->pru_attach == NULL ||
  364. prp->pr_usrreqs->pru_attach == pru_attach_notsupp)
  365. return (EPROTONOSUPPORT);
  366. if (prison_check_af(cred, prp->pr_domain->dom_family) != 0)
  367. return (EPROTONOSUPPORT);
  368. if (prp->pr_type != type)
  369. return (EPROTOTYPE);
  370. so = soalloc(CRED_TO_VNET(cred));
  371. if (so == NULL)
  372. return (ENOBUFS);
  373. TAILQ_INIT(&so->so_incomp);
  374. TAILQ_INIT(&so->so_comp);
  375. so->so_type = type;
  376. so->so_cred = crhold(cred);
  377. if ((prp->pr_domain->dom_family == PF_INET) ||
  378. (prp->pr_domain->dom_family == PF_INET6) ||
  379. (prp->pr_domain->dom_family == PF_ROUTE))
  380. so->so_fibnum = td->td_proc->p_fibnum;
  381. else
  382. so->so_fibnum = 0;
  383. so->so_proto = prp;
  384. #ifdef MAC
  385. mac_socket_create(cred, so);
  386. #endif
  387. knlist_init_mtx(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv));
  388. knlist_init_mtx(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd));
  389. so->so_count = 1;
  390. /*
  391. * Auto-sizing of socket buffers is managed by the protocols and
  392. * the appropriate flags must be set in the pru_attach function.
  393. */
  394. CURVNET_SET(so->so_vnet);
  395. error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
  396. CURVNET_RESTORE();
  397. if (error) {
  398. KASSERT(so->so_count == 1, ("socreate: so_count %d",
  399. so->so_count));
  400. so->so_count = 0;
  401. sodealloc(so);
  402. return (error);
  403. }
  404. *aso = so;
  405. return (0);
  406. }
  407. #ifdef REGRESSION
  408. static int regression_sonewconn_earlytest = 1;
  409. SYSCTL_INT(_regression, OID_AUTO, sonewconn_earlytest, CTLFLAG_RW,
  410. &regression_sonewconn_earlytest, 0, "Perform early sonewconn limit test");
  411. #endif
  412. /*
  413. * When an attempt at a new connection is noted on a socket which accepts
  414. * connections, sonewconn is called. If the connection is possible (subject
  415. * to space constraints, etc.) then we allocate a new structure, properly
  416. * linked into the data structure of the original socket, and return this.
  417. * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTED.
  418. *
  419. * Note: the ref count on the socket is 0 on return.
  420. */
  421. struct socket *
  422. sonewconn(struct socket *head, int connstatus)
  423. {
  424. struct socket *so;
  425. int over;
  426. ACCEPT_LOCK();
  427. over = (head->so_qlen > 3 * head->so_qlimit / 2);
  428. ACCEPT_UNLOCK();
  429. #ifdef REGRESSION
  430. if (regression_sonewconn_earlytest && over)
  431. #else
  432. if (over)
  433. #endif
  434. return (NULL);
  435. VNET_ASSERT(head->so_vnet != NULL, ("%s:%d so_vnet is NULL, head=%p",
  436. __func__, __LINE__, head));
  437. so = soalloc(head->so_vnet);
  438. if (so == NULL)
  439. return (NULL);
  440. if ((head->so_options & SO_ACCEPTFILTER) != 0)
  441. connstatus = 0;
  442. so->so_head = head;
  443. so->so_type = head->so_type;
  444. so->so_options = head->so_options &~ SO_ACCEPTCONN;
  445. so->so_linger = head->so_linger;
  446. so->so_state = head->so_state | SS_NOFDREF;
  447. so->so_fibnum = head->so_fibnum;
  448. so->so_proto = head->so_proto;
  449. so->so_cred = crhold(head->so_cred);
  450. #ifdef MAC
  451. mac_socket_newconn(head, so);
  452. #endif
  453. #ifdef PROMISCUOUS_INET
  454. in_promisc_socket_newconn(head, so);
  455. #endif
  456. knlist_init_mtx(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv));
  457. knlist_init_mtx(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd));
  458. VNET_SO_ASSERT(head);
  459. if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat) ||
  460. (*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
  461. sodealloc(so);
  462. return (NULL);
  463. }
  464. so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
  465. so->so_snd.sb_lowat = head->so_snd.sb_lowat;
  466. so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
  467. so->so_snd.sb_timeo = head->so_snd.sb_timeo;
  468. so->so_rcv.sb_flags |= head->so_rcv.sb_flags & SB_AUTOSIZE;
  469. so->so_snd.sb_flags |= head->so_snd.sb_flags & SB_AUTOSIZE;
  470. so->so_state |= connstatus;
  471. ACCEPT_LOCK();
  472. if (connstatus) {
  473. TAILQ_INSERT_TAIL(&head->so_comp, so, so_list);
  474. so->so_qstate |= SQ_COMP;
  475. head->so_qlen++;
  476. } else {
  477. /*
  478. * Keep removing sockets from the head until there's room for
  479. * us to insert on the tail. In pre-locking revisions, this
  480. * was a simple if(), but as we could be racing with other
  481. * threads and soabort() requires dropping locks, we must
  482. * loop waiting for the condition to be true.
  483. */
  484. while (head->so_incqlen > head->so_qlimit) {
  485. struct socket *sp;
  486. sp = TAILQ_FIRST(&head->so_incomp);
  487. TAILQ_REMOVE(&head->so_incomp, sp, so_list);
  488. head->so_incqlen--;
  489. sp->so_qstate &= ~SQ_INCOMP;
  490. sp->so_head = NULL;
  491. ACCEPT_UNLOCK();
  492. soabort(sp);
  493. ACCEPT_LOCK();
  494. }
  495. TAILQ_INSERT_TAIL(&head->so_incomp, so, so_list);
  496. so->so_qstate |= SQ_INCOMP;
  497. head->so_incqlen++;
  498. }
  499. ACCEPT_UNLOCK();
  500. if (connstatus) {
  501. sorwakeup(head);
  502. wakeup_one(&head->so_timeo);
  503. }
  504. return (so);
  505. }
  506. #ifdef PASSIVE_INET
  507. /*
  508. * When a new connection is completed on a listening socket that is
  509. * configured for passive reassembly, sonewconn_passive_client is called to
  510. * create a socket representing the client side of the reassembled
  511. * connection. We allocate a new structure, inherit configuration from the
  512. * listening socket, and return this.
  513. * Connstatus may be 0, or SO_ISCONFIRMING, or SO_ISCONNECTING.
  514. *
  515. * Note: the ref count on the socket is 1 on return.
  516. */
  517. struct socket *
  518. sonewconn_passive_client(struct socket *head, int connstatus)
  519. {
  520. struct socket *so;
  521. VNET_ASSERT(head->so_vnet != NULL, ("%s:%d so_vnet is NULL, head=%p",
  522. __func__, __LINE__, head));
  523. so = soalloc(head->so_vnet);
  524. if (so == NULL)
  525. return (NULL);
  526. so->so_head = NULL; /* just inheriting from head, not otherwise associating */
  527. so->so_type = head->so_type;
  528. so->so_options = head->so_options &~ SO_ACCEPTCONN;
  529. so->so_linger = head->so_linger;
  530. so->so_state = head->so_state | SS_NOFDREF;
  531. so->so_fibnum = head->so_fibnum;
  532. so->so_proto = head->so_proto;
  533. so->so_cred = crhold(head->so_cred);
  534. #ifdef MAC
  535. mac_socket_newconn(head, so);
  536. #endif
  537. #ifdef PROMISCUOUS_INET
  538. in_promisc_socket_newconn(head, so);
  539. #endif
  540. knlist_init_mtx(&so->so_rcv.sb_sel.si_note, SOCKBUF_MTX(&so->so_rcv));
  541. knlist_init_mtx(&so->so_snd.sb_sel.si_note, SOCKBUF_MTX(&so->so_snd));
  542. VNET_SO_ASSERT(head);
  543. if (soreserve(so, head->so_snd.sb_hiwat, head->so_rcv.sb_hiwat) ||
  544. (*so->so_proto->pr_usrreqs->pru_attach)(so, 0, NULL)) {
  545. sodealloc(so);
  546. return (NULL);
  547. }
  548. so->so_rcv.sb_lowat = head->so_rcv.sb_lowat;
  549. so->so_snd.sb_lowat = head->so_snd.sb_lowat;
  550. so->so_rcv.sb_timeo = head->so_rcv.sb_timeo;
  551. so->so_snd.sb_timeo = head->so_snd.sb_timeo;
  552. so->so_rcv.sb_flags |= head->so_rcv.sb_flags & SB_AUTOSIZE;
  553. so->so_snd.sb_flags |= head->so_snd.sb_flags & SB_AUTOSIZE;
  554. so->so_state |= connstatus;
  555. return (so);
  556. }
  557. #endif /* PASSIVE_INET */
  558. int
  559. sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
  560. {
  561. int error;
  562. CURVNET_SET(so->so_vnet);
  563. error = (*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td);
  564. CURVNET_RESTORE();
  565. return error;
  566. }
  567. /*
  568. * solisten() transitions a socket from a non-listening state to a listening
  569. * state, but can also be used to update the listen queue depth on an
  570. * existing listen socket. The protocol will call back into the sockets
  571. * layer using solisten_proto_check() and solisten_proto() to check and set
  572. * socket-layer listen state. Call backs are used so that the protocol can
  573. * acquire both protocol and socket layer locks in whatever order is required
  574. * by the protocol.
  575. *
  576. * Protocol implementors are advised to hold the socket lock across the
  577. * socket-layer test and set to avoid races at the socket layer.
  578. */
  579. int
  580. solisten(struct socket *so, int backlog, struct thread *td)
  581. {
  582. int error;
  583. CURVNET_SET(so->so_vnet);
  584. error = (*so->so_proto->pr_usrreqs->pru_listen)(so, backlog, td);
  585. CURVNET_RESTORE();
  586. return error;
  587. }
  588. int
  589. solisten_proto_check(struct socket *so)
  590. {
  591. SOCK_LOCK_ASSERT(so);
  592. if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING |
  593. SS_ISDISCONNECTING))
  594. return (EINVAL);
  595. return (0);
  596. }
  597. void
  598. solisten_proto(struct socket *so, int backlog)
  599. {
  600. SOCK_LOCK_ASSERT(so);
  601. if (backlog < 0 || backlog > somaxconn)
  602. backlog = somaxconn;
  603. so->so_qlimit = backlog;
  604. so->so_options |= SO_ACCEPTCONN;
  605. }
  606. /*
  607. * Evaluate the reference count and named references on a socket; if no
  608. * references remain, free it. This should be called whenever a reference is
  609. * released, such as in sorele(), but also when named reference flags are
  610. * cleared in socket or protocol code.
  611. *
  612. * sofree() will free the socket if:
  613. *
  614. * - There are no outstanding file descriptor references or related consumers
  615. * (so_count == 0).
  616. *
  617. * - The socket has been closed by user space, if ever open (SS_NOFDREF).
  618. *
  619. * - The protocol does not have an outstanding strong reference on the socket
  620. * (SS_PROTOREF).
  621. *
  622. * - The socket is not in a completed connection queue, so a process has been
  623. * notified that it is present. If it is removed, the user process may
  624. * block in accept() despite select() saying the socket was ready.
  625. */
  626. void
  627. sofree(struct socket *so)
  628. {
  629. struct protosw *pr = so->so_proto;
  630. struct socket *head;
  631. ACCEPT_LOCK_ASSERT();
  632. SOCK_LOCK_ASSERT(so);
  633. if ((so->so_state & SS_NOFDREF) == 0 || so->so_count != 0 ||
  634. (so->so_state & SS_PROTOREF) || (so->so_qstate & SQ_COMP)) {
  635. SOCK_UNLOCK(so);
  636. ACCEPT_UNLOCK();
  637. return;
  638. }
  639. head = so->so_head;
  640. if (head != NULL) {
  641. KASSERT((so->so_qstate & SQ_COMP) != 0 ||
  642. (so->so_qstate & SQ_INCOMP) != 0,
  643. ("sofree: so_head != NULL, but neither SQ_COMP nor "
  644. "SQ_INCOMP"));
  645. KASSERT((so->so_qstate & SQ_COMP) == 0 ||
  646. (so->so_qstate & SQ_INCOMP) == 0,
  647. ("sofree: so->so_qstate is SQ_COMP and also SQ_INCOMP"));
  648. TAILQ_REMOVE(&head->so_incomp, so, so_list);
  649. head->so_incqlen--;
  650. so->so_qstate &= ~SQ_INCOMP;
  651. so->so_head = NULL;
  652. }
  653. KASSERT((so->so_qstate & SQ_COMP) == 0 &&
  654. (so->so_qstate & SQ_INCOMP) == 0,
  655. ("sofree: so_head == NULL, but still SQ_COMP(%d) or SQ_INCOMP(%d)",
  656. so->so_qstate & SQ_COMP, so->so_qstate & SQ_INCOMP));
  657. if (so->so_options & SO_ACCEPTCONN) {
  658. KASSERT((TAILQ_EMPTY(&so->so_comp)), ("sofree: so_comp populated"));
  659. KASSERT((TAILQ_EMPTY(&so->so_incomp)), ("sofree: so_comp populated"));
  660. }
  661. SOCK_UNLOCK(so);
  662. ACCEPT_UNLOCK();
  663. VNET_SO_ASSERT(so);
  664. if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose != NULL)
  665. (*pr->pr_domain->dom_dispose)(so->so_rcv.sb_mb);
  666. if (pr->pr_usrreqs->pru_detach != NULL)
  667. (*pr->pr_usrreqs->pru_detach)(so);
  668. /*
  669. * From this point on, we assume that no other references to this
  670. * socket exist anywhere else in the stack. Therefore, no locks need
  671. * to be acquired or held.
  672. *
  673. * We used to do a lot of socket buffer and socket locking here, as
  674. * well as invoke sorflush() and perform wakeups. The direct call to
  675. * dom_dispose() and sbrelease_internal() are an inlining of what was
  676. * necessary from sorflush().
  677. *
  678. * Notice that the socket buffer and kqueue state are torn down
  679. * before calling pru_detach. This means that protocols shold not
  680. * assume they can perform socket wakeups, etc, in their detach code.
  681. */
  682. sbdestroy(&so->so_snd, so);
  683. sbdestroy(&so->so_rcv, so);
  684. seldrain(&so->so_snd.sb_sel);
  685. seldrain(&so->so_rcv.sb_sel);
  686. knlist_destroy(&so->so_rcv.sb_sel.si_note);
  687. knlist_destroy(&so->so_snd.sb_sel.si_note);
  688. sodealloc(so);
  689. }
  690. /*
  691. * Close a socket on last file table reference removal. Initiate disconnect
  692. * if connected. Free socket when disconnect complete.
  693. *
  694. * This function will sorele() the socket. Note that soclose() may be called
  695. * prior to the ref count reaching zero. The actual socket structure will
  696. * not be freed until the ref count reaches zero.
  697. */
  698. int
  699. soclose(struct socket *so)
  700. {
  701. int error = 0;
  702. KASSERT(!(so->so_state & SS_NOFDREF), ("soclose: SS_NOFDREF on enter"));
  703. CURVNET_SET(so->so_vnet);
  704. funsetown(&so->so_sigio);
  705. if (so->so_state & SS_ISCONNECTED) {
  706. if ((so->so_state & SS_ISDISCONNECTING) == 0) {
  707. error = sodisconnect(so);
  708. if (error) {
  709. if (error == ENOTCONN)
  710. error = 0;
  711. goto drop;
  712. }
  713. }
  714. if (so->so_options & SO_LINGER) {
  715. if ((so->so_state & SS_ISDISCONNECTING) &&
  716. (so->so_state & SS_NBIO))
  717. goto drop;
  718. while (so->so_state & SS_ISCONNECTED) {
  719. error = tsleep(&so->so_timeo,
  720. PSOCK | PCATCH, "soclos", so->so_linger * hz);
  721. if (error)
  722. break;
  723. }
  724. }
  725. }
  726. drop:
  727. if (so->so_proto->pr_usrreqs->pru_close != NULL)
  728. (*so->so_proto->pr_usrreqs->pru_close)(so);
  729. if (so->so_options & SO_ACCEPTCONN) {
  730. struct socket *sp;
  731. ACCEPT_LOCK();
  732. while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
  733. TAILQ_REMOVE(&so->so_incomp, sp, so_list);
  734. so->so_incqlen--;
  735. sp->so_qstate &= ~SQ_INCOMP;
  736. sp->so_head = NULL;
  737. ACCEPT_UNLOCK();
  738. soabort(sp);
  739. ACCEPT_LOCK();
  740. }
  741. while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
  742. TAILQ_REMOVE(&so->so_comp, sp, so_list);
  743. so->so_qlen--;
  744. sp->so_qstate &= ~SQ_COMP;
  745. sp->so_head = NULL;
  746. ACCEPT_UNLOCK();
  747. soabort(sp);
  748. ACCEPT_LOCK();
  749. }
  750. ACCEPT_UNLOCK();
  751. }
  752. ACCEPT_LOCK();
  753. SOCK_LOCK(so);
  754. KASSERT((so->so_state & SS_NOFDREF) == 0, ("soclose: NOFDREF"));
  755. so->so_state |= SS_NOFDREF;
  756. sorele(so);
  757. CURVNET_RESTORE();
  758. return (error);
  759. }
  760. /*
  761. * soabort() is used to abruptly tear down a connection, such as when a
  762. * resource limit is reached (listen queue depth exceeded), or if a listen
  763. * socket is closed while there are sockets waiting to be accepted.
  764. *
  765. * This interface is tricky, because it is called on an unreferenced socket,
  766. * and must be called only by a thread that has actually removed the socket
  767. * from the listen queue it was on, or races with other threads are risked.
  768. *
  769. * This interface will call into the protocol code, so must not be called
  770. * with any socket locks held. Protocols do call it while holding their own
  771. * recursible protocol mutexes, but this is something that should be subject
  772. * to review in the future.
  773. */
  774. void
  775. soabort(struct socket *so)
  776. {
  777. /*
  778. * In as much as is possible, assert that no references to this
  779. * socket are held. This is not quite the same as asserting that the
  780. * current thread is responsible for arranging for no references, but
  781. * is as close as we can get for now.
  782. */
  783. KASSERT(so->so_count == 0, ("soabort: so_count"));
  784. KASSERT((so->so_state & SS_PROTOREF) == 0, ("soabort: SS_PROTOREF"));
  785. KASSERT(so->so_state & SS_NOFDREF, ("soabort: !SS_NOFDREF"));
  786. KASSERT((so->so_state & SQ_COMP) == 0, ("soabort: SQ_COMP"));
  787. KASSERT((so->so_state & SQ_INCOMP) == 0, ("soabort: SQ_INCOMP"));
  788. VNET_SO_ASSERT(so);
  789. if (so->so_proto->pr_usrreqs->pru_abort != NULL)
  790. (*so->so_proto->pr_usrreqs->pru_abort)(so);
  791. ACCEPT_LOCK();
  792. SOCK_LOCK(so);
  793. sofree(so);
  794. }
  795. int
  796. soaccept(struct socket *so, struct sockaddr **nam)
  797. {
  798. int error;
  799. SOCK_LOCK(so);
  800. KASSERT((so->so_state & SS_NOFDREF) != 0, ("soaccept: !NOFDREF"));
  801. so->so_state &= ~SS_NOFDREF;
  802. SOCK_UNLOCK(so);
  803. CURVNET_SET(so->so_vnet);
  804. error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
  805. CURVNET_RESTORE();
  806. return (error);
  807. }
  808. int
  809. soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
  810. {
  811. int error;
  812. if (so->so_options & SO_ACCEPTCONN)
  813. return (EOPNOTSUPP);
  814. CURVNET_SET(so->so_vnet);
  815. /*
  816. * If protocol is connection-based, can only connect once.
  817. * Otherwise, if connected, try to disconnect first. This allows
  818. * user to disconnect by connecting to, e.g., a null address.
  819. */
  820. if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
  821. ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
  822. (error = sodisconnect(so)))) {
  823. error = EISCONN;
  824. } else {
  825. /*
  826. * Prevent accumulated error from previous connection from
  827. * biting us.
  828. */
  829. so->so_error = 0;
  830. error = (*so->so_proto->pr_usrreqs->pru_connect)(so, nam, td);
  831. }
  832. CURVNET_RESTORE();
  833. return (error);
  834. }
  835. int
  836. soconnect2(struct socket *so1, struct socket *so2)
  837. {
  838. int error;
  839. CURVNET_SET(so1->so_vnet);
  840. error = (*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2);
  841. CURVNET_RESTORE();
  842. return (error);
  843. }
  844. int
  845. sodisconnect(struct socket *so)
  846. {
  847. int error;
  848. if ((so->so_state & SS_ISCONNECTED) == 0)
  849. return (ENOTCONN);
  850. if (so->so_state & SS_ISDISCONNECTING)
  851. return (EALREADY);
  852. VNET_SO_ASSERT(so);
  853. error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
  854. return (error);
  855. }
  856. #ifdef ZERO_COPY_SOCKETS
  857. struct so_zerocopy_stats{
  858. int size_ok;
  859. int align_ok;
  860. int found_ifp;
  861. };
  862. struct so_zerocopy_stats so_zerocp_stats = {0,0,0};
  863. #include <netinet/in.h>
  864. #include <net/route.h>
  865. #include <netinet/in_pcb.h>
  866. #include <vm/vm.h>
  867. #include <vm/vm_page.h>
  868. #include <vm/vm_object.h>
  869. /*
  870. * sosend_copyin() is only used if zero copy sockets are enabled. Otherwise
  871. * sosend_dgram() and sosend_generic() use m_uiotombuf().
  872. *
  873. * sosend_copyin() accepts a uio and prepares an mbuf chain holding part or
  874. * all of the data referenced by the uio. If desired, it uses zero-copy.
  875. * *space will be updated to reflect data copied in.
  876. *
  877. * NB: If atomic I/O is requested, the caller must already have checked that
  878. * space can hold resid bytes.
  879. *
  880. * NB: In the event of an error, the caller may need to free the partial
  881. * chain pointed to by *mpp. The contents of both *uio and *space may be
  882. * modified even in the case of an error.
  883. */
  884. static int
  885. sosend_copyin(struct uio *uio, struct mbuf **retmp, int atomic, long *space,
  886. int flags)
  887. {
  888. struct mbuf *m, **mp, *top;
  889. long len;
  890. ssize_t resid;
  891. int error;
  892. #ifdef ZERO_COPY_SOCKETS
  893. int cow_send;
  894. #endif
  895. *retmp = top = NULL;
  896. mp = &top;
  897. len = 0;
  898. resid = uio->uio_resid;
  899. error = 0;
  900. do {
  901. #ifdef ZERO_COPY_SOCKETS
  902. cow_send = 0;
  903. #endif /* ZERO_COPY_SOCKETS */
  904. if (resid >= MINCLSIZE) {
  905. #ifdef ZERO_COPY_SOCKETS
  906. if (top == NULL) {
  907. m = m_gethdr(M_WAITOK, MT_DATA);
  908. m->m_pkthdr.len = 0;
  909. m->m_pkthdr.rcvif = NULL;
  910. } else
  911. m = m_get(M_WAITOK, MT_DATA);
  912. if (so_zero_copy_send &&
  913. resid>=PAGE_SIZE &&
  914. *space>=PAGE_SIZE &&
  915. uio->uio_iov->iov_len>=PAGE_SIZE) {
  916. so_zerocp_stats.size_ok++;
  917. so_zerocp_stats.align_ok++;
  918. cow_send = socow_setup(m, uio);
  919. len = cow_send;
  920. }
  921. if (!cow_send) {
  922. m_clget(m, M_WAITOK);
  923. len = min(min(MCLBYTES, resid), *space);
  924. }
  925. #else /* ZERO_COPY_SOCKETS */
  926. if (top == NULL) {
  927. m = m_getcl(M_WAIT, MT_DATA, M_PKTHDR);
  928. m->m_pkthdr.len = 0;
  929. m->m_pkthdr.rcvif = NULL;
  930. } else
  931. m = m_getcl(M_WAIT, MT_DATA, 0);
  932. len = min(min(MCLBYTES, resid), *space);
  933. #endif /* ZERO_COPY_SOCKETS */
  934. } else {
  935. if (top == NULL) {
  936. m = m_gethdr(M_WAIT, MT_DATA);
  937. m->m_pkthdr.len = 0;
  938. m->m_pkthdr.rcvif = NULL;
  939. len = min(min(MHLEN, resid), *space);
  940. /*
  941. * For datagram protocols, leave room
  942. * for protocol headers in first mbuf.
  943. */
  944. if (atomic && m && len < MHLEN)
  945. MH_ALIGN(m, len);
  946. } else {
  947. m = m_get(M_WAIT, MT_DATA);
  948. len = min(min(MLEN, resid), *space);
  949. }
  950. }
  951. if (m == NULL) {
  952. error = ENOBUFS;
  953. goto out;
  954. }
  955. *space -= len;
  956. #ifdef ZERO_COPY_SOCKETS
  957. if (cow_send)
  958. error = 0;
  959. else
  960. #endif /* ZERO_COPY_SOCKETS */
  961. error = uiomove(mtod(m, void *), (int)len, uio);
  962. resid = uio->uio_resid;
  963. m->m_len = len;
  964. *mp = m;
  965. top->m_pkthdr.len += len;
  966. if (error)
  967. goto out;
  968. mp = &m->m_next;
  969. if (resid <= 0) {
  970. if (flags & MSG_EOR)
  971. top->m_flags |= M_EOR;
  972. break;
  973. }
  974. } while (*space > 0 && atomic);
  975. out:
  976. *retmp = top;
  977. return (error);
  978. }
  979. #endif /*ZERO_COPY_SOCKETS*/
  980. #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? 0 : SBL_WAIT)
  981. int
  982. sosend_dgram(struct socket *so, struct sockaddr *addr, struct uio *uio,
  983. struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
  984. {
  985. long space;
  986. ssize_t resid;
  987. int clen = 0, error, dontroute;
  988. #ifdef ZERO_COPY_SOCKETS
  989. int atomic = sosendallatonce(so) || top;
  990. #endif
  991. KASSERT(so->so_type == SOCK_DGRAM, ("sodgram_send: !SOCK_DGRAM"));
  992. KASSERT(so->so_proto->pr_flags & PR_ATOMIC,
  993. ("sodgram_send: !PR_ATOMIC"));
  994. if (uio != NULL)
  995. resid = uio->uio_resid;
  996. else
  997. resid = top->m_pkthdr.len;
  998. /*
  999. * In theory resid should be unsigned. However, space must be
  1000. * signed, as it might be less than 0 if we over-committed, and we
  1001. * must use a signed comparison of space and resid. On the other
  1002. * hand, a negative resid causes us to loop sending 0-length
  1003. * segments to the protocol.
  1004. */
  1005. if (resid < 0) {
  1006. error = EINVAL;
  1007. goto out;
  1008. }
  1009. dontroute =
  1010. (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0;
  1011. if (td != NULL)
  1012. td->td_ru.ru_msgsnd++;
  1013. if (control != NULL)
  1014. clen = control->m_len;
  1015. SOCKBUF_LOCK(&so->so_snd);
  1016. if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
  1017. SOCKBUF_UNLOCK(&so->so_snd);
  1018. error = EPIPE;
  1019. goto out;
  1020. }
  1021. if (so->so_error) {
  1022. error = so->so_error;
  1023. so->so_error = 0;
  1024. SOCKBUF_UNLOCK(&so->so_snd);
  1025. goto out;
  1026. }
  1027. if ((so->so_state & SS_ISCONNECTED) == 0) {
  1028. /*
  1029. * `sendto' and `sendmsg' is allowed on a connection-based
  1030. * socket if it supports implied connect. Return ENOTCONN if
  1031. * not connected and no address is supplied.
  1032. */
  1033. if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
  1034. (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
  1035. if ((so->so_state & SS_ISCONFIRMING) == 0 &&
  1036. !(resid == 0 && clen != 0)) {
  1037. SOCKBUF_UNLOCK(&so->so_snd);
  1038. error = ENOTCONN;
  1039. goto out;
  1040. }
  1041. } else if (addr == NULL) {
  1042. if (so->so_proto->pr_flags & PR_CONNREQUIRED)
  1043. error = ENOTCONN;
  1044. else
  1045. error = EDESTADDRREQ;
  1046. SOCKBUF_UNLOCK(&so->so_snd);
  1047. goto out;
  1048. }
  1049. }
  1050. /*
  1051. * Do we need MSG_OOB support in SOCK_DGRAM? Signs here may be a
  1052. * problem and need fixing.
  1053. */
  1054. space = sbspace(&so->so_snd);
  1055. if (flags & MSG_OOB)
  1056. space += 1024;
  1057. space -= clen;
  1058. SOCKBUF_UNLOCK(&so->so_snd);
  1059. if (resid > space) {
  1060. error = EMSGSIZE;
  1061. goto out;
  1062. }
  1063. if (uio == NULL) {
  1064. resid = 0;
  1065. if (flags & MSG_EOR)
  1066. top->m_flags |= M_EOR;
  1067. } else {
  1068. #ifdef ZERO_COPY_SOCKETS
  1069. error = sosend_copyin(uio, &top, atomic, &space, flags);
  1070. if (error)
  1071. goto out;
  1072. #else
  1073. /*
  1074. * Copy the data from userland into a mbuf chain.
  1075. * If no data is to be copied in, a single empty mbuf
  1076. * is returned.
  1077. */
  1078. top = m_uiotombuf(uio, M_WAITOK, space, max_hdr,
  1079. (M_PKTHDR | ((flags & MSG_EOR) ? M_EOR : 0)));
  1080. if (top == NULL) {
  1081. error = EFAULT; /* only possible error */
  1082. goto out;
  1083. }
  1084. space -= resid - uio->uio_resid;
  1085. #endif
  1086. resid = uio->uio_resid;
  1087. }
  1088. KASSERT(resid == 0, ("sosend_dgram: resid != 0"));
  1089. /*
  1090. * XXXRW: Frobbing SO_DONTROUTE here is even worse without sblock
  1091. * than with.
  1092. */
  1093. if (dontroute) {
  1094. SOCK_LOCK(so);
  1095. so->so_options |= SO_DONTROUTE;
  1096. SOCK_UNLOCK(so);
  1097. }
  1098. /*
  1099. * XXX all the SBS_CANTSENDMORE checks previously done could be out
  1100. * of date. We could have recieved a reset packet in an interrupt or
  1101. * maybe we slept while doing page faults in uiomove() etc. We could
  1102. * probably recheck again inside the locking protection here, but
  1103. * there are probably other places that this also happens. We must
  1104. * rethink this.
  1105. */
  1106. VNET_SO_ASSERT(so);
  1107. error = (*so->so_proto->pr_usrreqs->pru_send)(so,
  1108. (flags & MSG_OOB) ? PRUS_OOB :
  1109. /*
  1110. * If the user set MSG_EOF, the protocol understands this flag and
  1111. * nothing left to send then use PRU_SEND_EOF instead of PRU_SEND.
  1112. */
  1113. ((flags & MSG_EOF) &&
  1114. (so->so_proto->pr_flags & PR_IMPLOPCL) &&
  1115. (resid <= 0)) ?
  1116. PRUS_EOF :
  1117. /* If there is more to send set PRUS_MORETOCOME */
  1118. (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
  1119. top, addr, control, td);
  1120. if (dontroute) {
  1121. SOCK_LOCK(so);
  1122. so->so_options &= ~SO_DONTROUTE;
  1123. SOCK_UNLOCK(so);
  1124. }
  1125. clen = 0;
  1126. control = NULL;
  1127. top = NULL;
  1128. out:
  1129. if (top != NULL)
  1130. m_freem(top);
  1131. if (control != NULL)
  1132. m_freem(control);
  1133. return (error);
  1134. }
  1135. /*
  1136. * Send on a socket. If send must go all at once and message is larger than
  1137. * send buffering, then hard error. Lock against other senders. If must go
  1138. * all at once and not enough room now, then inform user that this would
  1139. * block and do nothing. Otherwise, if nonblocking, send as much as
  1140. * possible. The data to be sent is described by "uio" if nonzero, otherwise
  1141. * by the mbuf chain "top" (which must be null if uio is not). Data provided
  1142. * in mbuf chain must be small enough to send all at once.
  1143. *
  1144. * Returns nonzero on error, timeout or signal; callers must check for short
  1145. * counts if EINTR/ERESTART are returned. Data and control buffers are freed
  1146. * on return.
  1147. */
  1148. int
  1149. sosend_generic(struct socket *so, struct sockaddr *addr, struct uio *uio,
  1150. struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
  1151. {
  1152. long space;
  1153. ssize_t resid;
  1154. int clen = 0, error, dontroute;
  1155. int atomic = sosendallatonce(so) || top;
  1156. if (uio != NULL)
  1157. resid = uio->uio_resid;
  1158. else
  1159. resid = top->m_pkthdr.len;
  1160. /*
  1161. * In theory resid should be unsigned. However, space must be
  1162. * signed, as it might be less than 0 if we over-committed, and we
  1163. * must use a signed comparison of space and resid. On the other
  1164. * hand, a negative resid causes us to loop sending 0-length
  1165. * segments to the protocol.
  1166. *
  1167. * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
  1168. * type sockets since that's an error.
  1169. */
  1170. if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
  1171. error = EINVAL;
  1172. goto out;
  1173. }
  1174. dontroute =
  1175. (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
  1176. (so->so_proto->pr_flags & PR_ATOMIC);
  1177. if (td != NULL)
  1178. td->td_ru.ru_msgsnd++;
  1179. if (control != NULL)
  1180. clen = control->m_len;
  1181. error = sblock(&so->so_snd, SBLOCKWAIT(flags));
  1182. if (error)
  1183. goto out;
  1184. restart:
  1185. do {
  1186. SOCKBUF_LOCK(&so->so_snd);
  1187. if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
  1188. SOCKBUF_UNLOCK(&so->so_snd);
  1189. error = EPIPE;
  1190. goto release;
  1191. }
  1192. if (so->so_error) {
  1193. error = so->so_error;
  1194. so->so_error = 0;
  1195. SOCKBUF_UNLOCK(&so->so_snd);
  1196. goto release;
  1197. }
  1198. if ((so->so_state & SS_ISCONNECTED) == 0) {
  1199. /*
  1200. * `sendto' and `sendmsg' is allowed on a connection-
  1201. * based socket if it supports implied connect.
  1202. * Return ENOTCONN if not connected and no address is
  1203. * supplied.
  1204. */
  1205. if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
  1206. (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
  1207. if ((so->so_state & SS_ISCONFIRMING) == 0 &&
  1208. !(resid == 0 && clen != 0)) {
  1209. SOCKBUF_UNLOCK(&so->so_snd);
  1210. error = ENOTCONN;
  1211. goto release;
  1212. }
  1213. } else if (addr == NULL) {
  1214. SOCKBUF_UNLOCK(&so->so_snd);
  1215. if (so->so_proto->pr_flags & PR_CONNREQUIRED)
  1216. error = ENOTCONN;
  1217. else
  1218. error = EDESTADDRREQ;
  1219. goto release;
  1220. }
  1221. }
  1222. space = sbspace(&so->so_snd);
  1223. if (flags & MSG_OOB)
  1224. space += 1024;
  1225. if ((atomic && resid > so->so_snd.sb_hiwat) ||
  1226. clen > so->so_snd.sb_hiwat) {
  1227. SOCKBUF_UNLOCK(&so->so_snd);
  1228. error = EMSGSIZE;
  1229. goto release;
  1230. }
  1231. if (space < resid + clen &&
  1232. (atomic || space < so->so_snd.sb_lowat || space < clen)) {
  1233. if ((so->so_state & SS_NBIO) || (flags & MSG_NBIO)) {
  1234. if (so->so_upcallprep.soup_send) {
  1235. so->so_upcallprep.soup_send(so,
  1236. so->so_upcallprep.soup_send_arg,
  1237. resid);
  1238. }
  1239. SOCKBUF_UNLOCK(&so->so_snd);
  1240. error = EWOULDBLOCK;
  1241. goto release;
  1242. }
  1243. error = sbwait(&so->so_snd);
  1244. SOCKBUF_UNLOCK(&so->so_snd);
  1245. if (error)
  1246. goto release;
  1247. goto restart;
  1248. }
  1249. SOCKBUF_UNLOCK(&so->so_snd);
  1250. space -= clen;
  1251. do {
  1252. if (uio == NULL) {
  1253. resid = 0;
  1254. if (flags & MSG_EOR)
  1255. top->m_flags |= M_EOR;
  1256. } else {
  1257. #ifdef ZERO_COPY_SOCKETS
  1258. error = sosend_copyin(uio, &top, atomic,
  1259. &space, flags);
  1260. if (error != 0)
  1261. goto release;
  1262. #else
  1263. /*
  1264. * Copy the data from userland into a mbuf
  1265. * chain. If no data is to be copied in,
  1266. * a single empty mbuf is returned.
  1267. */
  1268. top = m_uiotombuf(uio, M_WAITOK, space,
  1269. (atomic ? max_hdr : 0),
  1270. (atomic ? M_PKTHDR : 0) |
  1271. ((flags & MSG_EOR) ? M_EOR : 0));
  1272. if (top == NULL) {
  1273. error = EFAULT; /* only possible error */
  1274. goto release;
  1275. }
  1276. space -= resid - uio->uio_resid;
  1277. #endif
  1278. resid = uio->uio_resid;
  1279. }
  1280. if (dontroute) {
  1281. SOCK_LOCK(so);
  1282. so->so_options |= SO_DONTROUTE;
  1283. SOCK_UNLOCK(so);
  1284. }
  1285. /*
  1286. * XXX all the SBS_CANTSENDMORE checks previously
  1287. * done could be out of date. We could have recieved
  1288. * a reset packet in an interrupt or maybe we slept
  1289. * while doing page faults in uiomove() etc. We
  1290. * could probably recheck again inside the locking
  1291. * protection here, but there are probably other
  1292. * places that this also happens. We must rethink
  1293. * this.
  1294. */
  1295. VNET_SO_ASSERT(so);
  1296. error = (*so->so_proto->pr_usrreqs->pru_send)(so,
  1297. (flags & MSG_OOB) ? PRUS_OOB :
  1298. /*
  1299. * If the user set MSG_EOF, the protocol understands
  1300. * this flag and nothing left to send then use
  1301. * PRU_SEND_EOF instead of PRU_SEND.
  1302. */
  1303. ((flags & MSG_EOF) &&
  1304. (so->so_proto->pr_flags & PR_IMPLOPCL) &&
  1305. (resid <= 0)) ?
  1306. PRUS_EOF :
  1307. /* If there is more to send set PRUS_MORETOCOME. */
  1308. (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
  1309. top, addr, control, td);
  1310. if (dontroute) {
  1311. SOCK_LOCK(so);
  1312. so->so_options &= ~SO_DONTROUTE;
  1313. SOCK_UNLOCK(so);
  1314. }
  1315. clen = 0;
  1316. control = NULL;
  1317. top = NULL;
  1318. if (error)
  1319. goto release;
  1320. } while (resid && space > 0);
  1321. } while (resid);
  1322. release:
  1323. sbunlock(&so->so_snd);
  1324. out:
  1325. if (top != NULL)
  1326. m_freem(top);
  1327. if (control != NULL)
  1328. m_freem(control);
  1329. return (error);
  1330. }
  1331. int
  1332. sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
  1333. struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
  1334. {
  1335. int error;
  1336. CURVNET_SET(so->so_vnet);
  1337. error = so->so_proto->pr_usrreqs->pru_sosend(so, addr, uio, top,
  1338. control, flags, td);
  1339. CURVNET_RESTORE();
  1340. return (error);
  1341. }
  1342. /*
  1343. * The part of soreceive() that implements reading non-inline out-of-band
  1344. * data from a socket. For more complete comments, see soreceive(), from
  1345. * which this code originated.
  1346. *
  1347. * Note that soreceive_rcvoob(), unlike the remainder of soreceive(), is
  1348. * unable to return an mbuf chain to the caller.
  1349. */
  1350. static int
  1351. soreceive_rcvoob(struct socket *so, struct uio *uio, int flags)
  1352. {
  1353. struct protosw *pr = so->so_proto;
  1354. struct mbuf *m;
  1355. int error;
  1356. KASSERT(flags & MSG_OOB, ("soreceive_rcvoob: (flags & MSG_OOB) == 0"));
  1357. VNET_SO_ASSERT(so);
  1358. m = m_get(M_WAIT, MT_DATA);
  1359. error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
  1360. if (error)
  1361. goto bad;
  1362. do {
  1363. #ifdef ZERO_COPY_SOCKETS
  1364. if (so_zero_copy_receive) {
  1365. int disposable;
  1366. if ((m->m_flags & M_EXT)
  1367. && (m->m_ext.ext_type == EXT_DISPOSABLE))
  1368. disposable = 1;
  1369. else
  1370. disposable = 0;
  1371. error = uiomoveco(mtod(m, void *),
  1372. min(uio->uio_resid, m->m_len),
  1373. uio, disposable);
  1374. } else
  1375. #endif /* ZERO_COPY_SOCKETS */
  1376. error = uiomove(mtod(m, void *),
  1377. (int) min(uio->uio_resid, m->m_len), uio);
  1378. m = m_free(m);
  1379. } while (uio->uio_resid && error == 0 && m);
  1380. bad:
  1381. if (m != NULL)
  1382. m_freem(m);
  1383. return (error);
  1384. }
  1385. /*
  1386. * Following replacement or removal of the first mbuf on the first mbuf chain
  1387. * of a socket buffer, push necessary state changes back into the socket
  1388. * buffer so that other consumers see the values consistently. 'nextrecord'
  1389. * is the callers locally stored value of the original value of
  1390. * sb->sb_mb->m_nextpkt which must be restored when the lead mbuf changes.
  1391. * NOTE: 'nextrecord' may be NULL.
  1392. */
  1393. static __inline void
  1394. sockbuf_pushsync(struct sockbuf *sb, struct mbuf *nextrecord)
  1395. {
  1396. SOCKBUF_LOCK_ASSERT(sb);
  1397. /*
  1398. * First, update for the new value of nextrecord. If necessary, make
  1399. * it the first record.
  1400. */
  1401. if (sb->sb_mb != NULL)
  1402. sb->sb_mb->m_nextpkt = nextrecord;
  1403. else
  1404. sb->sb_mb = nextrecord;
  1405. /*
  1406. * Now update any dependent socket buffer fields to reflect the new
  1407. * state. This is an expanded inline of SB_EMPTY_FIXUP(), with the
  1408. * addition of a second clause that takes care of the case where
  1409. * sb_mb has been updated, but remains the last record.
  1410. */
  1411. if (sb->sb_mb == NULL) {
  1412. sb->sb_mbtail = NULL;
  1413. sb->sb_lastrecord = NULL;
  1414. } else if (sb->sb_mb->m_nextpkt == NULL)
  1415. sb->sb_lastrecord = sb->sb_mb;
  1416. }
  1417. /*
  1418. * Implement receive operations on a socket. We depend on the way that
  1419. * records are added to the sockbuf by sbappend. In particular, each record
  1420. * (mbufs linked through m_next) must begin with an address if the protocol
  1421. * so specifies, followed by an optional mbuf or mbufs containing ancillary
  1422. * data, and then zero or more mbufs of data. In order to allow parallelism
  1423. * between network receive and copying to user space, as well as avoid
  1424. * sleeping with a mutex held, we release the socket buffer mutex during the
  1425. * user space copy. Although the sockbuf is locked, new data may still be
  1426. * appended, and thus we must maintain consistency of the sockbuf during that
  1427. * time.
  1428. *
  1429. * The caller may receive the data as a single mbuf chain by supplying an
  1430. * mbuf **mp0 for use in returning the chain. The uio is then used only for
  1431. * the count in uio_resid.
  1432. */
  1433. int
  1434. soreceive_generic(struct socket *so, struct sockaddr **psa, struct uio *uio,
  1435. struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
  1436. {
  1437. struct mbuf *m, **mp;
  1438. int flags, error, offset;
  1439. ssize_t len;
  1440. struct protosw *pr = so->so_proto;
  1441. struct mbuf *nextrecord;
  1442. int moff, type = 0, last_m_flags, hole_break = 0;
  1443. ssize_t orig_resid = uio->uio_resid;
  1444. mp = mp0;
  1445. if (psa != NULL)
  1446. *psa = NULL;
  1447. if (controlp != NULL)
  1448. *controlp = NULL;
  1449. if (flagsp != NULL) {
  1450. hole_break = *flagsp & MSG_HOLE_BREAK;
  1451. *flagsp &= ~MSG_HOLE_BREAK;
  1452. flags = *flagsp &~ MSG_EOR;
  1453. } else
  1454. flags = 0;
  1455. if (flags & MSG_OOB)
  1456. return (soreceive_rcvoob(so, uio, flags));
  1457. if (mp != NULL)
  1458. *mp = NULL;
  1459. if ((pr->pr_flags & PR_WANTRCVD) && (so->so_state & SS_ISCONFIRMING)
  1460. && uio->uio_resid) {
  1461. VNET_SO_ASSERT(so);
  1462. (*pr->pr_usrreqs->pru_rcvd)(so, 0);
  1463. }
  1464. error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
  1465. if (error)
  1466. return (error);
  1467. restart:
  1468. SOCKBUF_LOCK(&so->so_rcv);
  1469. m = so->so_rcv.sb_mb;
  1470. /*
  1471. * If we have less data than requested, block awaiting more (subject
  1472. * to any timeout) if:
  1473. * 1. the current count is less than the low water mark, or
  1474. * 2. MSG_WAITALL is set, and it is possible to do the entire
  1475. * receive operation at once if we block (resid <= hiwat).
  1476. * 3. MSG_DONTWAIT is not set
  1477. * If MSG_WAITALL is set but resid is larger than the receive buffer,
  1478. * we have to do the receive in sections, and thus risk returning a
  1479. * short count if a timeout or signal occurs after we start.
  1480. */
  1481. if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
  1482. so->so_rcv.sb_cc < uio->uio_resid) &&
  1483. (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
  1484. ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
  1485. m->m_nextpkt == NULL && (pr->pr_flags & PR_ATOMIC) == 0)) {
  1486. KASSERT(m != NULL || !so->so_rcv.sb_cc,
  1487. ("receive: m == %p so->so_rcv.sb_cc == %u",
  1488. m, so->so_rcv.sb_cc));
  1489. if (so->so_error) {
  1490. if (m != NULL)
  1491. goto dontblock;
  1492. error = so->so_error;
  1493. if ((flags & MSG_PEEK) == 0)
  1494. so->so_error = 0;
  1495. SOCKBUF_UNLOCK(&so->so_rcv);
  1496. goto release;
  1497. }
  1498. SOCKBUF_LOCK_ASSERT(&so->so_rcv);
  1499. if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
  1500. if (m == NULL) {
  1501. SOCKBUF_UNLOCK(&so->so_rcv);
  1502. goto release;
  1503. } else
  1504. goto dontblock;
  1505. }
  1506. for (; m != NULL; m = m->m_next)
  1507. if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
  1508. m = so->so_rcv.sb_mb;
  1509. goto dontblock;
  1510. }
  1511. if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
  1512. (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
  1513. SOCKBUF_UNLOCK(&so->so_rcv);
  1514. error = ENOTCONN;
  1515. goto release;
  1516. }
  1517. if (uio->uio_resid == 0) {
  1518. SOCKBUF_UNLOCK(&so->so_rcv);
  1519. goto release;
  1520. }
  1521. if ((so->so_state & SS_NBIO) ||
  1522. (flags & (MSG_DONTWAIT|MSG_NBIO))) {
  1523. if (so->so_upcallprep.soup_receive != NULL) {
  1524. so->so_upcallprep.soup_receive(so,
  1525. so->so_upcallprep.soup_receive_arg,
  1526. orig_resid - uio->uio_resid, uio->uio_resid);
  1527. }
  1528. SOCKBUF_UNLOCK(&so->so_rcv);
  1529. error = EWOULDBLOCK;
  1530. goto release;
  1531. }
  1532. SBLASTRECORDCHK(&so->so_rcv);
  1533. SBLASTMBUFCHK(&so->so_rcv);
  1534. error = sbwait(&so->so_rcv);
  1535. SOCKBUF_UNLOCK(&so->so_rcv);
  1536. if (error)
  1537. goto release;
  1538. goto restart;
  1539. }
  1540. dontblock:
  1541. /*
  1542. * From this point onward, we maintain 'nextrecord' as a cache of the
  1543. * pointer to the next record in the socket buffer. We must keep the
  1544. * various socket buffer pointers and local stack versions of the
  1545. * pointers in sync, pushing out modifications before dropping the
  1546. * socket buffer mutex, and re-reading them when picking it up.
  1547. *
  1548. * Otherwise, we will race with the network stack appending new data
  1549. * or records onto the socket buffer by using inconsistent/stale
  1550. * versions of the field, possibly resulting in socket buffer
  1551. * corruption.
  1552. *
  1553. * By holding the high-level sblock(), we prevent simultaneous
  1554. * readers from pulling off the front of the socket buffer.
  1555. */
  1556. SOCKBUF_LOCK_ASSERT(&so->so_rcv);
  1557. if (uio->u

Large files files are truncated, but you can click here to view the full file