xref: /freebsd/sys/dev/cxgbe/tom/t4_ddp.c (revision cdc58367265a2bd6e8f913db2bdc591699ee229f)
1 /*-
2  * Copyright (c) 2012 Chelsio Communications, Inc.
3  * All rights reserved.
4  * Written by: Navdeep Parhar <np@FreeBSD.org>
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include "opt_inet.h"
32 
33 #include <sys/param.h>
34 #include <sys/types.h>
35 #include <sys/systm.h>
36 #include <sys/kernel.h>
37 #include <sys/ktr.h>
38 #include <sys/module.h>
39 #include <sys/protosw.h>
40 #include <sys/proc.h>
41 #include <sys/domain.h>
42 #include <sys/socket.h>
43 #include <sys/socketvar.h>
44 #include <sys/uio.h>
45 #include <netinet/in.h>
46 #include <netinet/in_pcb.h>
47 #include <netinet/ip.h>
48 #include <netinet/tcp_var.h>
49 #define TCPSTATES
50 #include <netinet/tcp_fsm.h>
51 #include <netinet/toecore.h>
52 
53 #include <vm/vm.h>
54 #include <vm/vm_extern.h>
55 #include <vm/vm_param.h>
56 #include <vm/pmap.h>
57 #include <vm/vm_map.h>
58 #include <vm/vm_page.h>
59 #include <vm/vm_object.h>
60 
61 #ifdef TCP_OFFLOAD
62 #include "common/common.h"
63 #include "common/t4_msg.h"
64 #include "common/t4_regs.h"
65 #include "common/t4_tcb.h"
66 #include "tom/t4_tom.h"
67 
68 VNET_DECLARE(int, tcp_do_autorcvbuf);
69 #define V_tcp_do_autorcvbuf VNET(tcp_do_autorcvbuf)
70 VNET_DECLARE(int, tcp_autorcvbuf_inc);
71 #define V_tcp_autorcvbuf_inc VNET(tcp_autorcvbuf_inc)
72 VNET_DECLARE(int, tcp_autorcvbuf_max);
73 #define V_tcp_autorcvbuf_max VNET(tcp_autorcvbuf_max)
74 
75 static struct mbuf *get_ddp_mbuf(int len);
76 
77 #define PPOD_SZ(n)	((n) * sizeof(struct pagepod))
78 #define PPOD_SIZE	(PPOD_SZ(1))
79 
80 /* XXX: must match A_ULP_RX_TDDP_PSZ */
81 static int t4_ddp_pgsz[] = {4096, 4096 << 2, 4096 << 4, 4096 << 6};
82 
83 #if 0
84 static void
85 t4_dump_tcb(struct adapter *sc, int tid)
86 {
87 	uint32_t tcb_base, off, i, j;
88 
89 	/* Dump TCB for the tid */
90 	tcb_base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
91 	t4_write_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2),
92 	    tcb_base + tid * TCB_SIZE);
93 	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2));
94 	off = 0;
95 	printf("\n");
96 	for (i = 0; i < 4; i++) {
97 		uint32_t buf[8];
98 		for (j = 0; j < 8; j++, off += 4)
99 			buf[j] = htonl(t4_read_reg(sc, MEMWIN2_BASE + off));
100 
101 		printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
102 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
103 		    buf[7]);
104 	}
105 }
106 #endif
107 
108 #define MAX_DDP_BUFFER_SIZE		(M_TCB_RX_DDP_BUF0_LEN)
109 static int
110 alloc_ppods(struct tom_data *td, int n, u_int *ppod_addr)
111 {
112 	vmem_addr_t v;
113 	int rc;
114 
115 	MPASS(n > 0);
116 
117 	rc = vmem_alloc(td->ppod_arena, PPOD_SZ(n), M_NOWAIT | M_FIRSTFIT, &v);
118 	*ppod_addr = (u_int)v;
119 
120 	return (rc);
121 }
122 
123 static void
124 free_ppods(struct tom_data *td, u_int ppod_addr, int n)
125 {
126 
127 	MPASS(n > 0);
128 
129 	vmem_free(td->ppod_arena, (vmem_addr_t)ppod_addr, PPOD_SZ(n));
130 }
131 
132 static inline int
133 pages_to_nppods(int npages, int ddp_pgsz)
134 {
135 	int nsegs = npages * PAGE_SIZE / ddp_pgsz;
136 
137 	return (howmany(nsegs, PPOD_PAGES));
138 }
139 
140 static void
141 free_ddp_buffer(struct tom_data *td, struct ddp_buffer *db)
142 {
143 
144 	if (db == NULL)
145 		return;
146 
147 	if (db->pages)
148 		free(db->pages, M_CXGBE);
149 
150 	if (db->nppods > 0)
151 		free_ppods(td, db->ppod_addr, db->nppods);
152 
153 	free(db, M_CXGBE);
154 }
155 
156 void
157 release_ddp_resources(struct toepcb *toep)
158 {
159 	int i;
160 
161 	for (i = 0; i < nitems(toep->db); i++) {
162 		if (toep->db[i] != NULL) {
163 			free_ddp_buffer(toep->td, toep->db[i]);
164 			toep->db[i] = NULL;
165 		}
166 	}
167 }
168 
169 /* XXX: handle_ddp_data code duplication */
170 void
171 insert_ddp_data(struct toepcb *toep, uint32_t n)
172 {
173 	struct inpcb *inp = toep->inp;
174 	struct tcpcb *tp = intotcpcb(inp);
175 	struct sockbuf *sb = &inp->inp_socket->so_rcv;
176 	struct mbuf *m;
177 
178 	INP_WLOCK_ASSERT(inp);
179 	SOCKBUF_LOCK_ASSERT(sb);
180 
181 	m = get_ddp_mbuf(n);
182 	tp->rcv_nxt += n;
183 #ifndef USE_DDP_RX_FLOW_CONTROL
184 	KASSERT(tp->rcv_wnd >= n, ("%s: negative window size", __func__));
185 	tp->rcv_wnd -= n;
186 #endif
187 
188 	KASSERT(toep->sb_cc >= sbused(sb),
189 	    ("%s: sb %p has more data (%d) than last time (%d).",
190 	    __func__, sb, sbused(sb), toep->sb_cc));
191 	toep->rx_credits += toep->sb_cc - sbused(sb);
192 #ifdef USE_DDP_RX_FLOW_CONTROL
193 	toep->rx_credits -= n;	/* adjust for F_RX_FC_DDP */
194 #endif
195 	sbappendstream_locked(sb, m, 0);
196 	toep->sb_cc = sbused(sb);
197 }
198 
199 /* SET_TCB_FIELD sent as a ULP command looks like this */
200 #define LEN__SET_TCB_FIELD_ULP (sizeof(struct ulp_txpkt) + \
201     sizeof(struct ulptx_idata) + sizeof(struct cpl_set_tcb_field_core))
202 
203 /* RX_DATA_ACK sent as a ULP command looks like this */
204 #define LEN__RX_DATA_ACK_ULP (sizeof(struct ulp_txpkt) + \
205     sizeof(struct ulptx_idata) + sizeof(struct cpl_rx_data_ack_core))
206 
207 static inline void *
208 mk_set_tcb_field_ulp(struct ulp_txpkt *ulpmc, struct toepcb *toep,
209     uint64_t word, uint64_t mask, uint64_t val)
210 {
211 	struct ulptx_idata *ulpsc;
212 	struct cpl_set_tcb_field_core *req;
213 
214 	ulpmc->cmd_dest = htonl(V_ULPTX_CMD(ULP_TX_PKT) | V_ULP_TXPKT_DEST(0));
215 	ulpmc->len = htobe32(howmany(LEN__SET_TCB_FIELD_ULP, 16));
216 
217 	ulpsc = (struct ulptx_idata *)(ulpmc + 1);
218 	ulpsc->cmd_more = htobe32(V_ULPTX_CMD(ULP_TX_SC_IMM));
219 	ulpsc->len = htobe32(sizeof(*req));
220 
221 	req = (struct cpl_set_tcb_field_core *)(ulpsc + 1);
222 	OPCODE_TID(req) = htobe32(MK_OPCODE_TID(CPL_SET_TCB_FIELD, toep->tid));
223 	req->reply_ctrl = htobe16(V_NO_REPLY(1) |
224 	    V_QUEUENO(toep->ofld_rxq->iq.abs_id));
225 	req->word_cookie = htobe16(V_WORD(word) | V_COOKIE(0));
226         req->mask = htobe64(mask);
227         req->val = htobe64(val);
228 
229 	ulpsc = (struct ulptx_idata *)(req + 1);
230 	if (LEN__SET_TCB_FIELD_ULP % 16) {
231 		ulpsc->cmd_more = htobe32(V_ULPTX_CMD(ULP_TX_SC_NOOP));
232 		ulpsc->len = htobe32(0);
233 		return (ulpsc + 1);
234 	}
235 	return (ulpsc);
236 }
237 
238 static inline void *
239 mk_rx_data_ack_ulp(struct ulp_txpkt *ulpmc, struct toepcb *toep)
240 {
241 	struct ulptx_idata *ulpsc;
242 	struct cpl_rx_data_ack_core *req;
243 
244 	ulpmc->cmd_dest = htonl(V_ULPTX_CMD(ULP_TX_PKT) | V_ULP_TXPKT_DEST(0));
245 	ulpmc->len = htobe32(howmany(LEN__RX_DATA_ACK_ULP, 16));
246 
247 	ulpsc = (struct ulptx_idata *)(ulpmc + 1);
248 	ulpsc->cmd_more = htobe32(V_ULPTX_CMD(ULP_TX_SC_IMM));
249 	ulpsc->len = htobe32(sizeof(*req));
250 
251 	req = (struct cpl_rx_data_ack_core *)(ulpsc + 1);
252 	OPCODE_TID(req) = htobe32(MK_OPCODE_TID(CPL_RX_DATA_ACK, toep->tid));
253 	req->credit_dack = htobe32(F_RX_MODULATE_RX);
254 
255 	ulpsc = (struct ulptx_idata *)(req + 1);
256 	if (LEN__RX_DATA_ACK_ULP % 16) {
257 		ulpsc->cmd_more = htobe32(V_ULPTX_CMD(ULP_TX_SC_NOOP));
258 		ulpsc->len = htobe32(0);
259 		return (ulpsc + 1);
260 	}
261 	return (ulpsc);
262 }
263 
264 static inline uint64_t
265 select_ddp_flags(struct socket *so, int flags, int db_idx)
266 {
267 	uint64_t ddp_flags = V_TF_DDP_INDICATE_OUT(0);
268 	int waitall = flags & MSG_WAITALL;
269 	int nb = so->so_state & SS_NBIO || flags & (MSG_DONTWAIT | MSG_NBIO);
270 
271 	KASSERT(db_idx == 0 || db_idx == 1,
272 	    ("%s: bad DDP buffer index %d", __func__, db_idx));
273 
274 	if (db_idx == 0) {
275 		ddp_flags |= V_TF_DDP_BUF0_VALID(1) | V_TF_DDP_ACTIVE_BUF(0);
276 		if (waitall)
277 			ddp_flags |= V_TF_DDP_PUSH_DISABLE_0(1);
278 		else if (nb)
279 			ddp_flags |= V_TF_DDP_BUF0_FLUSH(1);
280 		else
281 			ddp_flags |= V_TF_DDP_BUF0_FLUSH(0);
282 	} else {
283 		ddp_flags |= V_TF_DDP_BUF1_VALID(1) | V_TF_DDP_ACTIVE_BUF(1);
284 		if (waitall)
285 			ddp_flags |= V_TF_DDP_PUSH_DISABLE_1(1);
286 		else if (nb)
287 			ddp_flags |= V_TF_DDP_BUF1_FLUSH(1);
288 		else
289 			ddp_flags |= V_TF_DDP_BUF1_FLUSH(0);
290 	}
291 
292 	return (ddp_flags);
293 }
294 
295 static struct wrqe *
296 mk_update_tcb_for_ddp(struct adapter *sc, struct toepcb *toep, int db_idx,
297     int offset, uint64_t ddp_flags)
298 {
299 	struct ddp_buffer *db = toep->db[db_idx];
300 	struct wrqe *wr;
301 	struct work_request_hdr *wrh;
302 	struct ulp_txpkt *ulpmc;
303 	int len;
304 
305 	KASSERT(db_idx == 0 || db_idx == 1,
306 	    ("%s: bad DDP buffer index %d", __func__, db_idx));
307 
308 	/*
309 	 * We'll send a compound work request that has 3 SET_TCB_FIELDs and an
310 	 * RX_DATA_ACK (with RX_MODULATE to speed up delivery).
311 	 *
312 	 * The work request header is 16B and always ends at a 16B boundary.
313 	 * The ULPTX master commands that follow must all end at 16B boundaries
314 	 * too so we round up the size to 16.
315 	 */
316 	len = sizeof(*wrh) + 3 * roundup2(LEN__SET_TCB_FIELD_ULP, 16) +
317 	    roundup2(LEN__RX_DATA_ACK_ULP, 16);
318 
319 	wr = alloc_wrqe(len, toep->ctrlq);
320 	if (wr == NULL)
321 		return (NULL);
322 	wrh = wrtod(wr);
323 	INIT_ULPTX_WRH(wrh, len, 1, 0);	/* atomic */
324 	ulpmc = (struct ulp_txpkt *)(wrh + 1);
325 
326 	/* Write the buffer's tag */
327 	ulpmc = mk_set_tcb_field_ulp(ulpmc, toep,
328 	    W_TCB_RX_DDP_BUF0_TAG + db_idx,
329 	    V_TCB_RX_DDP_BUF0_TAG(M_TCB_RX_DDP_BUF0_TAG),
330 	    V_TCB_RX_DDP_BUF0_TAG(db->tag));
331 
332 	/* Update the current offset in the DDP buffer and its total length */
333 	if (db_idx == 0)
334 		ulpmc = mk_set_tcb_field_ulp(ulpmc, toep,
335 		    W_TCB_RX_DDP_BUF0_OFFSET,
336 		    V_TCB_RX_DDP_BUF0_OFFSET(M_TCB_RX_DDP_BUF0_OFFSET) |
337 		    V_TCB_RX_DDP_BUF0_LEN(M_TCB_RX_DDP_BUF0_LEN),
338 		    V_TCB_RX_DDP_BUF0_OFFSET(offset) |
339 		    V_TCB_RX_DDP_BUF0_LEN(db->len));
340 	else
341 		ulpmc = mk_set_tcb_field_ulp(ulpmc, toep,
342 		    W_TCB_RX_DDP_BUF1_OFFSET,
343 		    V_TCB_RX_DDP_BUF1_OFFSET(M_TCB_RX_DDP_BUF1_OFFSET) |
344 		    V_TCB_RX_DDP_BUF1_LEN((u64)M_TCB_RX_DDP_BUF1_LEN << 32),
345 		    V_TCB_RX_DDP_BUF1_OFFSET(offset) |
346 		    V_TCB_RX_DDP_BUF1_LEN((u64)db->len << 32));
347 
348 	/* Update DDP flags */
349 	ulpmc = mk_set_tcb_field_ulp(ulpmc, toep, W_TCB_RX_DDP_FLAGS,
350 	    V_TF_DDP_BUF0_FLUSH(1) | V_TF_DDP_BUF1_FLUSH(1) |
351 	    V_TF_DDP_PUSH_DISABLE_0(1) | V_TF_DDP_PUSH_DISABLE_1(1) |
352 	    V_TF_DDP_BUF0_VALID(1) | V_TF_DDP_BUF1_VALID(1) |
353 	    V_TF_DDP_ACTIVE_BUF(1) | V_TF_DDP_INDICATE_OUT(1), ddp_flags);
354 
355 	/* Gratuitous RX_DATA_ACK with RX_MODULATE set to speed up delivery. */
356 	ulpmc = mk_rx_data_ack_ulp(ulpmc, toep);
357 
358 	return (wr);
359 }
360 
361 static void
362 discourage_ddp(struct toepcb *toep)
363 {
364 
365 	if (toep->ddp_score && --toep->ddp_score == 0) {
366 		toep->ddp_flags &= ~DDP_OK;
367 		toep->ddp_disabled = time_uptime;
368 		CTR3(KTR_CXGBE, "%s: tid %u !DDP_OK @ %u",
369 		    __func__, toep->tid, time_uptime);
370 	}
371 }
372 
373 static int
374 handle_ddp_data(struct toepcb *toep, __be32 ddp_report, __be32 rcv_nxt, int len)
375 {
376 	uint32_t report = be32toh(ddp_report);
377 	unsigned int db_flag;
378 	struct inpcb *inp = toep->inp;
379 	struct tcpcb *tp;
380 	struct socket *so;
381 	struct sockbuf *sb;
382 	struct mbuf *m;
383 
384 	db_flag = report & F_DDP_BUF_IDX ? DDP_BUF1_ACTIVE : DDP_BUF0_ACTIVE;
385 
386 	if (__predict_false(!(report & F_DDP_INV)))
387 		CXGBE_UNIMPLEMENTED("DDP buffer still valid");
388 
389 	INP_WLOCK(inp);
390 	so = inp_inpcbtosocket(inp);
391 	sb = &so->so_rcv;
392 	if (__predict_false(inp->inp_flags & (INP_DROPPED | INP_TIMEWAIT))) {
393 
394 		/*
395 		 * XXX: think a bit more.
396 		 * tcpcb probably gone, but socket should still be around
397 		 * because we always wait for DDP completion in soreceive no
398 		 * matter what.  Just wake it up and let it clean up.
399 		 */
400 
401 		CTR5(KTR_CXGBE, "%s: tid %u, seq 0x%x, len %d, inp_flags 0x%x",
402 		    __func__, toep->tid, be32toh(rcv_nxt), len, inp->inp_flags);
403 		SOCKBUF_LOCK(sb);
404 		goto wakeup;
405 	}
406 
407 	tp = intotcpcb(inp);
408 	len += be32toh(rcv_nxt) - tp->rcv_nxt;
409 	tp->rcv_nxt += len;
410 	tp->t_rcvtime = ticks;
411 #ifndef USE_DDP_RX_FLOW_CONTROL
412 	KASSERT(tp->rcv_wnd >= len, ("%s: negative window size", __func__));
413 	tp->rcv_wnd -= len;
414 #endif
415 	m = get_ddp_mbuf(len);
416 
417 	SOCKBUF_LOCK(sb);
418 	if (report & F_DDP_BUF_COMPLETE)
419 		toep->ddp_score = DDP_HIGH_SCORE;
420 	else
421 		discourage_ddp(toep);
422 
423 	/* receive buffer autosize */
424 	if (sb->sb_flags & SB_AUTOSIZE &&
425 	    V_tcp_do_autorcvbuf &&
426 	    sb->sb_hiwat < V_tcp_autorcvbuf_max &&
427 	    len > (sbspace(sb) / 8 * 7)) {
428 		unsigned int hiwat = sb->sb_hiwat;
429 		unsigned int newsize = min(hiwat + V_tcp_autorcvbuf_inc,
430 		    V_tcp_autorcvbuf_max);
431 
432 		if (!sbreserve_locked(sb, newsize, so, NULL))
433 			sb->sb_flags &= ~SB_AUTOSIZE;
434 		else
435 			toep->rx_credits += newsize - hiwat;
436 	}
437 
438 	KASSERT(toep->sb_cc >= sbused(sb),
439 	    ("%s: sb %p has more data (%d) than last time (%d).",
440 	    __func__, sb, sbused(sb), toep->sb_cc));
441 	toep->rx_credits += toep->sb_cc - sbused(sb);
442 #ifdef USE_DDP_RX_FLOW_CONTROL
443 	toep->rx_credits -= len;	/* adjust for F_RX_FC_DDP */
444 #endif
445 	sbappendstream_locked(sb, m, 0);
446 	toep->sb_cc = sbused(sb);
447 wakeup:
448 	KASSERT(toep->ddp_flags & db_flag,
449 	    ("%s: DDP buffer not active. toep %p, ddp_flags 0x%x, report 0x%x",
450 	    __func__, toep, toep->ddp_flags, report));
451 	toep->ddp_flags &= ~db_flag;
452 	sorwakeup_locked(so);
453 	SOCKBUF_UNLOCK_ASSERT(sb);
454 
455 	INP_WUNLOCK(inp);
456 	return (0);
457 }
458 
459 void
460 handle_ddp_close(struct toepcb *toep, struct tcpcb *tp, struct sockbuf *sb,
461     __be32 rcv_nxt)
462 {
463 	struct mbuf *m;
464 	int len;
465 
466 	SOCKBUF_LOCK_ASSERT(sb);
467 	INP_WLOCK_ASSERT(toep->inp);
468 	len = be32toh(rcv_nxt) - tp->rcv_nxt;
469 
470 	/* Signal handle_ddp() to break out of its sleep loop. */
471 	toep->ddp_flags &= ~(DDP_BUF0_ACTIVE | DDP_BUF1_ACTIVE);
472 	if (len == 0)
473 		return;
474 
475 	tp->rcv_nxt += len;
476 	KASSERT(toep->sb_cc >= sbused(sb),
477 	    ("%s: sb %p has more data (%d) than last time (%d).",
478 	    __func__, sb, sbused(sb), toep->sb_cc));
479 	toep->rx_credits += toep->sb_cc - sbused(sb);
480 #ifdef USE_DDP_RX_FLOW_CONTROL
481 	toep->rx_credits -= len;	/* adjust for F_RX_FC_DDP */
482 #endif
483 
484 	m = get_ddp_mbuf(len);
485 
486 	sbappendstream_locked(sb, m, 0);
487 	toep->sb_cc = sbused(sb);
488 }
489 
490 #define DDP_ERR (F_DDP_PPOD_MISMATCH | F_DDP_LLIMIT_ERR | F_DDP_ULIMIT_ERR |\
491 	 F_DDP_PPOD_PARITY_ERR | F_DDP_PADDING_ERR | F_DDP_OFFSET_ERR |\
492 	 F_DDP_INVALID_TAG | F_DDP_COLOR_ERR | F_DDP_TID_MISMATCH |\
493 	 F_DDP_INVALID_PPOD | F_DDP_HDRCRC_ERR | F_DDP_DATACRC_ERR)
494 
495 static int
496 do_rx_data_ddp(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
497 {
498 	struct adapter *sc = iq->adapter;
499 	const struct cpl_rx_data_ddp *cpl = (const void *)(rss + 1);
500 	unsigned int tid = GET_TID(cpl);
501 	uint32_t vld;
502 	struct toepcb *toep = lookup_tid(sc, tid);
503 	struct tom_data *td = toep->td;
504 
505 	KASSERT(m == NULL, ("%s: wasn't expecting payload", __func__));
506 	KASSERT(toep->tid == tid, ("%s: toep tid/atid mismatch", __func__));
507 	KASSERT(!(toep->flags & TPF_SYNQE),
508 	    ("%s: toep %p claims to be a synq entry", __func__, toep));
509 
510 	vld = be32toh(cpl->ddpvld);
511 	if (__predict_false(vld & DDP_ERR)) {
512 		panic("%s: DDP error 0x%x (tid %d, toep %p)",
513 		    __func__, vld, tid, toep);
514 	}
515 	if (toep->ulp_mode == ULP_MODE_ISCSI) {
516 		m = m_get(M_NOWAIT, MT_DATA);
517 		if (m == NULL)
518 			CXGBE_UNIMPLEMENTED("mbuf alloc failure");
519 		memcpy(mtod(m, unsigned char *), cpl,
520 		    sizeof(struct cpl_rx_data_ddp));
521         	if (!t4_cpl_iscsi_callback(td, toep, m, CPL_RX_DATA_DDP))
522 			return (0);
523 		m_freem(m);
524         }
525 
526 	handle_ddp_data(toep, cpl->u.ddp_report, cpl->seq, be16toh(cpl->len));
527 
528 	return (0);
529 }
530 
531 static int
532 do_rx_ddp_complete(struct sge_iq *iq, const struct rss_header *rss,
533     struct mbuf *m)
534 {
535 	struct adapter *sc = iq->adapter;
536 	const struct cpl_rx_ddp_complete *cpl = (const void *)(rss + 1);
537 	unsigned int tid = GET_TID(cpl);
538 	struct toepcb *toep = lookup_tid(sc, tid);
539 
540 	KASSERT(m == NULL, ("%s: wasn't expecting payload", __func__));
541 	KASSERT(toep->tid == tid, ("%s: toep tid/atid mismatch", __func__));
542 	KASSERT(!(toep->flags & TPF_SYNQE),
543 	    ("%s: toep %p claims to be a synq entry", __func__, toep));
544 
545 	handle_ddp_data(toep, cpl->ddp_report, cpl->rcv_nxt, 0);
546 
547 	return (0);
548 }
549 
550 void
551 enable_ddp(struct adapter *sc, struct toepcb *toep)
552 {
553 
554 	KASSERT((toep->ddp_flags & (DDP_ON | DDP_OK | DDP_SC_REQ)) == DDP_OK,
555 	    ("%s: toep %p has bad ddp_flags 0x%x",
556 	    __func__, toep, toep->ddp_flags));
557 
558 	CTR3(KTR_CXGBE, "%s: tid %u (time %u)",
559 	    __func__, toep->tid, time_uptime);
560 
561 	toep->ddp_flags |= DDP_SC_REQ;
562 	t4_set_tcb_field(sc, toep, 1, W_TCB_RX_DDP_FLAGS,
563 	    V_TF_DDP_OFF(1) | V_TF_DDP_INDICATE_OUT(1) |
564 	    V_TF_DDP_BUF0_INDICATE(1) | V_TF_DDP_BUF1_INDICATE(1) |
565 	    V_TF_DDP_BUF0_VALID(1) | V_TF_DDP_BUF1_VALID(1),
566 	    V_TF_DDP_BUF0_INDICATE(1) | V_TF_DDP_BUF1_INDICATE(1));
567 	t4_set_tcb_field(sc, toep, 1, W_TCB_T_FLAGS,
568 	    V_TF_RCV_COALESCE_ENABLE(1), 0);
569 }
570 
571 static inline void
572 disable_ddp(struct adapter *sc, struct toepcb *toep)
573 {
574 
575 	KASSERT((toep->ddp_flags & (DDP_ON | DDP_SC_REQ)) == DDP_ON,
576 	    ("%s: toep %p has bad ddp_flags 0x%x",
577 	    __func__, toep, toep->ddp_flags));
578 
579 	CTR3(KTR_CXGBE, "%s: tid %u (time %u)",
580 	    __func__, toep->tid, time_uptime);
581 
582 	toep->ddp_flags |= DDP_SC_REQ;
583 	t4_set_tcb_field(sc, toep, 1, W_TCB_T_FLAGS,
584 	    V_TF_RCV_COALESCE_ENABLE(1), V_TF_RCV_COALESCE_ENABLE(1));
585 	t4_set_tcb_field(sc, toep, 1, W_TCB_RX_DDP_FLAGS, V_TF_DDP_OFF(1),
586 	    V_TF_DDP_OFF(1));
587 }
588 
589 static int
590 hold_uio(struct uio *uio, vm_page_t **ppages, int *pnpages)
591 {
592 	struct vm_map *map;
593 	struct iovec *iov;
594 	vm_offset_t start, end;
595 	vm_page_t *pp;
596 	int n;
597 
598 	KASSERT(uio->uio_iovcnt == 1,
599 	    ("%s: uio_iovcnt %d", __func__, uio->uio_iovcnt));
600 	KASSERT(uio->uio_td->td_proc == curproc,
601 	    ("%s: uio proc (%p) is not curproc (%p)",
602 	    __func__, uio->uio_td->td_proc, curproc));
603 
604 	map = &curproc->p_vmspace->vm_map;
605 	iov = &uio->uio_iov[0];
606 	start = trunc_page((uintptr_t)iov->iov_base);
607 	end = round_page((vm_offset_t)iov->iov_base + iov->iov_len);
608 	n = howmany(end - start, PAGE_SIZE);
609 
610 	if (end - start > MAX_DDP_BUFFER_SIZE)
611 		return (E2BIG);
612 
613 	pp = malloc(n * sizeof(vm_page_t), M_CXGBE, M_NOWAIT);
614 	if (pp == NULL)
615 		return (ENOMEM);
616 
617 	if (vm_fault_quick_hold_pages(map, (vm_offset_t)iov->iov_base,
618 	    iov->iov_len, VM_PROT_WRITE, pp, n) < 0) {
619 		free(pp, M_CXGBE);
620 		return (EFAULT);
621 	}
622 
623 	*ppages = pp;
624 	*pnpages = n;
625 
626 	return (0);
627 }
628 
629 static int
630 bufcmp(struct ddp_buffer *db, vm_page_t *pages, int npages, int offset, int len)
631 {
632 	int i;
633 
634 	if (db == NULL || db->npages != npages || db->offset != offset ||
635 	    db->len != len)
636 		return (1);
637 
638 	for (i = 0; i < npages; i++) {
639 		if (pages[i]->phys_addr != db->pages[i]->phys_addr)
640 			return (1);
641 	}
642 
643 	return (0);
644 }
645 
646 static int
647 calculate_hcf(int n1, int n2)
648 {
649 	int a, b, t;
650 
651 	if (n1 <= n2) {
652 		a = n1;
653 		b = n2;
654 	} else {
655 		a = n2;
656 		b = n1;
657 	}
658 
659 	while (a != 0) {
660 		t = a;
661 		a = b % a;
662 		b = t;
663 	}
664 
665 	return (b);
666 }
667 
668 static struct ddp_buffer *
669 alloc_ddp_buffer(struct tom_data *td, vm_page_t *pages, int npages, int offset,
670     int len)
671 {
672 	int i, hcf, seglen, idx, ppod, nppods;
673 	struct ddp_buffer *db;
674 
675 	/*
676 	 * The DDP page size is unrelated to the VM page size.  We combine
677 	 * contiguous physical pages into larger segments to get the best DDP
678 	 * page size possible.  This is the largest of the four sizes in
679 	 * A_ULP_RX_TDDP_PSZ that evenly divides the HCF of the segment sizes in
680 	 * the page list.
681 	 */
682 	hcf = 0;
683 	for (i = 0; i < npages; i++) {
684 		seglen = PAGE_SIZE;
685 		while (i < npages - 1 &&
686 		    pages[i]->phys_addr + PAGE_SIZE == pages[i + 1]->phys_addr) {
687 			seglen += PAGE_SIZE;
688 			i++;
689 		}
690 
691 		hcf = calculate_hcf(hcf, seglen);
692 		if (hcf < t4_ddp_pgsz[1]) {
693 			idx = 0;
694 			goto have_pgsz;	/* give up, short circuit */
695 		}
696 	}
697 
698 	if (hcf % t4_ddp_pgsz[0] != 0) {
699 		/* hmmm.  This could only happen when PAGE_SIZE < 4K */
700 		KASSERT(PAGE_SIZE < 4096,
701 		    ("%s: PAGE_SIZE %d, hcf %d", __func__, PAGE_SIZE, hcf));
702 		CTR3(KTR_CXGBE, "%s: PAGE_SIZE %d, hcf %d",
703 		    __func__, PAGE_SIZE, hcf);
704 		return (NULL);
705 	}
706 
707 	for (idx = nitems(t4_ddp_pgsz) - 1; idx > 0; idx--) {
708 		if (hcf % t4_ddp_pgsz[idx] == 0)
709 			break;
710 	}
711 have_pgsz:
712 	MPASS(idx <= M_PPOD_PGSZ);
713 
714 	db = malloc(sizeof(*db), M_CXGBE, M_NOWAIT);
715 	if (db == NULL) {
716 		CTR1(KTR_CXGBE, "%s: malloc failed.", __func__);
717 		return (NULL);
718 	}
719 
720 	nppods = pages_to_nppods(npages, t4_ddp_pgsz[idx]);
721 	if (alloc_ppods(td, nppods, &db->ppod_addr) != 0) {
722 		free(db, M_CXGBE);
723 		CTR4(KTR_CXGBE, "%s: no pods, nppods %d, resid %d, pgsz %d",
724 		    __func__, nppods, len, t4_ddp_pgsz[idx]);
725 		return (NULL);
726 	}
727 	ppod = (db->ppod_addr - td->ppod_start) / PPOD_SIZE;
728 
729 	db->tag = V_PPOD_PGSZ(idx) | V_PPOD_TAG(ppod);
730 	db->nppods = nppods;
731 	db->npages = npages;
732 	db->pages = pages;
733 	db->offset = offset;
734 	db->len = len;
735 
736 	CTR6(KTR_CXGBE, "New DDP buffer.  "
737 	    "ddp_pgsz %d, ppod 0x%x, npages %d, nppods %d, offset %d, len %d",
738 	    t4_ddp_pgsz[idx], ppod, db->npages, db->nppods, db->offset,
739 	    db->len);
740 
741 	return (db);
742 }
743 
744 #define NUM_ULP_TX_SC_IMM_PPODS (256 / PPOD_SIZE)
745 
746 static int
747 write_page_pods(struct adapter *sc, struct toepcb *toep, struct ddp_buffer *db)
748 {
749 	struct wrqe *wr;
750 	struct ulp_mem_io *ulpmc;
751 	struct ulptx_idata *ulpsc;
752 	struct pagepod *ppod;
753 	int i, j, k, n, chunk, len, ddp_pgsz, idx;
754 	u_int ppod_addr;
755 	uint32_t cmd;
756 
757 	cmd = htobe32(V_ULPTX_CMD(ULP_TX_MEM_WRITE));
758 	if (is_t4(sc))
759 		cmd |= htobe32(F_ULP_MEMIO_ORDER);
760 	else
761 		cmd |= htobe32(F_T5_ULP_MEMIO_IMM);
762 	ddp_pgsz = t4_ddp_pgsz[G_PPOD_PGSZ(db->tag)];
763 	ppod_addr = db->ppod_addr;
764 	for (i = 0; i < db->nppods; ppod_addr += chunk) {
765 
766 		/* How many page pods are we writing in this cycle */
767 		n = min(db->nppods - i, NUM_ULP_TX_SC_IMM_PPODS);
768 		chunk = PPOD_SZ(n);
769 		len = roundup2(sizeof(*ulpmc) + sizeof(*ulpsc) + chunk, 16);
770 
771 		wr = alloc_wrqe(len, toep->ctrlq);
772 		if (wr == NULL)
773 			return (ENOMEM);	/* ok to just bail out */
774 		ulpmc = wrtod(wr);
775 
776 		INIT_ULPTX_WR(ulpmc, len, 0, 0);
777 		ulpmc->cmd = cmd;
778 		ulpmc->dlen = htobe32(V_ULP_MEMIO_DATA_LEN(chunk / 32));
779 		ulpmc->len16 = htobe32(howmany(len - sizeof(ulpmc->wr), 16));
780 		ulpmc->lock_addr = htobe32(V_ULP_MEMIO_ADDR(ppod_addr >> 5));
781 
782 		ulpsc = (struct ulptx_idata *)(ulpmc + 1);
783 		ulpsc->cmd_more = htobe32(V_ULPTX_CMD(ULP_TX_SC_IMM));
784 		ulpsc->len = htobe32(chunk);
785 
786 		ppod = (struct pagepod *)(ulpsc + 1);
787 		for (j = 0; j < n; i++, j++, ppod++) {
788 			ppod->vld_tid_pgsz_tag_color = htobe64(F_PPOD_VALID |
789 			    V_PPOD_TID(toep->tid) | db->tag);
790 			ppod->len_offset = htobe64(V_PPOD_LEN(db->len) |
791 			    V_PPOD_OFST(db->offset));
792 			ppod->rsvd = 0;
793 			idx = i * PPOD_PAGES * (ddp_pgsz / PAGE_SIZE);
794 			for (k = 0; k < nitems(ppod->addr); k++) {
795 				if (idx < db->npages) {
796 					ppod->addr[k] =
797 					    htobe64(db->pages[idx]->phys_addr);
798 					idx += ddp_pgsz / PAGE_SIZE;
799 				} else
800 					ppod->addr[k] = 0;
801 #if 0
802 				CTR5(KTR_CXGBE,
803 				    "%s: tid %d ppod[%d]->addr[%d] = %p",
804 				    __func__, toep->tid, i, k,
805 				    htobe64(ppod->addr[k]));
806 #endif
807 			}
808 
809 		}
810 
811 		t4_wrq_tx(sc, wr);
812 	}
813 
814 	return (0);
815 }
816 
817 /*
818  * Reuse, or allocate (and program the page pods for) a new DDP buffer.  The
819  * "pages" array is handed over to this function and should not be used in any
820  * way by the caller after that.
821  */
822 static int
823 select_ddp_buffer(struct adapter *sc, struct toepcb *toep, vm_page_t *pages,
824     int npages, int db_off, int db_len)
825 {
826 	struct ddp_buffer *db;
827 	struct tom_data *td = sc->tom_softc;
828 	int i, empty_slot = -1;
829 
830 	/* Try to reuse */
831 	for (i = 0; i < nitems(toep->db); i++) {
832 		if (bufcmp(toep->db[i], pages, npages, db_off, db_len) == 0) {
833 			free(pages, M_CXGBE);
834 			return (i);	/* pages still held */
835 		} else if (toep->db[i] == NULL && empty_slot < 0)
836 			empty_slot = i;
837 	}
838 
839 	/* Allocate new buffer, write its page pods. */
840 	db = alloc_ddp_buffer(td, pages, npages, db_off, db_len);
841 	if (db == NULL) {
842 		vm_page_unhold_pages(pages, npages);
843 		free(pages, M_CXGBE);
844 		return (-1);
845 	}
846 	if (write_page_pods(sc, toep, db) != 0) {
847 		vm_page_unhold_pages(pages, npages);
848 		free_ddp_buffer(td, db);
849 		return (-1);
850 	}
851 
852 	i = empty_slot;
853 	if (i < 0) {
854 		i = arc4random() % nitems(toep->db);
855 		free_ddp_buffer(td, toep->db[i]);
856 	}
857 	toep->db[i] = db;
858 
859 	CTR5(KTR_CXGBE, "%s: tid %d, DDP buffer[%d] = %p (tag 0x%x)",
860 	    __func__, toep->tid, i, db, db->tag);
861 
862 	return (i);
863 }
864 
865 static void
866 wire_ddp_buffer(struct ddp_buffer *db)
867 {
868 	int i;
869 	vm_page_t p;
870 
871 	for (i = 0; i < db->npages; i++) {
872 		p = db->pages[i];
873 		vm_page_lock(p);
874 		vm_page_wire(p);
875 		vm_page_unhold(p);
876 		vm_page_unlock(p);
877 	}
878 }
879 
880 static void
881 unwire_ddp_buffer(struct ddp_buffer *db)
882 {
883 	int i;
884 	vm_page_t p;
885 
886 	for (i = 0; i < db->npages; i++) {
887 		p = db->pages[i];
888 		vm_page_lock(p);
889 		vm_page_unwire(p, PQ_INACTIVE);
890 		vm_page_unlock(p);
891 	}
892 }
893 
894 static int
895 handle_ddp(struct socket *so, struct uio *uio, int flags, int error)
896 {
897 	struct sockbuf *sb = &so->so_rcv;
898 	struct tcpcb *tp = so_sototcpcb(so);
899 	struct toepcb *toep = tp->t_toe;
900 	struct adapter *sc = td_adapter(toep->td);
901 	vm_page_t *pages;
902 	int npages, db_idx, rc, buf_flag;
903 	struct ddp_buffer *db;
904 	struct wrqe *wr;
905 	uint64_t ddp_flags;
906 
907 	SOCKBUF_LOCK_ASSERT(sb);
908 
909 #if 0
910 	if (sbused(sb) + sc->tt.ddp_thres > uio->uio_resid) {
911 		CTR4(KTR_CXGBE, "%s: sb_cc %d, threshold %d, resid %d",
912 		    __func__, sbused(sb), sc->tt.ddp_thres, uio->uio_resid);
913 	}
914 #endif
915 
916 	/* XXX: too eager to disable DDP, could handle NBIO better than this. */
917 	if (sbused(sb) >= uio->uio_resid || uio->uio_resid < sc->tt.ddp_thres ||
918 	    uio->uio_resid > MAX_DDP_BUFFER_SIZE || uio->uio_iovcnt > 1 ||
919 	    so->so_state & SS_NBIO || flags & (MSG_DONTWAIT | MSG_NBIO) ||
920 	    error || so->so_error || sb->sb_state & SBS_CANTRCVMORE)
921 		goto no_ddp;
922 
923 	/*
924 	 * Fault in and then hold the pages of the uio buffers.  We'll wire them
925 	 * a bit later if everything else works out.
926 	 */
927 	SOCKBUF_UNLOCK(sb);
928 	if (hold_uio(uio, &pages, &npages) != 0) {
929 		SOCKBUF_LOCK(sb);
930 		goto no_ddp;
931 	}
932 	SOCKBUF_LOCK(sb);
933 	if (__predict_false(so->so_error || sb->sb_state & SBS_CANTRCVMORE)) {
934 		vm_page_unhold_pages(pages, npages);
935 		free(pages, M_CXGBE);
936 		goto no_ddp;
937 	}
938 
939 	/*
940 	 * Figure out which one of the two DDP buffers to use this time.
941 	 */
942 	db_idx = select_ddp_buffer(sc, toep, pages, npages,
943 	    (uintptr_t)uio->uio_iov->iov_base & PAGE_MASK, uio->uio_resid);
944 	pages = NULL;	/* handed off to select_ddp_buffer */
945 	if (db_idx < 0)
946 		goto no_ddp;
947 	db = toep->db[db_idx];
948 	buf_flag = db_idx == 0 ? DDP_BUF0_ACTIVE : DDP_BUF1_ACTIVE;
949 
950 	/*
951 	 * Build the compound work request that tells the chip where to DMA the
952 	 * payload.
953 	 */
954 	ddp_flags = select_ddp_flags(so, flags, db_idx);
955 	wr = mk_update_tcb_for_ddp(sc, toep, db_idx, sbused(sb), ddp_flags);
956 	if (wr == NULL) {
957 		/*
958 		 * Just unhold the pages.  The DDP buffer's software state is
959 		 * left as-is in the toep.  The page pods were written
960 		 * successfully and we may have an opportunity to use it in the
961 		 * future.
962 		 */
963 		vm_page_unhold_pages(db->pages, db->npages);
964 		goto no_ddp;
965 	}
966 
967 	/* Wire (and then unhold) the pages, and give the chip the go-ahead. */
968 	wire_ddp_buffer(db);
969 	t4_wrq_tx(sc, wr);
970 	sb->sb_flags &= ~SB_DDP_INDICATE;
971 	toep->ddp_flags |= buf_flag;
972 
973 	/*
974 	 * Wait for the DDP operation to complete and then unwire the pages.
975 	 * The return code from the sbwait will be the final return code of this
976 	 * function.  But we do need to wait for DDP no matter what.
977 	 */
978 	rc = sbwait(sb);
979 	while (toep->ddp_flags & buf_flag) {
980 		/* XXXGL: shouldn't here be sbwait() call? */
981 		sb->sb_flags |= SB_WAIT;
982 		msleep(&sb->sb_acc, &sb->sb_mtx, PSOCK , "sbwait", 0);
983 	}
984 	unwire_ddp_buffer(db);
985 	return (rc);
986 no_ddp:
987 	disable_ddp(sc, toep);
988 	discourage_ddp(toep);
989 	sb->sb_flags &= ~SB_DDP_INDICATE;
990 	return (0);
991 }
992 
993 void
994 t4_init_ddp(struct adapter *sc, struct tom_data *td)
995 {
996 
997 	td->ppod_start = sc->vres.ddp.start;
998 	td->ppod_arena = vmem_create("DDP page pods", sc->vres.ddp.start,
999 	    sc->vres.ddp.size, 1, 32, M_FIRSTFIT | M_NOWAIT);
1000 
1001 	t4_register_cpl_handler(sc, CPL_RX_DATA_DDP, do_rx_data_ddp);
1002 	t4_register_cpl_handler(sc, CPL_RX_DDP_COMPLETE, do_rx_ddp_complete);
1003 }
1004 
1005 void
1006 t4_uninit_ddp(struct adapter *sc __unused, struct tom_data *td)
1007 {
1008 
1009 	if (td->ppod_arena != NULL) {
1010 		vmem_destroy(td->ppod_arena);
1011 		td->ppod_arena = NULL;
1012 	}
1013 }
1014 
1015 #define	VNET_SO_ASSERT(so)						\
1016 	VNET_ASSERT(curvnet != NULL,					\
1017 	    ("%s:%d curvnet is NULL, so=%p", __func__, __LINE__, (so)));
1018 #define	SBLOCKWAIT(f)	(((f) & MSG_DONTWAIT) ? 0 : SBL_WAIT)
1019 static int
1020 soreceive_rcvoob(struct socket *so, struct uio *uio, int flags)
1021 {
1022 
1023 	CXGBE_UNIMPLEMENTED(__func__);
1024 }
1025 
1026 static char ddp_magic_str[] = "nothing to see here";
1027 
1028 static struct mbuf *
1029 get_ddp_mbuf(int len)
1030 {
1031 	struct mbuf *m;
1032 
1033 	m = m_get(M_NOWAIT, MT_DATA);
1034 	if (m == NULL)
1035 		CXGBE_UNIMPLEMENTED("mbuf alloc failure");
1036 	m->m_len = len;
1037 	m->m_data = &ddp_magic_str[0];
1038 
1039 	return (m);
1040 }
1041 
1042 static inline int
1043 is_ddp_mbuf(struct mbuf *m)
1044 {
1045 
1046 	return (m->m_data == &ddp_magic_str[0]);
1047 }
1048 
1049 /*
1050  * Copy an mbuf chain into a uio limited by len if set.
1051  */
1052 static int
1053 m_mbuftouio_ddp(struct uio *uio, struct mbuf *m, int len)
1054 {
1055 	int error, length, total;
1056 	int progress = 0;
1057 
1058 	if (len > 0)
1059 		total = min(uio->uio_resid, len);
1060 	else
1061 		total = uio->uio_resid;
1062 
1063 	/* Fill the uio with data from the mbufs. */
1064 	for (; m != NULL; m = m->m_next) {
1065 		length = min(m->m_len, total - progress);
1066 
1067 		if (is_ddp_mbuf(m)) {
1068 			enum uio_seg segflag = uio->uio_segflg;
1069 
1070 			uio->uio_segflg	= UIO_NOCOPY;
1071 			error = uiomove(mtod(m, void *), length, uio);
1072 			uio->uio_segflg	= segflag;
1073 		} else
1074 			error = uiomove(mtod(m, void *), length, uio);
1075 		if (error)
1076 			return (error);
1077 
1078 		progress += length;
1079 	}
1080 
1081 	return (0);
1082 }
1083 
1084 /*
1085  * Based on soreceive_stream() in uipc_socket.c
1086  */
1087 int
1088 t4_soreceive_ddp(struct socket *so, struct sockaddr **psa, struct uio *uio,
1089     struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
1090 {
1091 	int len = 0, error = 0, flags, oresid, ddp_handled = 0;
1092 	struct sockbuf *sb;
1093 	struct mbuf *m, *n = NULL;
1094 
1095 	/* We only do stream sockets. */
1096 	if (so->so_type != SOCK_STREAM)
1097 		return (EINVAL);
1098 	if (psa != NULL)
1099 		*psa = NULL;
1100 	if (controlp != NULL)
1101 		return (EINVAL);
1102 	if (flagsp != NULL)
1103 		flags = *flagsp &~ MSG_EOR;
1104 	else
1105 		flags = 0;
1106 	if (flags & MSG_OOB)
1107 		return (soreceive_rcvoob(so, uio, flags));
1108 	if (mp0 != NULL)
1109 		*mp0 = NULL;
1110 
1111 	sb = &so->so_rcv;
1112 
1113 	/* Prevent other readers from entering the socket. */
1114 	error = sblock(sb, SBLOCKWAIT(flags));
1115 	SOCKBUF_LOCK(sb);
1116 	if (error)
1117 		goto out;
1118 
1119 	/* Easy one, no space to copyout anything. */
1120 	if (uio->uio_resid == 0) {
1121 		error = EINVAL;
1122 		goto out;
1123 	}
1124 	oresid = uio->uio_resid;
1125 
1126 	/* We will never ever get anything unless we are or were connected. */
1127 	if (!(so->so_state & (SS_ISCONNECTED|SS_ISDISCONNECTED))) {
1128 		error = ENOTCONN;
1129 		goto out;
1130 	}
1131 
1132 restart:
1133 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1134 
1135 	if (sb->sb_flags & SB_DDP_INDICATE && !ddp_handled) {
1136 
1137 		/* uio should be just as it was at entry */
1138 		KASSERT(oresid == uio->uio_resid,
1139 		    ("%s: oresid = %d, uio_resid = %zd, sbavail = %d",
1140 		    __func__, oresid, uio->uio_resid, sbavail(sb)));
1141 
1142 		error = handle_ddp(so, uio, flags, 0);
1143 		ddp_handled = 1;
1144 		if (error)
1145 			goto out;
1146 	}
1147 
1148 	/* Abort if socket has reported problems. */
1149 	if (so->so_error) {
1150 		if (sbavail(sb))
1151 			goto deliver;
1152 		if (oresid > uio->uio_resid)
1153 			goto out;
1154 		error = so->so_error;
1155 		if (!(flags & MSG_PEEK))
1156 			so->so_error = 0;
1157 		goto out;
1158 	}
1159 
1160 	/* Door is closed.  Deliver what is left, if any. */
1161 	if (sb->sb_state & SBS_CANTRCVMORE) {
1162 		if (sbavail(sb))
1163 			goto deliver;
1164 		else
1165 			goto out;
1166 	}
1167 
1168 	/* Socket buffer is empty and we shall not block. */
1169 	if (sbavail(sb) == 0 &&
1170 	    ((so->so_state & SS_NBIO) || (flags & (MSG_DONTWAIT|MSG_NBIO)))) {
1171 		error = EAGAIN;
1172 		goto out;
1173 	}
1174 
1175 	/* Socket buffer got some data that we shall deliver now. */
1176 	if (sbavail(sb) > 0 && !(flags & MSG_WAITALL) &&
1177 	    ((so->so_state & SS_NBIO) ||
1178 	     (flags & (MSG_DONTWAIT|MSG_NBIO)) ||
1179 	     sbavail(sb) >= sb->sb_lowat ||
1180 	     sbavail(sb) >= uio->uio_resid ||
1181 	     sbavail(sb) >= sb->sb_hiwat) ) {
1182 		goto deliver;
1183 	}
1184 
1185 	/* On MSG_WAITALL we must wait until all data or error arrives. */
1186 	if ((flags & MSG_WAITALL) &&
1187 	    (sbavail(sb) >= uio->uio_resid || sbavail(sb) >= sb->sb_lowat))
1188 		goto deliver;
1189 
1190 	/*
1191 	 * Wait and block until (more) data comes in.
1192 	 * NB: Drops the sockbuf lock during wait.
1193 	 */
1194 	error = sbwait(sb);
1195 	if (error) {
1196 		if (sb->sb_flags & SB_DDP_INDICATE && !ddp_handled) {
1197 			(void) handle_ddp(so, uio, flags, 1);
1198 			ddp_handled = 1;
1199 		}
1200 		goto out;
1201 	}
1202 	goto restart;
1203 
1204 deliver:
1205 	SOCKBUF_LOCK_ASSERT(&so->so_rcv);
1206 	KASSERT(sbavail(sb) > 0, ("%s: sockbuf empty", __func__));
1207 	KASSERT(sb->sb_mb != NULL, ("%s: sb_mb == NULL", __func__));
1208 
1209 	if (sb->sb_flags & SB_DDP_INDICATE && !ddp_handled)
1210 		goto restart;
1211 
1212 	/* Statistics. */
1213 	if (uio->uio_td)
1214 		uio->uio_td->td_ru.ru_msgrcv++;
1215 
1216 	/* Fill uio until full or current end of socket buffer is reached. */
1217 	len = min(uio->uio_resid, sbavail(sb));
1218 	if (mp0 != NULL) {
1219 		/* Dequeue as many mbufs as possible. */
1220 		if (!(flags & MSG_PEEK) && len >= sb->sb_mb->m_len) {
1221 			for (*mp0 = m = sb->sb_mb;
1222 			     m != NULL && m->m_len <= len;
1223 			     m = m->m_next) {
1224 				len -= m->m_len;
1225 				uio->uio_resid -= m->m_len;
1226 				sbfree(sb, m);
1227 				n = m;
1228 			}
1229 			sb->sb_mb = m;
1230 			if (sb->sb_mb == NULL)
1231 				SB_EMPTY_FIXUP(sb);
1232 			n->m_next = NULL;
1233 		}
1234 		/* Copy the remainder. */
1235 		if (len > 0) {
1236 			KASSERT(sb->sb_mb != NULL,
1237 			    ("%s: len > 0 && sb->sb_mb empty", __func__));
1238 
1239 			m = m_copym(sb->sb_mb, 0, len, M_NOWAIT);
1240 			if (m == NULL)
1241 				len = 0;	/* Don't flush data from sockbuf. */
1242 			else
1243 				uio->uio_resid -= m->m_len;
1244 			if (*mp0 != NULL)
1245 				n->m_next = m;
1246 			else
1247 				*mp0 = m;
1248 			if (*mp0 == NULL) {
1249 				error = ENOBUFS;
1250 				goto out;
1251 			}
1252 		}
1253 	} else {
1254 		/* NB: Must unlock socket buffer as uiomove may sleep. */
1255 		SOCKBUF_UNLOCK(sb);
1256 		error = m_mbuftouio_ddp(uio, sb->sb_mb, len);
1257 		SOCKBUF_LOCK(sb);
1258 		if (error)
1259 			goto out;
1260 	}
1261 	SBLASTRECORDCHK(sb);
1262 	SBLASTMBUFCHK(sb);
1263 
1264 	/*
1265 	 * Remove the delivered data from the socket buffer unless we
1266 	 * were only peeking.
1267 	 */
1268 	if (!(flags & MSG_PEEK)) {
1269 		if (len > 0)
1270 			sbdrop_locked(sb, len);
1271 
1272 		/* Notify protocol that we drained some data. */
1273 		if ((so->so_proto->pr_flags & PR_WANTRCVD) &&
1274 		    (((flags & MSG_WAITALL) && uio->uio_resid > 0) ||
1275 		     !(flags & MSG_SOCALLBCK))) {
1276 			SOCKBUF_UNLOCK(sb);
1277 			VNET_SO_ASSERT(so);
1278 			(*so->so_proto->pr_usrreqs->pru_rcvd)(so, flags);
1279 			SOCKBUF_LOCK(sb);
1280 		}
1281 	}
1282 
1283 	/*
1284 	 * For MSG_WAITALL we may have to loop again and wait for
1285 	 * more data to come in.
1286 	 */
1287 	if ((flags & MSG_WAITALL) && uio->uio_resid > 0)
1288 		goto restart;
1289 out:
1290 	SOCKBUF_LOCK_ASSERT(sb);
1291 	SBLASTRECORDCHK(sb);
1292 	SBLASTMBUFCHK(sb);
1293 	SOCKBUF_UNLOCK(sb);
1294 	sbunlock(sb);
1295 	return (error);
1296 }
1297 
1298 #endif
1299