PageRenderTime 61ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/kern/uipc_socket.c

https://bitbucket.org/brucec/sctpdrv
C | 3490 lines | 2503 code | 328 blank | 659 comment | 708 complexity | 837653b306623c240174d108dff4766b MD5 | raw file

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

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