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