xref: /freebsd/sys/dev/cxgbe/tom/t4_ddp.c (revision ef36b3f75658d201edb495068db5e1be49593de5)
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/aio.h>
35 #include <sys/file.h>
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #include <sys/ktr.h>
39 #include <sys/module.h>
40 #include <sys/protosw.h>
41 #include <sys/proc.h>
42 #include <sys/domain.h>
43 #include <sys/socket.h>
44 #include <sys/socketvar.h>
45 #include <sys/taskqueue.h>
46 #include <sys/uio.h>
47 #include <netinet/in.h>
48 #include <netinet/in_pcb.h>
49 #include <netinet/ip.h>
50 #include <netinet/tcp_var.h>
51 #define TCPSTATES
52 #include <netinet/tcp_fsm.h>
53 #include <netinet/toecore.h>
54 
55 #include <vm/vm.h>
56 #include <vm/vm_extern.h>
57 #include <vm/vm_param.h>
58 #include <vm/pmap.h>
59 #include <vm/vm_map.h>
60 #include <vm/vm_page.h>
61 #include <vm/vm_object.h>
62 
63 #ifdef TCP_OFFLOAD
64 #include "common/common.h"
65 #include "common/t4_msg.h"
66 #include "common/t4_regs.h"
67 #include "common/t4_tcb.h"
68 #include "tom/t4_tom.h"
69 
70 /*
71  * Use the 'backend3' field in AIO jobs to store the amount of data
72  * received by the AIO job so far.
73  */
74 #define	aio_received	backend3
75 
76 static void aio_ddp_requeue_task(void *context, int pending);
77 static void ddp_complete_all(struct toepcb *toep, int error);
78 static void t4_aio_cancel_active(struct kaiocb *job);
79 static void t4_aio_cancel_queued(struct kaiocb *job);
80 
81 static TAILQ_HEAD(, pageset) ddp_orphan_pagesets;
82 static struct mtx ddp_orphan_pagesets_lock;
83 static struct task ddp_orphan_task;
84 
85 #define MAX_DDP_BUFFER_SIZE		(M_TCB_RX_DDP_BUF0_LEN)
86 
87 /*
88  * A page set holds information about a buffer used for DDP.  The page
89  * set holds resources such as the VM pages backing the buffer (either
90  * held or wired) and the page pods associated with the buffer.
91  * Recently used page sets are cached to allow for efficient reuse of
92  * buffers (avoiding the need to re-fault in pages, hold them, etc.).
93  * Note that cached page sets keep the backing pages wired.  The
94  * number of wired pages is capped by only allowing for two wired
95  * pagesets per connection.  This is not a perfect cap, but is a
96  * trade-off for performance.
97  *
98  * If an application ping-pongs two buffers for a connection via
99  * aio_read(2) then those buffers should remain wired and expensive VM
100  * fault lookups should be avoided after each buffer has been used
101  * once.  If an application uses more than two buffers then this will
102  * fall back to doing expensive VM fault lookups for each operation.
103  */
104 static void
105 free_pageset(struct tom_data *td, struct pageset *ps)
106 {
107 	vm_page_t p;
108 	int i;
109 
110 	if (ps->prsv.prsv_nppods > 0)
111 		t4_free_page_pods(&ps->prsv);
112 
113 	if (ps->flags & PS_WIRED) {
114 		for (i = 0; i < ps->npages; i++) {
115 			p = ps->pages[i];
116 			vm_page_lock(p);
117 			vm_page_unwire(p, PQ_INACTIVE);
118 			vm_page_unlock(p);
119 		}
120 	} else
121 		vm_page_unhold_pages(ps->pages, ps->npages);
122 	mtx_lock(&ddp_orphan_pagesets_lock);
123 	TAILQ_INSERT_TAIL(&ddp_orphan_pagesets, ps, link);
124 	taskqueue_enqueue(taskqueue_thread, &ddp_orphan_task);
125 	mtx_unlock(&ddp_orphan_pagesets_lock);
126 }
127 
128 static void
129 ddp_free_orphan_pagesets(void *context, int pending)
130 {
131 	struct pageset *ps;
132 
133 	mtx_lock(&ddp_orphan_pagesets_lock);
134 	while (!TAILQ_EMPTY(&ddp_orphan_pagesets)) {
135 		ps = TAILQ_FIRST(&ddp_orphan_pagesets);
136 		TAILQ_REMOVE(&ddp_orphan_pagesets, ps, link);
137 		mtx_unlock(&ddp_orphan_pagesets_lock);
138 		if (ps->vm)
139 			vmspace_free(ps->vm);
140 		free(ps, M_CXGBE);
141 		mtx_lock(&ddp_orphan_pagesets_lock);
142 	}
143 	mtx_unlock(&ddp_orphan_pagesets_lock);
144 }
145 
146 static void
147 recycle_pageset(struct toepcb *toep, struct pageset *ps)
148 {
149 
150 	DDP_ASSERT_LOCKED(toep);
151 	if (!(toep->ddp_flags & DDP_DEAD) && ps->flags & PS_WIRED) {
152 		KASSERT(toep->ddp_cached_count + toep->ddp_active_count <
153 		    nitems(toep->db), ("too many wired pagesets"));
154 		TAILQ_INSERT_HEAD(&toep->ddp_cached_pagesets, ps, link);
155 		toep->ddp_cached_count++;
156 	} else
157 		free_pageset(toep->td, ps);
158 }
159 
160 static void
161 ddp_complete_one(struct kaiocb *job, int error)
162 {
163 	long copied;
164 
165 	/*
166 	 * If this job had copied data out of the socket buffer before
167 	 * it was cancelled, report it as a short read rather than an
168 	 * error.
169 	 */
170 	copied = job->aio_received;
171 	if (copied != 0 || error == 0)
172 		aio_complete(job, copied, 0);
173 	else
174 		aio_complete(job, -1, error);
175 }
176 
177 static void
178 free_ddp_buffer(struct tom_data *td, struct ddp_buffer *db)
179 {
180 
181 	if (db->job) {
182 		/*
183 		 * XXX: If we are un-offloading the socket then we
184 		 * should requeue these on the socket somehow.  If we
185 		 * got a FIN from the remote end, then this completes
186 		 * any remaining requests with an EOF read.
187 		 */
188 		if (!aio_clear_cancel_function(db->job))
189 			ddp_complete_one(db->job, 0);
190 	}
191 
192 	if (db->ps)
193 		free_pageset(td, db->ps);
194 }
195 
196 void
197 ddp_init_toep(struct toepcb *toep)
198 {
199 
200 	TAILQ_INIT(&toep->ddp_aiojobq);
201 	TASK_INIT(&toep->ddp_requeue_task, 0, aio_ddp_requeue_task, toep);
202 	toep->ddp_active_id = -1;
203 	mtx_init(&toep->ddp_lock, "t4 ddp", NULL, MTX_DEF);
204 }
205 
206 void
207 ddp_uninit_toep(struct toepcb *toep)
208 {
209 
210 	mtx_destroy(&toep->ddp_lock);
211 }
212 
213 void
214 release_ddp_resources(struct toepcb *toep)
215 {
216 	struct pageset *ps;
217 	int i;
218 
219 	DDP_LOCK(toep);
220 	toep->flags |= DDP_DEAD;
221 	for (i = 0; i < nitems(toep->db); i++) {
222 		free_ddp_buffer(toep->td, &toep->db[i]);
223 	}
224 	while ((ps = TAILQ_FIRST(&toep->ddp_cached_pagesets)) != NULL) {
225 		TAILQ_REMOVE(&toep->ddp_cached_pagesets, ps, link);
226 		free_pageset(toep->td, ps);
227 	}
228 	ddp_complete_all(toep, 0);
229 	DDP_UNLOCK(toep);
230 }
231 
232 #ifdef INVARIANTS
233 void
234 ddp_assert_empty(struct toepcb *toep)
235 {
236 	int i;
237 
238 	MPASS(!(toep->ddp_flags & DDP_TASK_ACTIVE));
239 	for (i = 0; i < nitems(toep->db); i++) {
240 		MPASS(toep->db[i].job == NULL);
241 		MPASS(toep->db[i].ps == NULL);
242 	}
243 	MPASS(TAILQ_EMPTY(&toep->ddp_cached_pagesets));
244 	MPASS(TAILQ_EMPTY(&toep->ddp_aiojobq));
245 }
246 #endif
247 
248 static void
249 complete_ddp_buffer(struct toepcb *toep, struct ddp_buffer *db,
250     unsigned int db_idx)
251 {
252 	unsigned int db_flag;
253 
254 	toep->ddp_active_count--;
255 	if (toep->ddp_active_id == db_idx) {
256 		if (toep->ddp_active_count == 0) {
257 			KASSERT(toep->db[db_idx ^ 1].job == NULL,
258 			    ("%s: active_count mismatch", __func__));
259 			toep->ddp_active_id = -1;
260 		} else
261 			toep->ddp_active_id ^= 1;
262 #ifdef VERBOSE_TRACES
263 		CTR2(KTR_CXGBE, "%s: ddp_active_id = %d", __func__,
264 		    toep->ddp_active_id);
265 #endif
266 	} else {
267 		KASSERT(toep->ddp_active_count != 0 &&
268 		    toep->ddp_active_id != -1,
269 		    ("%s: active count mismatch", __func__));
270 	}
271 
272 	db->cancel_pending = 0;
273 	db->job = NULL;
274 	recycle_pageset(toep, db->ps);
275 	db->ps = NULL;
276 
277 	db_flag = db_idx == 1 ? DDP_BUF1_ACTIVE : DDP_BUF0_ACTIVE;
278 	KASSERT(toep->ddp_flags & db_flag,
279 	    ("%s: DDP buffer not active. toep %p, ddp_flags 0x%x",
280 	    __func__, toep, toep->ddp_flags));
281 	toep->ddp_flags &= ~db_flag;
282 }
283 
284 /* XXX: handle_ddp_data code duplication */
285 void
286 insert_ddp_data(struct toepcb *toep, uint32_t n)
287 {
288 	struct inpcb *inp = toep->inp;
289 	struct tcpcb *tp = intotcpcb(inp);
290 	struct ddp_buffer *db;
291 	struct kaiocb *job;
292 	size_t placed;
293 	long copied;
294 	unsigned int db_flag, db_idx;
295 
296 	INP_WLOCK_ASSERT(inp);
297 	DDP_ASSERT_LOCKED(toep);
298 
299 	tp->rcv_nxt += n;
300 #ifndef USE_DDP_RX_FLOW_CONTROL
301 	KASSERT(tp->rcv_wnd >= n, ("%s: negative window size", __func__));
302 	tp->rcv_wnd -= n;
303 #endif
304 #ifndef USE_DDP_RX_FLOW_CONTROL
305 	toep->rx_credits += n;
306 #endif
307 	CTR2(KTR_CXGBE, "%s: placed %u bytes before falling out of DDP",
308 	    __func__, n);
309 	while (toep->ddp_active_count > 0) {
310 		MPASS(toep->ddp_active_id != -1);
311 		db_idx = toep->ddp_active_id;
312 		db_flag = db_idx == 1 ? DDP_BUF1_ACTIVE : DDP_BUF0_ACTIVE;
313 		MPASS((toep->ddp_flags & db_flag) != 0);
314 		db = &toep->db[db_idx];
315 		job = db->job;
316 		copied = job->aio_received;
317 		placed = n;
318 		if (placed > job->uaiocb.aio_nbytes - copied)
319 			placed = job->uaiocb.aio_nbytes - copied;
320 		if (placed > 0)
321 			job->msgrcv = 1;
322 		if (!aio_clear_cancel_function(job)) {
323 			/*
324 			 * Update the copied length for when
325 			 * t4_aio_cancel_active() completes this
326 			 * request.
327 			 */
328 			job->aio_received += placed;
329 		} else if (copied + placed != 0) {
330 			CTR4(KTR_CXGBE,
331 			    "%s: completing %p (copied %ld, placed %lu)",
332 			    __func__, job, copied, placed);
333 			/* XXX: This always completes if there is some data. */
334 			aio_complete(job, copied + placed, 0);
335 		} else if (aio_set_cancel_function(job, t4_aio_cancel_queued)) {
336 			TAILQ_INSERT_HEAD(&toep->ddp_aiojobq, job, list);
337 			toep->ddp_waiting_count++;
338 		} else
339 			aio_cancel(job);
340 		n -= placed;
341 		complete_ddp_buffer(toep, db, db_idx);
342 	}
343 
344 	MPASS(n == 0);
345 }
346 
347 /* SET_TCB_FIELD sent as a ULP command looks like this */
348 #define LEN__SET_TCB_FIELD_ULP (sizeof(struct ulp_txpkt) + \
349     sizeof(struct ulptx_idata) + sizeof(struct cpl_set_tcb_field_core))
350 
351 /* RX_DATA_ACK sent as a ULP command looks like this */
352 #define LEN__RX_DATA_ACK_ULP (sizeof(struct ulp_txpkt) + \
353     sizeof(struct ulptx_idata) + sizeof(struct cpl_rx_data_ack_core))
354 
355 static inline void *
356 mk_set_tcb_field_ulp(struct ulp_txpkt *ulpmc, struct toepcb *toep,
357     uint64_t word, uint64_t mask, uint64_t val)
358 {
359 	struct ulptx_idata *ulpsc;
360 	struct cpl_set_tcb_field_core *req;
361 
362 	ulpmc->cmd_dest = htonl(V_ULPTX_CMD(ULP_TX_PKT) | V_ULP_TXPKT_DEST(0));
363 	ulpmc->len = htobe32(howmany(LEN__SET_TCB_FIELD_ULP, 16));
364 
365 	ulpsc = (struct ulptx_idata *)(ulpmc + 1);
366 	ulpsc->cmd_more = htobe32(V_ULPTX_CMD(ULP_TX_SC_IMM));
367 	ulpsc->len = htobe32(sizeof(*req));
368 
369 	req = (struct cpl_set_tcb_field_core *)(ulpsc + 1);
370 	OPCODE_TID(req) = htobe32(MK_OPCODE_TID(CPL_SET_TCB_FIELD, toep->tid));
371 	req->reply_ctrl = htobe16(V_NO_REPLY(1) |
372 	    V_QUEUENO(toep->ofld_rxq->iq.abs_id));
373 	req->word_cookie = htobe16(V_WORD(word) | V_COOKIE(0));
374         req->mask = htobe64(mask);
375         req->val = htobe64(val);
376 
377 	ulpsc = (struct ulptx_idata *)(req + 1);
378 	if (LEN__SET_TCB_FIELD_ULP % 16) {
379 		ulpsc->cmd_more = htobe32(V_ULPTX_CMD(ULP_TX_SC_NOOP));
380 		ulpsc->len = htobe32(0);
381 		return (ulpsc + 1);
382 	}
383 	return (ulpsc);
384 }
385 
386 static inline void *
387 mk_rx_data_ack_ulp(struct ulp_txpkt *ulpmc, struct toepcb *toep)
388 {
389 	struct ulptx_idata *ulpsc;
390 	struct cpl_rx_data_ack_core *req;
391 
392 	ulpmc->cmd_dest = htonl(V_ULPTX_CMD(ULP_TX_PKT) | V_ULP_TXPKT_DEST(0));
393 	ulpmc->len = htobe32(howmany(LEN__RX_DATA_ACK_ULP, 16));
394 
395 	ulpsc = (struct ulptx_idata *)(ulpmc + 1);
396 	ulpsc->cmd_more = htobe32(V_ULPTX_CMD(ULP_TX_SC_IMM));
397 	ulpsc->len = htobe32(sizeof(*req));
398 
399 	req = (struct cpl_rx_data_ack_core *)(ulpsc + 1);
400 	OPCODE_TID(req) = htobe32(MK_OPCODE_TID(CPL_RX_DATA_ACK, toep->tid));
401 	req->credit_dack = htobe32(F_RX_MODULATE_RX);
402 
403 	ulpsc = (struct ulptx_idata *)(req + 1);
404 	if (LEN__RX_DATA_ACK_ULP % 16) {
405 		ulpsc->cmd_more = htobe32(V_ULPTX_CMD(ULP_TX_SC_NOOP));
406 		ulpsc->len = htobe32(0);
407 		return (ulpsc + 1);
408 	}
409 	return (ulpsc);
410 }
411 
412 static struct wrqe *
413 mk_update_tcb_for_ddp(struct adapter *sc, struct toepcb *toep, int db_idx,
414     struct pageset *ps, int offset, uint64_t ddp_flags, uint64_t ddp_flags_mask)
415 {
416 	struct wrqe *wr;
417 	struct work_request_hdr *wrh;
418 	struct ulp_txpkt *ulpmc;
419 	int len;
420 
421 	KASSERT(db_idx == 0 || db_idx == 1,
422 	    ("%s: bad DDP buffer index %d", __func__, db_idx));
423 
424 	/*
425 	 * We'll send a compound work request that has 3 SET_TCB_FIELDs and an
426 	 * RX_DATA_ACK (with RX_MODULATE to speed up delivery).
427 	 *
428 	 * The work request header is 16B and always ends at a 16B boundary.
429 	 * The ULPTX master commands that follow must all end at 16B boundaries
430 	 * too so we round up the size to 16.
431 	 */
432 	len = sizeof(*wrh) + 3 * roundup2(LEN__SET_TCB_FIELD_ULP, 16) +
433 	    roundup2(LEN__RX_DATA_ACK_ULP, 16);
434 
435 	wr = alloc_wrqe(len, toep->ctrlq);
436 	if (wr == NULL)
437 		return (NULL);
438 	wrh = wrtod(wr);
439 	INIT_ULPTX_WRH(wrh, len, 1, 0);	/* atomic */
440 	ulpmc = (struct ulp_txpkt *)(wrh + 1);
441 
442 	/* Write the buffer's tag */
443 	ulpmc = mk_set_tcb_field_ulp(ulpmc, toep,
444 	    W_TCB_RX_DDP_BUF0_TAG + db_idx,
445 	    V_TCB_RX_DDP_BUF0_TAG(M_TCB_RX_DDP_BUF0_TAG),
446 	    V_TCB_RX_DDP_BUF0_TAG(ps->prsv.prsv_tag));
447 
448 	/* Update the current offset in the DDP buffer and its total length */
449 	if (db_idx == 0)
450 		ulpmc = mk_set_tcb_field_ulp(ulpmc, toep,
451 		    W_TCB_RX_DDP_BUF0_OFFSET,
452 		    V_TCB_RX_DDP_BUF0_OFFSET(M_TCB_RX_DDP_BUF0_OFFSET) |
453 		    V_TCB_RX_DDP_BUF0_LEN(M_TCB_RX_DDP_BUF0_LEN),
454 		    V_TCB_RX_DDP_BUF0_OFFSET(offset) |
455 		    V_TCB_RX_DDP_BUF0_LEN(ps->len));
456 	else
457 		ulpmc = mk_set_tcb_field_ulp(ulpmc, toep,
458 		    W_TCB_RX_DDP_BUF1_OFFSET,
459 		    V_TCB_RX_DDP_BUF1_OFFSET(M_TCB_RX_DDP_BUF1_OFFSET) |
460 		    V_TCB_RX_DDP_BUF1_LEN((u64)M_TCB_RX_DDP_BUF1_LEN << 32),
461 		    V_TCB_RX_DDP_BUF1_OFFSET(offset) |
462 		    V_TCB_RX_DDP_BUF1_LEN((u64)ps->len << 32));
463 
464 	/* Update DDP flags */
465 	ulpmc = mk_set_tcb_field_ulp(ulpmc, toep, W_TCB_RX_DDP_FLAGS,
466 	    ddp_flags_mask, ddp_flags);
467 
468 	/* Gratuitous RX_DATA_ACK with RX_MODULATE set to speed up delivery. */
469 	ulpmc = mk_rx_data_ack_ulp(ulpmc, toep);
470 
471 	return (wr);
472 }
473 
474 static int
475 handle_ddp_data(struct toepcb *toep, __be32 ddp_report, __be32 rcv_nxt, int len)
476 {
477 	uint32_t report = be32toh(ddp_report);
478 	unsigned int db_idx;
479 	struct inpcb *inp = toep->inp;
480 	struct ddp_buffer *db;
481 	struct tcpcb *tp;
482 	struct socket *so;
483 	struct sockbuf *sb;
484 	struct kaiocb *job;
485 	long copied;
486 
487 	db_idx = report & F_DDP_BUF_IDX ? 1 : 0;
488 
489 	if (__predict_false(!(report & F_DDP_INV)))
490 		CXGBE_UNIMPLEMENTED("DDP buffer still valid");
491 
492 	INP_WLOCK(inp);
493 	so = inp_inpcbtosocket(inp);
494 	sb = &so->so_rcv;
495 	DDP_LOCK(toep);
496 
497 	KASSERT(toep->ddp_active_id == db_idx,
498 	    ("completed DDP buffer (%d) != active_id (%d) for tid %d", db_idx,
499 	    toep->ddp_active_id, toep->tid));
500 	db = &toep->db[db_idx];
501 	job = db->job;
502 
503 	if (__predict_false(inp->inp_flags & (INP_DROPPED | INP_TIMEWAIT))) {
504 		/*
505 		 * This can happen due to an administrative tcpdrop(8).
506 		 * Just fail the request with ECONNRESET.
507 		 */
508 		CTR5(KTR_CXGBE, "%s: tid %u, seq 0x%x, len %d, inp_flags 0x%x",
509 		    __func__, toep->tid, be32toh(rcv_nxt), len, inp->inp_flags);
510 		if (aio_clear_cancel_function(job))
511 			ddp_complete_one(job, ECONNRESET);
512 		goto completed;
513 	}
514 
515 	tp = intotcpcb(inp);
516 
517 	/*
518 	 * For RX_DDP_COMPLETE, len will be zero and rcv_nxt is the
519 	 * sequence number of the next byte to receive.  The length of
520 	 * the data received for this message must be computed by
521 	 * comparing the new and old values of rcv_nxt.
522 	 *
523 	 * For RX_DATA_DDP, len might be non-zero, but it is only the
524 	 * length of the most recent DMA.  It does not include the
525 	 * total length of the data received since the previous update
526 	 * for this DDP buffer.  rcv_nxt is the sequence number of the
527 	 * first received byte from the most recent DMA.
528 	 */
529 	len += be32toh(rcv_nxt) - tp->rcv_nxt;
530 	tp->rcv_nxt += len;
531 	tp->t_rcvtime = ticks;
532 #ifndef USE_DDP_RX_FLOW_CONTROL
533 	KASSERT(tp->rcv_wnd >= len, ("%s: negative window size", __func__));
534 	tp->rcv_wnd -= len;
535 #endif
536 #ifdef VERBOSE_TRACES
537 	CTR4(KTR_CXGBE, "%s: DDP[%d] placed %d bytes (%#x)", __func__, db_idx,
538 	    len, report);
539 #endif
540 
541 	/* receive buffer autosize */
542 	MPASS(toep->vnet == so->so_vnet);
543 	CURVNET_SET(toep->vnet);
544 	SOCKBUF_LOCK(sb);
545 	if (sb->sb_flags & SB_AUTOSIZE &&
546 	    V_tcp_do_autorcvbuf &&
547 	    sb->sb_hiwat < V_tcp_autorcvbuf_max &&
548 	    len > (sbspace(sb) / 8 * 7)) {
549 		unsigned int hiwat = sb->sb_hiwat;
550 		unsigned int newsize = min(hiwat + V_tcp_autorcvbuf_inc,
551 		    V_tcp_autorcvbuf_max);
552 
553 		if (!sbreserve_locked(sb, newsize, so, NULL))
554 			sb->sb_flags &= ~SB_AUTOSIZE;
555 		else
556 			toep->rx_credits += newsize - hiwat;
557 	}
558 	SOCKBUF_UNLOCK(sb);
559 	CURVNET_RESTORE();
560 
561 #ifndef USE_DDP_RX_FLOW_CONTROL
562 	toep->rx_credits += len;
563 #endif
564 
565 	job->msgrcv = 1;
566 	if (db->cancel_pending) {
567 		/*
568 		 * Update the job's length but defer completion to the
569 		 * TCB_RPL callback.
570 		 */
571 		job->aio_received += len;
572 		goto out;
573 	} else if (!aio_clear_cancel_function(job)) {
574 		/*
575 		 * Update the copied length for when
576 		 * t4_aio_cancel_active() completes this request.
577 		 */
578 		job->aio_received += len;
579 	} else {
580 		copied = job->aio_received;
581 #ifdef VERBOSE_TRACES
582 		CTR4(KTR_CXGBE, "%s: completing %p (copied %ld, placed %d)",
583 		    __func__, job, copied, len);
584 #endif
585 		aio_complete(job, copied + len, 0);
586 		t4_rcvd(&toep->td->tod, tp);
587 	}
588 
589 completed:
590 	complete_ddp_buffer(toep, db, db_idx);
591 	if (toep->ddp_waiting_count > 0)
592 		ddp_queue_toep(toep);
593 out:
594 	DDP_UNLOCK(toep);
595 	INP_WUNLOCK(inp);
596 
597 	return (0);
598 }
599 
600 void
601 handle_ddp_indicate(struct toepcb *toep)
602 {
603 
604 	DDP_ASSERT_LOCKED(toep);
605 	MPASS(toep->ddp_active_count == 0);
606 	MPASS((toep->ddp_flags & (DDP_BUF0_ACTIVE | DDP_BUF1_ACTIVE)) == 0);
607 	if (toep->ddp_waiting_count == 0) {
608 		/*
609 		 * The pending requests that triggered the request for an
610 		 * an indicate were cancelled.  Those cancels should have
611 		 * already disabled DDP.  Just ignore this as the data is
612 		 * going into the socket buffer anyway.
613 		 */
614 		return;
615 	}
616 	CTR3(KTR_CXGBE, "%s: tid %d indicated (%d waiting)", __func__,
617 	    toep->tid, toep->ddp_waiting_count);
618 	ddp_queue_toep(toep);
619 }
620 
621 enum {
622 	DDP_BUF0_INVALIDATED = 0x2,
623 	DDP_BUF1_INVALIDATED
624 };
625 
626 void
627 handle_ddp_tcb_rpl(struct toepcb *toep, const struct cpl_set_tcb_rpl *cpl)
628 {
629 	unsigned int db_idx;
630 	struct inpcb *inp = toep->inp;
631 	struct ddp_buffer *db;
632 	struct kaiocb *job;
633 	long copied;
634 
635 	if (cpl->status != CPL_ERR_NONE)
636 		panic("XXX: tcp_rpl failed: %d", cpl->status);
637 
638 	switch (cpl->cookie) {
639 	case V_WORD(W_TCB_RX_DDP_FLAGS) | V_COOKIE(DDP_BUF0_INVALIDATED):
640 	case V_WORD(W_TCB_RX_DDP_FLAGS) | V_COOKIE(DDP_BUF1_INVALIDATED):
641 		/*
642 		 * XXX: This duplicates a lot of code with handle_ddp_data().
643 		 */
644 		db_idx = G_COOKIE(cpl->cookie) - DDP_BUF0_INVALIDATED;
645 		INP_WLOCK(inp);
646 		DDP_LOCK(toep);
647 		db = &toep->db[db_idx];
648 
649 		/*
650 		 * handle_ddp_data() should leave the job around until
651 		 * this callback runs once a cancel is pending.
652 		 */
653 		MPASS(db != NULL);
654 		MPASS(db->job != NULL);
655 		MPASS(db->cancel_pending);
656 
657 		/*
658 		 * XXX: It's not clear what happens if there is data
659 		 * placed when the buffer is invalidated.  I suspect we
660 		 * need to read the TCB to see how much data was placed.
661 		 *
662 		 * For now this just pretends like nothing was placed.
663 		 *
664 		 * XXX: Note that if we did check the PCB we would need to
665 		 * also take care of updating the tp, etc.
666 		 */
667 		job = db->job;
668 		copied = job->aio_received;
669 		if (copied == 0) {
670 			CTR2(KTR_CXGBE, "%s: cancelling %p", __func__, job);
671 			aio_cancel(job);
672 		} else {
673 			CTR3(KTR_CXGBE, "%s: completing %p (copied %ld)",
674 			    __func__, job, copied);
675 			aio_complete(job, copied, 0);
676 			t4_rcvd(&toep->td->tod, intotcpcb(inp));
677 		}
678 
679 		complete_ddp_buffer(toep, db, db_idx);
680 		if (toep->ddp_waiting_count > 0)
681 			ddp_queue_toep(toep);
682 		DDP_UNLOCK(toep);
683 		INP_WUNLOCK(inp);
684 		break;
685 	default:
686 		panic("XXX: unknown tcb_rpl offset %#x, cookie %#x",
687 		    G_WORD(cpl->cookie), G_COOKIE(cpl->cookie));
688 	}
689 }
690 
691 void
692 handle_ddp_close(struct toepcb *toep, struct tcpcb *tp, __be32 rcv_nxt)
693 {
694 	struct ddp_buffer *db;
695 	struct kaiocb *job;
696 	long copied;
697 	unsigned int db_flag, db_idx;
698 	int len, placed;
699 
700 	INP_WLOCK_ASSERT(toep->inp);
701 	DDP_ASSERT_LOCKED(toep);
702 	len = be32toh(rcv_nxt) - tp->rcv_nxt;
703 
704 	tp->rcv_nxt += len;
705 #ifndef USE_DDP_RX_FLOW_CONTROL
706 	toep->rx_credits += len;
707 #endif
708 
709 	while (toep->ddp_active_count > 0) {
710 		MPASS(toep->ddp_active_id != -1);
711 		db_idx = toep->ddp_active_id;
712 		db_flag = db_idx == 1 ? DDP_BUF1_ACTIVE : DDP_BUF0_ACTIVE;
713 		MPASS((toep->ddp_flags & db_flag) != 0);
714 		db = &toep->db[db_idx];
715 		job = db->job;
716 		copied = job->aio_received;
717 		placed = len;
718 		if (placed > job->uaiocb.aio_nbytes - copied)
719 			placed = job->uaiocb.aio_nbytes - copied;
720 		if (placed > 0)
721 			job->msgrcv = 1;
722 		if (!aio_clear_cancel_function(job)) {
723 			/*
724 			 * Update the copied length for when
725 			 * t4_aio_cancel_active() completes this
726 			 * request.
727 			 */
728 			job->aio_received += placed;
729 		} else {
730 			CTR4(KTR_CXGBE, "%s: tid %d completed buf %d len %d",
731 			    __func__, toep->tid, db_idx, placed);
732 			aio_complete(job, copied + placed, 0);
733 		}
734 		len -= placed;
735 		complete_ddp_buffer(toep, db, db_idx);
736 	}
737 
738 	MPASS(len == 0);
739 	ddp_complete_all(toep, 0);
740 }
741 
742 #define DDP_ERR (F_DDP_PPOD_MISMATCH | F_DDP_LLIMIT_ERR | F_DDP_ULIMIT_ERR |\
743 	 F_DDP_PPOD_PARITY_ERR | F_DDP_PADDING_ERR | F_DDP_OFFSET_ERR |\
744 	 F_DDP_INVALID_TAG | F_DDP_COLOR_ERR | F_DDP_TID_MISMATCH |\
745 	 F_DDP_INVALID_PPOD | F_DDP_HDRCRC_ERR | F_DDP_DATACRC_ERR)
746 
747 extern cpl_handler_t t4_cpl_handler[];
748 
749 static int
750 do_rx_data_ddp(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
751 {
752 	struct adapter *sc = iq->adapter;
753 	const struct cpl_rx_data_ddp *cpl = (const void *)(rss + 1);
754 	unsigned int tid = GET_TID(cpl);
755 	uint32_t vld;
756 	struct toepcb *toep = lookup_tid(sc, tid);
757 
758 	KASSERT(m == NULL, ("%s: wasn't expecting payload", __func__));
759 	KASSERT(toep->tid == tid, ("%s: toep tid/atid mismatch", __func__));
760 	KASSERT(!(toep->flags & TPF_SYNQE),
761 	    ("%s: toep %p claims to be a synq entry", __func__, toep));
762 
763 	vld = be32toh(cpl->ddpvld);
764 	if (__predict_false(vld & DDP_ERR)) {
765 		panic("%s: DDP error 0x%x (tid %d, toep %p)",
766 		    __func__, vld, tid, toep);
767 	}
768 
769 	if (toep->ulp_mode == ULP_MODE_ISCSI) {
770 		t4_cpl_handler[CPL_RX_ISCSI_DDP](iq, rss, m);
771 		return (0);
772 	}
773 
774 	handle_ddp_data(toep, cpl->u.ddp_report, cpl->seq, be16toh(cpl->len));
775 
776 	return (0);
777 }
778 
779 static int
780 do_rx_ddp_complete(struct sge_iq *iq, const struct rss_header *rss,
781     struct mbuf *m)
782 {
783 	struct adapter *sc = iq->adapter;
784 	const struct cpl_rx_ddp_complete *cpl = (const void *)(rss + 1);
785 	unsigned int tid = GET_TID(cpl);
786 	struct toepcb *toep = lookup_tid(sc, tid);
787 
788 	KASSERT(m == NULL, ("%s: wasn't expecting payload", __func__));
789 	KASSERT(toep->tid == tid, ("%s: toep tid/atid mismatch", __func__));
790 	KASSERT(!(toep->flags & TPF_SYNQE),
791 	    ("%s: toep %p claims to be a synq entry", __func__, toep));
792 
793 	handle_ddp_data(toep, cpl->ddp_report, cpl->rcv_nxt, 0);
794 
795 	return (0);
796 }
797 
798 static void
799 enable_ddp(struct adapter *sc, struct toepcb *toep)
800 {
801 
802 	KASSERT((toep->ddp_flags & (DDP_ON | DDP_OK | DDP_SC_REQ)) == DDP_OK,
803 	    ("%s: toep %p has bad ddp_flags 0x%x",
804 	    __func__, toep, toep->ddp_flags));
805 
806 	CTR3(KTR_CXGBE, "%s: tid %u (time %u)",
807 	    __func__, toep->tid, time_uptime);
808 
809 	DDP_ASSERT_LOCKED(toep);
810 	toep->ddp_flags |= DDP_SC_REQ;
811 	t4_set_tcb_field(sc, toep->ctrlq, toep->tid, W_TCB_RX_DDP_FLAGS,
812 	    V_TF_DDP_OFF(1) | V_TF_DDP_INDICATE_OUT(1) |
813 	    V_TF_DDP_BUF0_INDICATE(1) | V_TF_DDP_BUF1_INDICATE(1) |
814 	    V_TF_DDP_BUF0_VALID(1) | V_TF_DDP_BUF1_VALID(1),
815 	    V_TF_DDP_BUF0_INDICATE(1) | V_TF_DDP_BUF1_INDICATE(1), 0, 0,
816 	    toep->ofld_rxq->iq.abs_id);
817 	t4_set_tcb_field(sc, toep->ctrlq, toep->tid, W_TCB_T_FLAGS,
818 	    V_TF_RCV_COALESCE_ENABLE(1), 0, 0, 0, toep->ofld_rxq->iq.abs_id);
819 }
820 
821 static int
822 calculate_hcf(int n1, int n2)
823 {
824 	int a, b, t;
825 
826 	if (n1 <= n2) {
827 		a = n1;
828 		b = n2;
829 	} else {
830 		a = n2;
831 		b = n1;
832 	}
833 
834 	while (a != 0) {
835 		t = a;
836 		a = b % a;
837 		b = t;
838 	}
839 
840 	return (b);
841 }
842 
843 static inline int
844 pages_to_nppods(int npages, int ddp_page_shift)
845 {
846 
847 	MPASS(ddp_page_shift >= PAGE_SHIFT);
848 
849 	return (howmany(npages >> (ddp_page_shift - PAGE_SHIFT), PPOD_PAGES));
850 }
851 
852 static int
853 alloc_page_pods(struct ppod_region *pr, u_int nppods, u_int pgsz_idx,
854     struct ppod_reservation *prsv)
855 {
856 	vmem_addr_t addr;       /* relative to start of region */
857 
858 	if (vmem_alloc(pr->pr_arena, PPOD_SZ(nppods), M_NOWAIT | M_FIRSTFIT,
859 	    &addr) != 0)
860 		return (ENOMEM);
861 
862 	CTR5(KTR_CXGBE, "%-17s arena %p, addr 0x%08x, nppods %d, pgsz %d",
863 	    __func__, pr->pr_arena, (uint32_t)addr & pr->pr_tag_mask,
864 	    nppods, 1 << pr->pr_page_shift[pgsz_idx]);
865 
866 	/*
867 	 * The hardware tagmask includes an extra invalid bit but the arena was
868 	 * seeded with valid values only.  An allocation out of this arena will
869 	 * fit inside the tagmask but won't have the invalid bit set.
870 	 */
871 	MPASS((addr & pr->pr_tag_mask) == addr);
872 	MPASS((addr & pr->pr_invalid_bit) == 0);
873 
874 	prsv->prsv_pr = pr;
875 	prsv->prsv_tag = V_PPOD_PGSZ(pgsz_idx) | addr;
876 	prsv->prsv_nppods = nppods;
877 
878 	return (0);
879 }
880 
881 int
882 t4_alloc_page_pods_for_ps(struct ppod_region *pr, struct pageset *ps)
883 {
884 	int i, hcf, seglen, idx, nppods;
885 	struct ppod_reservation *prsv = &ps->prsv;
886 
887 	KASSERT(prsv->prsv_nppods == 0,
888 	    ("%s: page pods already allocated", __func__));
889 
890 	/*
891 	 * The DDP page size is unrelated to the VM page size.  We combine
892 	 * contiguous physical pages into larger segments to get the best DDP
893 	 * page size possible.  This is the largest of the four sizes in
894 	 * A_ULP_RX_TDDP_PSZ that evenly divides the HCF of the segment sizes in
895 	 * the page list.
896 	 */
897 	hcf = 0;
898 	for (i = 0; i < ps->npages; i++) {
899 		seglen = PAGE_SIZE;
900 		while (i < ps->npages - 1 &&
901 		    ps->pages[i]->phys_addr + PAGE_SIZE ==
902 		    ps->pages[i + 1]->phys_addr) {
903 			seglen += PAGE_SIZE;
904 			i++;
905 		}
906 
907 		hcf = calculate_hcf(hcf, seglen);
908 		if (hcf < (1 << pr->pr_page_shift[1])) {
909 			idx = 0;
910 			goto have_pgsz;	/* give up, short circuit */
911 		}
912 	}
913 
914 #define PR_PAGE_MASK(x) ((1 << pr->pr_page_shift[(x)]) - 1)
915 	MPASS((hcf & PR_PAGE_MASK(0)) == 0); /* PAGE_SIZE is >= 4K everywhere */
916 	for (idx = nitems(pr->pr_page_shift) - 1; idx > 0; idx--) {
917 		if ((hcf & PR_PAGE_MASK(idx)) == 0)
918 			break;
919 	}
920 #undef PR_PAGE_MASK
921 
922 have_pgsz:
923 	MPASS(idx <= M_PPOD_PGSZ);
924 
925 	nppods = pages_to_nppods(ps->npages, pr->pr_page_shift[idx]);
926 	if (alloc_page_pods(pr, nppods, idx, prsv) != 0)
927 		return (0);
928 	MPASS(prsv->prsv_nppods > 0);
929 
930 	return (1);
931 }
932 
933 int
934 t4_alloc_page_pods_for_buf(struct ppod_region *pr, vm_offset_t buf, int len,
935     struct ppod_reservation *prsv)
936 {
937 	int hcf, seglen, idx, npages, nppods;
938 	uintptr_t start_pva, end_pva, pva, p1;
939 
940 	MPASS(buf > 0);
941 	MPASS(len > 0);
942 
943 	/*
944 	 * The DDP page size is unrelated to the VM page size.  We combine
945 	 * contiguous physical pages into larger segments to get the best DDP
946 	 * page size possible.  This is the largest of the four sizes in
947 	 * A_ULP_RX_ISCSI_PSZ that evenly divides the HCF of the segment sizes
948 	 * in the page list.
949 	 */
950 	hcf = 0;
951 	start_pva = trunc_page(buf);
952 	end_pva = trunc_page(buf + len - 1);
953 	pva = start_pva;
954 	while (pva <= end_pva) {
955 		seglen = PAGE_SIZE;
956 		p1 = pmap_kextract(pva);
957 		pva += PAGE_SIZE;
958 		while (pva <= end_pva && p1 + seglen == pmap_kextract(pva)) {
959 			seglen += PAGE_SIZE;
960 			pva += PAGE_SIZE;
961 		}
962 
963 		hcf = calculate_hcf(hcf, seglen);
964 		if (hcf < (1 << pr->pr_page_shift[1])) {
965 			idx = 0;
966 			goto have_pgsz;	/* give up, short circuit */
967 		}
968 	}
969 
970 #define PR_PAGE_MASK(x) ((1 << pr->pr_page_shift[(x)]) - 1)
971 	MPASS((hcf & PR_PAGE_MASK(0)) == 0); /* PAGE_SIZE is >= 4K everywhere */
972 	for (idx = nitems(pr->pr_page_shift) - 1; idx > 0; idx--) {
973 		if ((hcf & PR_PAGE_MASK(idx)) == 0)
974 			break;
975 	}
976 #undef PR_PAGE_MASK
977 
978 have_pgsz:
979 	MPASS(idx <= M_PPOD_PGSZ);
980 
981 	npages = 1;
982 	npages += (end_pva - start_pva) >> pr->pr_page_shift[idx];
983 	nppods = howmany(npages, PPOD_PAGES);
984 	if (alloc_page_pods(pr, nppods, idx, prsv) != 0)
985 		return (ENOMEM);
986 	MPASS(prsv->prsv_nppods > 0);
987 
988 	return (0);
989 }
990 
991 void
992 t4_free_page_pods(struct ppod_reservation *prsv)
993 {
994 	struct ppod_region *pr = prsv->prsv_pr;
995 	vmem_addr_t addr;
996 
997 	MPASS(prsv != NULL);
998 	MPASS(prsv->prsv_nppods != 0);
999 
1000 	addr = prsv->prsv_tag & pr->pr_tag_mask;
1001 	MPASS((addr & pr->pr_invalid_bit) == 0);
1002 
1003 	CTR4(KTR_CXGBE, "%-17s arena %p, addr 0x%08x, nppods %d", __func__,
1004 	    pr->pr_arena, addr, prsv->prsv_nppods);
1005 
1006 	vmem_free(pr->pr_arena, addr, PPOD_SZ(prsv->prsv_nppods));
1007 	prsv->prsv_nppods = 0;
1008 }
1009 
1010 #define NUM_ULP_TX_SC_IMM_PPODS (256 / PPOD_SIZE)
1011 
1012 int
1013 t4_write_page_pods_for_ps(struct adapter *sc, struct sge_wrq *wrq, int tid,
1014     struct pageset *ps)
1015 {
1016 	struct wrqe *wr;
1017 	struct ulp_mem_io *ulpmc;
1018 	struct ulptx_idata *ulpsc;
1019 	struct pagepod *ppod;
1020 	int i, j, k, n, chunk, len, ddp_pgsz, idx;
1021 	u_int ppod_addr;
1022 	uint32_t cmd;
1023 	struct ppod_reservation *prsv = &ps->prsv;
1024 	struct ppod_region *pr = prsv->prsv_pr;
1025 
1026 	KASSERT(!(ps->flags & PS_PPODS_WRITTEN),
1027 	    ("%s: page pods already written", __func__));
1028 	MPASS(prsv->prsv_nppods > 0);
1029 
1030 	cmd = htobe32(V_ULPTX_CMD(ULP_TX_MEM_WRITE));
1031 	if (is_t4(sc))
1032 		cmd |= htobe32(F_ULP_MEMIO_ORDER);
1033 	else
1034 		cmd |= htobe32(F_T5_ULP_MEMIO_IMM);
1035 	ddp_pgsz = 1 << pr->pr_page_shift[G_PPOD_PGSZ(prsv->prsv_tag)];
1036 	ppod_addr = pr->pr_start + (prsv->prsv_tag & pr->pr_tag_mask);
1037 	for (i = 0; i < prsv->prsv_nppods; ppod_addr += chunk) {
1038 
1039 		/* How many page pods are we writing in this cycle */
1040 		n = min(prsv->prsv_nppods - i, NUM_ULP_TX_SC_IMM_PPODS);
1041 		chunk = PPOD_SZ(n);
1042 		len = roundup2(sizeof(*ulpmc) + sizeof(*ulpsc) + chunk, 16);
1043 
1044 		wr = alloc_wrqe(len, wrq);
1045 		if (wr == NULL)
1046 			return (ENOMEM);	/* ok to just bail out */
1047 		ulpmc = wrtod(wr);
1048 
1049 		INIT_ULPTX_WR(ulpmc, len, 0, 0);
1050 		ulpmc->cmd = cmd;
1051 		ulpmc->dlen = htobe32(V_ULP_MEMIO_DATA_LEN(chunk / 32));
1052 		ulpmc->len16 = htobe32(howmany(len - sizeof(ulpmc->wr), 16));
1053 		ulpmc->lock_addr = htobe32(V_ULP_MEMIO_ADDR(ppod_addr >> 5));
1054 
1055 		ulpsc = (struct ulptx_idata *)(ulpmc + 1);
1056 		ulpsc->cmd_more = htobe32(V_ULPTX_CMD(ULP_TX_SC_IMM));
1057 		ulpsc->len = htobe32(chunk);
1058 
1059 		ppod = (struct pagepod *)(ulpsc + 1);
1060 		for (j = 0; j < n; i++, j++, ppod++) {
1061 			ppod->vld_tid_pgsz_tag_color = htobe64(F_PPOD_VALID |
1062 			    V_PPOD_TID(tid) | prsv->prsv_tag);
1063 			ppod->len_offset = htobe64(V_PPOD_LEN(ps->len) |
1064 			    V_PPOD_OFST(ps->offset));
1065 			ppod->rsvd = 0;
1066 			idx = i * PPOD_PAGES * (ddp_pgsz / PAGE_SIZE);
1067 			for (k = 0; k < nitems(ppod->addr); k++) {
1068 				if (idx < ps->npages) {
1069 					ppod->addr[k] =
1070 					    htobe64(ps->pages[idx]->phys_addr);
1071 					idx += ddp_pgsz / PAGE_SIZE;
1072 				} else
1073 					ppod->addr[k] = 0;
1074 #if 0
1075 				CTR5(KTR_CXGBE,
1076 				    "%s: tid %d ppod[%d]->addr[%d] = %p",
1077 				    __func__, toep->tid, i, k,
1078 				    htobe64(ppod->addr[k]));
1079 #endif
1080 			}
1081 
1082 		}
1083 
1084 		t4_wrq_tx(sc, wr);
1085 	}
1086 	ps->flags |= PS_PPODS_WRITTEN;
1087 
1088 	return (0);
1089 }
1090 
1091 int
1092 t4_write_page_pods_for_buf(struct adapter *sc, struct sge_wrq *wrq, int tid,
1093     struct ppod_reservation *prsv, vm_offset_t buf, int buflen)
1094 {
1095 	struct wrqe *wr;
1096 	struct ulp_mem_io *ulpmc;
1097 	struct ulptx_idata *ulpsc;
1098 	struct pagepod *ppod;
1099 	int i, j, k, n, chunk, len, ddp_pgsz;
1100 	u_int ppod_addr, offset;
1101 	uint32_t cmd;
1102 	struct ppod_region *pr = prsv->prsv_pr;
1103 	uintptr_t end_pva, pva, pa;
1104 
1105 	cmd = htobe32(V_ULPTX_CMD(ULP_TX_MEM_WRITE));
1106 	if (is_t4(sc))
1107 		cmd |= htobe32(F_ULP_MEMIO_ORDER);
1108 	else
1109 		cmd |= htobe32(F_T5_ULP_MEMIO_IMM);
1110 	ddp_pgsz = 1 << pr->pr_page_shift[G_PPOD_PGSZ(prsv->prsv_tag)];
1111 	offset = buf & PAGE_MASK;
1112 	ppod_addr = pr->pr_start + (prsv->prsv_tag & pr->pr_tag_mask);
1113 	pva = trunc_page(buf);
1114 	end_pva = trunc_page(buf + buflen - 1);
1115 	for (i = 0; i < prsv->prsv_nppods; ppod_addr += chunk) {
1116 
1117 		/* How many page pods are we writing in this cycle */
1118 		n = min(prsv->prsv_nppods - i, NUM_ULP_TX_SC_IMM_PPODS);
1119 		MPASS(n > 0);
1120 		chunk = PPOD_SZ(n);
1121 		len = roundup2(sizeof(*ulpmc) + sizeof(*ulpsc) + chunk, 16);
1122 
1123 		wr = alloc_wrqe(len, wrq);
1124 		if (wr == NULL)
1125 			return (ENOMEM);	/* ok to just bail out */
1126 		ulpmc = wrtod(wr);
1127 
1128 		INIT_ULPTX_WR(ulpmc, len, 0, 0);
1129 		ulpmc->cmd = cmd;
1130 		ulpmc->dlen = htobe32(V_ULP_MEMIO_DATA_LEN(chunk / 32));
1131 		ulpmc->len16 = htobe32(howmany(len - sizeof(ulpmc->wr), 16));
1132 		ulpmc->lock_addr = htobe32(V_ULP_MEMIO_ADDR(ppod_addr >> 5));
1133 
1134 		ulpsc = (struct ulptx_idata *)(ulpmc + 1);
1135 		ulpsc->cmd_more = htobe32(V_ULPTX_CMD(ULP_TX_SC_IMM));
1136 		ulpsc->len = htobe32(chunk);
1137 
1138 		ppod = (struct pagepod *)(ulpsc + 1);
1139 		for (j = 0; j < n; i++, j++, ppod++) {
1140 			ppod->vld_tid_pgsz_tag_color = htobe64(F_PPOD_VALID |
1141 			    V_PPOD_TID(tid) |
1142 			    (prsv->prsv_tag & ~V_PPOD_PGSZ(M_PPOD_PGSZ)));
1143 			ppod->len_offset = htobe64(V_PPOD_LEN(buflen) |
1144 			    V_PPOD_OFST(offset));
1145 			ppod->rsvd = 0;
1146 
1147 			for (k = 0; k < nitems(ppod->addr); k++) {
1148 				if (pva > end_pva)
1149 					ppod->addr[k] = 0;
1150 				else {
1151 					pa = pmap_kextract(pva);
1152 					ppod->addr[k] = htobe64(pa);
1153 					pva += ddp_pgsz;
1154 				}
1155 #if 0
1156 				CTR5(KTR_CXGBE,
1157 				    "%s: tid %d ppod[%d]->addr[%d] = %p",
1158 				    __func__, tid, i, k,
1159 				    htobe64(ppod->addr[k]));
1160 #endif
1161 			}
1162 
1163 			/*
1164 			 * Walk back 1 segment so that the first address in the
1165 			 * next pod is the same as the last one in the current
1166 			 * pod.
1167 			 */
1168 			pva -= ddp_pgsz;
1169 		}
1170 
1171 		t4_wrq_tx(sc, wr);
1172 	}
1173 
1174 	MPASS(pva <= end_pva);
1175 
1176 	return (0);
1177 }
1178 
1179 static void
1180 wire_pageset(struct pageset *ps)
1181 {
1182 	vm_page_t p;
1183 	int i;
1184 
1185 	KASSERT(!(ps->flags & PS_WIRED), ("pageset already wired"));
1186 
1187 	for (i = 0; i < ps->npages; i++) {
1188 		p = ps->pages[i];
1189 		vm_page_lock(p);
1190 		vm_page_wire(p);
1191 		vm_page_unhold(p);
1192 		vm_page_unlock(p);
1193 	}
1194 	ps->flags |= PS_WIRED;
1195 }
1196 
1197 /*
1198  * Prepare a pageset for DDP.  This wires the pageset and sets up page
1199  * pods.
1200  */
1201 static int
1202 prep_pageset(struct adapter *sc, struct toepcb *toep, struct pageset *ps)
1203 {
1204 	struct tom_data *td = sc->tom_softc;
1205 
1206 	if (!(ps->flags & PS_WIRED))
1207 		wire_pageset(ps);
1208 	if (ps->prsv.prsv_nppods == 0 &&
1209 	    !t4_alloc_page_pods_for_ps(&td->pr, ps)) {
1210 		return (0);
1211 	}
1212 	if (!(ps->flags & PS_PPODS_WRITTEN) &&
1213 	    t4_write_page_pods_for_ps(sc, toep->ctrlq, toep->tid, ps) != 0) {
1214 		return (0);
1215 	}
1216 
1217 	return (1);
1218 }
1219 
1220 int
1221 t4_init_ppod_region(struct ppod_region *pr, struct t4_range *r, u_int psz,
1222     const char *name)
1223 {
1224 	int i;
1225 
1226 	MPASS(pr != NULL);
1227 	MPASS(r->size > 0);
1228 
1229 	pr->pr_start = r->start;
1230 	pr->pr_len = r->size;
1231 	pr->pr_page_shift[0] = 12 + G_HPZ0(psz);
1232 	pr->pr_page_shift[1] = 12 + G_HPZ1(psz);
1233 	pr->pr_page_shift[2] = 12 + G_HPZ2(psz);
1234 	pr->pr_page_shift[3] = 12 + G_HPZ3(psz);
1235 
1236 	/* The SGL -> page pod algorithm requires the sizes to be in order. */
1237 	for (i = 1; i < nitems(pr->pr_page_shift); i++) {
1238 		if (pr->pr_page_shift[i] <= pr->pr_page_shift[i - 1])
1239 			return (ENXIO);
1240 	}
1241 
1242 	pr->pr_tag_mask = ((1 << fls(r->size)) - 1) & V_PPOD_TAG(M_PPOD_TAG);
1243 	pr->pr_alias_mask = V_PPOD_TAG(M_PPOD_TAG) & ~pr->pr_tag_mask;
1244 	if (pr->pr_tag_mask == 0 || pr->pr_alias_mask == 0)
1245 		return (ENXIO);
1246 	pr->pr_alias_shift = fls(pr->pr_tag_mask);
1247 	pr->pr_invalid_bit = 1 << (pr->pr_alias_shift - 1);
1248 
1249 	pr->pr_arena = vmem_create(name, 0, pr->pr_len, PPOD_SIZE, 0,
1250 	    M_FIRSTFIT | M_NOWAIT);
1251 	if (pr->pr_arena == NULL)
1252 		return (ENOMEM);
1253 
1254 	return (0);
1255 }
1256 
1257 void
1258 t4_free_ppod_region(struct ppod_region *pr)
1259 {
1260 
1261 	MPASS(pr != NULL);
1262 
1263 	if (pr->pr_arena)
1264 		vmem_destroy(pr->pr_arena);
1265 	bzero(pr, sizeof(*pr));
1266 }
1267 
1268 static int
1269 pscmp(struct pageset *ps, struct vmspace *vm, vm_offset_t start, int npages,
1270     int pgoff, int len)
1271 {
1272 
1273 	if (ps->start != start || ps->npages != npages ||
1274 	    ps->offset != pgoff || ps->len != len)
1275 		return (1);
1276 
1277 	return (ps->vm != vm || ps->vm_timestamp != vm->vm_map.timestamp);
1278 }
1279 
1280 static int
1281 hold_aio(struct toepcb *toep, struct kaiocb *job, struct pageset **pps)
1282 {
1283 	struct vmspace *vm;
1284 	vm_map_t map;
1285 	vm_offset_t start, end, pgoff;
1286 	struct pageset *ps;
1287 	int n;
1288 
1289 	DDP_ASSERT_LOCKED(toep);
1290 
1291 	/*
1292 	 * The AIO subsystem will cancel and drain all requests before
1293 	 * permitting a process to exit or exec, so p_vmspace should
1294 	 * be stable here.
1295 	 */
1296 	vm = job->userproc->p_vmspace;
1297 	map = &vm->vm_map;
1298 	start = (uintptr_t)job->uaiocb.aio_buf;
1299 	pgoff = start & PAGE_MASK;
1300 	end = round_page(start + job->uaiocb.aio_nbytes);
1301 	start = trunc_page(start);
1302 
1303 	if (end - start > MAX_DDP_BUFFER_SIZE) {
1304 		/*
1305 		 * Truncate the request to a short read.
1306 		 * Alternatively, we could DDP in chunks to the larger
1307 		 * buffer, but that would be quite a bit more work.
1308 		 *
1309 		 * When truncating, round the request down to avoid
1310 		 * crossing a cache line on the final transaction.
1311 		 */
1312 		end = rounddown2(start + MAX_DDP_BUFFER_SIZE, CACHE_LINE_SIZE);
1313 #ifdef VERBOSE_TRACES
1314 		CTR4(KTR_CXGBE, "%s: tid %d, truncating size from %lu to %lu",
1315 		    __func__, toep->tid, (unsigned long)job->uaiocb.aio_nbytes,
1316 		    (unsigned long)(end - (start + pgoff)));
1317 		job->uaiocb.aio_nbytes = end - (start + pgoff);
1318 #endif
1319 		end = round_page(end);
1320 	}
1321 
1322 	n = atop(end - start);
1323 
1324 	/*
1325 	 * Try to reuse a cached pageset.
1326 	 */
1327 	TAILQ_FOREACH(ps, &toep->ddp_cached_pagesets, link) {
1328 		if (pscmp(ps, vm, start, n, pgoff,
1329 		    job->uaiocb.aio_nbytes) == 0) {
1330 			TAILQ_REMOVE(&toep->ddp_cached_pagesets, ps, link);
1331 			toep->ddp_cached_count--;
1332 			*pps = ps;
1333 			return (0);
1334 		}
1335 	}
1336 
1337 	/*
1338 	 * If there are too many cached pagesets to create a new one,
1339 	 * free a pageset before creating a new one.
1340 	 */
1341 	KASSERT(toep->ddp_active_count + toep->ddp_cached_count <=
1342 	    nitems(toep->db), ("%s: too many wired pagesets", __func__));
1343 	if (toep->ddp_active_count + toep->ddp_cached_count ==
1344 	    nitems(toep->db)) {
1345 		KASSERT(toep->ddp_cached_count > 0,
1346 		    ("no cached pageset to free"));
1347 		ps = TAILQ_LAST(&toep->ddp_cached_pagesets, pagesetq);
1348 		TAILQ_REMOVE(&toep->ddp_cached_pagesets, ps, link);
1349 		toep->ddp_cached_count--;
1350 		free_pageset(toep->td, ps);
1351 	}
1352 	DDP_UNLOCK(toep);
1353 
1354 	/* Create a new pageset. */
1355 	ps = malloc(sizeof(*ps) + n * sizeof(vm_page_t), M_CXGBE, M_WAITOK |
1356 	    M_ZERO);
1357 	ps->pages = (vm_page_t *)(ps + 1);
1358 	ps->vm_timestamp = map->timestamp;
1359 	ps->npages = vm_fault_quick_hold_pages(map, start, end - start,
1360 	    VM_PROT_WRITE, ps->pages, n);
1361 
1362 	DDP_LOCK(toep);
1363 	if (ps->npages < 0) {
1364 		free(ps, M_CXGBE);
1365 		return (EFAULT);
1366 	}
1367 
1368 	KASSERT(ps->npages == n, ("hold_aio: page count mismatch: %d vs %d",
1369 	    ps->npages, n));
1370 
1371 	ps->offset = pgoff;
1372 	ps->len = job->uaiocb.aio_nbytes;
1373 	atomic_add_int(&vm->vm_refcnt, 1);
1374 	ps->vm = vm;
1375 	ps->start = start;
1376 
1377 	CTR5(KTR_CXGBE, "%s: tid %d, new pageset %p for job %p, npages %d",
1378 	    __func__, toep->tid, ps, job, ps->npages);
1379 	*pps = ps;
1380 	return (0);
1381 }
1382 
1383 static void
1384 ddp_complete_all(struct toepcb *toep, int error)
1385 {
1386 	struct kaiocb *job;
1387 
1388 	DDP_ASSERT_LOCKED(toep);
1389 	while (!TAILQ_EMPTY(&toep->ddp_aiojobq)) {
1390 		job = TAILQ_FIRST(&toep->ddp_aiojobq);
1391 		TAILQ_REMOVE(&toep->ddp_aiojobq, job, list);
1392 		toep->ddp_waiting_count--;
1393 		if (aio_clear_cancel_function(job))
1394 			ddp_complete_one(job, error);
1395 	}
1396 }
1397 
1398 static void
1399 aio_ddp_cancel_one(struct kaiocb *job)
1400 {
1401 	long copied;
1402 
1403 	/*
1404 	 * If this job had copied data out of the socket buffer before
1405 	 * it was cancelled, report it as a short read rather than an
1406 	 * error.
1407 	 */
1408 	copied = job->aio_received;
1409 	if (copied != 0)
1410 		aio_complete(job, copied, 0);
1411 	else
1412 		aio_cancel(job);
1413 }
1414 
1415 /*
1416  * Called when the main loop wants to requeue a job to retry it later.
1417  * Deals with the race of the job being cancelled while it was being
1418  * examined.
1419  */
1420 static void
1421 aio_ddp_requeue_one(struct toepcb *toep, struct kaiocb *job)
1422 {
1423 
1424 	DDP_ASSERT_LOCKED(toep);
1425 	if (!(toep->ddp_flags & DDP_DEAD) &&
1426 	    aio_set_cancel_function(job, t4_aio_cancel_queued)) {
1427 		TAILQ_INSERT_HEAD(&toep->ddp_aiojobq, job, list);
1428 		toep->ddp_waiting_count++;
1429 	} else
1430 		aio_ddp_cancel_one(job);
1431 }
1432 
1433 static void
1434 aio_ddp_requeue(struct toepcb *toep)
1435 {
1436 	struct adapter *sc = td_adapter(toep->td);
1437 	struct socket *so;
1438 	struct sockbuf *sb;
1439 	struct inpcb *inp;
1440 	struct kaiocb *job;
1441 	struct ddp_buffer *db;
1442 	size_t copied, offset, resid;
1443 	struct pageset *ps;
1444 	struct mbuf *m;
1445 	uint64_t ddp_flags, ddp_flags_mask;
1446 	struct wrqe *wr;
1447 	int buf_flag, db_idx, error;
1448 
1449 	DDP_ASSERT_LOCKED(toep);
1450 
1451 restart:
1452 	if (toep->ddp_flags & DDP_DEAD) {
1453 		MPASS(toep->ddp_waiting_count == 0);
1454 		MPASS(toep->ddp_active_count == 0);
1455 		return;
1456 	}
1457 
1458 	if (toep->ddp_waiting_count == 0 ||
1459 	    toep->ddp_active_count == nitems(toep->db)) {
1460 		return;
1461 	}
1462 
1463 	job = TAILQ_FIRST(&toep->ddp_aiojobq);
1464 	so = job->fd_file->f_data;
1465 	sb = &so->so_rcv;
1466 	SOCKBUF_LOCK(sb);
1467 
1468 	/* We will never get anything unless we are or were connected. */
1469 	if (!(so->so_state & (SS_ISCONNECTED|SS_ISDISCONNECTED))) {
1470 		SOCKBUF_UNLOCK(sb);
1471 		ddp_complete_all(toep, ENOTCONN);
1472 		return;
1473 	}
1474 
1475 	KASSERT(toep->ddp_active_count == 0 || sbavail(sb) == 0,
1476 	    ("%s: pending sockbuf data and DDP is active", __func__));
1477 
1478 	/* Abort if socket has reported problems. */
1479 	/* XXX: Wait for any queued DDP's to finish and/or flush them? */
1480 	if (so->so_error && sbavail(sb) == 0) {
1481 		toep->ddp_waiting_count--;
1482 		TAILQ_REMOVE(&toep->ddp_aiojobq, job, list);
1483 		if (!aio_clear_cancel_function(job)) {
1484 			SOCKBUF_UNLOCK(sb);
1485 			goto restart;
1486 		}
1487 
1488 		/*
1489 		 * If this job has previously copied some data, report
1490 		 * a short read and leave the error to be reported by
1491 		 * a future request.
1492 		 */
1493 		copied = job->aio_received;
1494 		if (copied != 0) {
1495 			SOCKBUF_UNLOCK(sb);
1496 			aio_complete(job, copied, 0);
1497 			goto restart;
1498 		}
1499 		error = so->so_error;
1500 		so->so_error = 0;
1501 		SOCKBUF_UNLOCK(sb);
1502 		aio_complete(job, -1, error);
1503 		goto restart;
1504 	}
1505 
1506 	/*
1507 	 * Door is closed.  If there is pending data in the socket buffer,
1508 	 * deliver it.  If there are pending DDP requests, wait for those
1509 	 * to complete.  Once they have completed, return EOF reads.
1510 	 */
1511 	if (sb->sb_state & SBS_CANTRCVMORE && sbavail(sb) == 0) {
1512 		SOCKBUF_UNLOCK(sb);
1513 		if (toep->ddp_active_count != 0)
1514 			return;
1515 		ddp_complete_all(toep, 0);
1516 		return;
1517 	}
1518 
1519 	/*
1520 	 * If DDP is not enabled and there is no pending socket buffer
1521 	 * data, try to enable DDP.
1522 	 */
1523 	if (sbavail(sb) == 0 && (toep->ddp_flags & DDP_ON) == 0) {
1524 		SOCKBUF_UNLOCK(sb);
1525 
1526 		/*
1527 		 * Wait for the card to ACK that DDP is enabled before
1528 		 * queueing any buffers.  Currently this waits for an
1529 		 * indicate to arrive.  This could use a TCB_SET_FIELD_RPL
1530 		 * message to know that DDP was enabled instead of waiting
1531 		 * for the indicate which would avoid copying the indicate
1532 		 * if no data is pending.
1533 		 *
1534 		 * XXX: Might want to limit the indicate size to the size
1535 		 * of the first queued request.
1536 		 */
1537 		if ((toep->ddp_flags & DDP_SC_REQ) == 0)
1538 			enable_ddp(sc, toep);
1539 		return;
1540 	}
1541 	SOCKBUF_UNLOCK(sb);
1542 
1543 	/*
1544 	 * If another thread is queueing a buffer for DDP, let it
1545 	 * drain any work and return.
1546 	 */
1547 	if (toep->ddp_queueing != NULL)
1548 		return;
1549 
1550 	/* Take the next job to prep it for DDP. */
1551 	toep->ddp_waiting_count--;
1552 	TAILQ_REMOVE(&toep->ddp_aiojobq, job, list);
1553 	if (!aio_clear_cancel_function(job))
1554 		goto restart;
1555 	toep->ddp_queueing = job;
1556 
1557 	/* NB: This drops DDP_LOCK while it holds the backing VM pages. */
1558 	error = hold_aio(toep, job, &ps);
1559 	if (error != 0) {
1560 		ddp_complete_one(job, error);
1561 		toep->ddp_queueing = NULL;
1562 		goto restart;
1563 	}
1564 
1565 	SOCKBUF_LOCK(sb);
1566 	if (so->so_error && sbavail(sb) == 0) {
1567 		copied = job->aio_received;
1568 		if (copied != 0) {
1569 			SOCKBUF_UNLOCK(sb);
1570 			recycle_pageset(toep, ps);
1571 			aio_complete(job, copied, 0);
1572 			toep->ddp_queueing = NULL;
1573 			goto restart;
1574 		}
1575 
1576 		error = so->so_error;
1577 		so->so_error = 0;
1578 		SOCKBUF_UNLOCK(sb);
1579 		recycle_pageset(toep, ps);
1580 		aio_complete(job, -1, error);
1581 		toep->ddp_queueing = NULL;
1582 		goto restart;
1583 	}
1584 
1585 	if (sb->sb_state & SBS_CANTRCVMORE && sbavail(sb) == 0) {
1586 		SOCKBUF_UNLOCK(sb);
1587 		recycle_pageset(toep, ps);
1588 		if (toep->ddp_active_count != 0) {
1589 			/*
1590 			 * The door is closed, but there are still pending
1591 			 * DDP buffers.  Requeue.  These jobs will all be
1592 			 * completed once those buffers drain.
1593 			 */
1594 			aio_ddp_requeue_one(toep, job);
1595 			toep->ddp_queueing = NULL;
1596 			return;
1597 		}
1598 		ddp_complete_one(job, 0);
1599 		ddp_complete_all(toep, 0);
1600 		toep->ddp_queueing = NULL;
1601 		return;
1602 	}
1603 
1604 sbcopy:
1605 	/*
1606 	 * If the toep is dead, there shouldn't be any data in the socket
1607 	 * buffer, so the above case should have handled this.
1608 	 */
1609 	MPASS(!(toep->ddp_flags & DDP_DEAD));
1610 
1611 	/*
1612 	 * If there is pending data in the socket buffer (either
1613 	 * from before the requests were queued or a DDP indicate),
1614 	 * copy those mbufs out directly.
1615 	 */
1616 	copied = 0;
1617 	offset = ps->offset + job->aio_received;
1618 	MPASS(job->aio_received <= job->uaiocb.aio_nbytes);
1619 	resid = job->uaiocb.aio_nbytes - job->aio_received;
1620 	m = sb->sb_mb;
1621 	KASSERT(m == NULL || toep->ddp_active_count == 0,
1622 	    ("%s: sockbuf data with active DDP", __func__));
1623 	while (m != NULL && resid > 0) {
1624 		struct iovec iov[1];
1625 		struct uio uio;
1626 		int error;
1627 
1628 		iov[0].iov_base = mtod(m, void *);
1629 		iov[0].iov_len = m->m_len;
1630 		if (iov[0].iov_len > resid)
1631 			iov[0].iov_len = resid;
1632 		uio.uio_iov = iov;
1633 		uio.uio_iovcnt = 1;
1634 		uio.uio_offset = 0;
1635 		uio.uio_resid = iov[0].iov_len;
1636 		uio.uio_segflg = UIO_SYSSPACE;
1637 		uio.uio_rw = UIO_WRITE;
1638 		error = uiomove_fromphys(ps->pages, offset + copied,
1639 		    uio.uio_resid, &uio);
1640 		MPASS(error == 0 && uio.uio_resid == 0);
1641 		copied += uio.uio_offset;
1642 		resid -= uio.uio_offset;
1643 		m = m->m_next;
1644 	}
1645 	if (copied != 0) {
1646 		sbdrop_locked(sb, copied);
1647 		job->aio_received += copied;
1648 		job->msgrcv = 1;
1649 		copied = job->aio_received;
1650 		inp = sotoinpcb(so);
1651 		if (!INP_TRY_WLOCK(inp)) {
1652 			/*
1653 			 * The reference on the socket file descriptor in
1654 			 * the AIO job should keep 'sb' and 'inp' stable.
1655 			 * Our caller has a reference on the 'toep' that
1656 			 * keeps it stable.
1657 			 */
1658 			SOCKBUF_UNLOCK(sb);
1659 			DDP_UNLOCK(toep);
1660 			INP_WLOCK(inp);
1661 			DDP_LOCK(toep);
1662 			SOCKBUF_LOCK(sb);
1663 
1664 			/*
1665 			 * If the socket has been closed, we should detect
1666 			 * that and complete this request if needed on
1667 			 * the next trip around the loop.
1668 			 */
1669 		}
1670 		t4_rcvd_locked(&toep->td->tod, intotcpcb(inp));
1671 		INP_WUNLOCK(inp);
1672 		if (resid == 0 || toep->ddp_flags & DDP_DEAD) {
1673 			/*
1674 			 * We filled the entire buffer with socket
1675 			 * data, DDP is not being used, or the socket
1676 			 * is being shut down, so complete the
1677 			 * request.
1678 			 */
1679 			SOCKBUF_UNLOCK(sb);
1680 			recycle_pageset(toep, ps);
1681 			aio_complete(job, copied, 0);
1682 			toep->ddp_queueing = NULL;
1683 			goto restart;
1684 		}
1685 
1686 		/*
1687 		 * If DDP is not enabled, requeue this request and restart.
1688 		 * This will either enable DDP or wait for more data to
1689 		 * arrive on the socket buffer.
1690 		 */
1691 		if ((toep->ddp_flags & (DDP_ON | DDP_SC_REQ)) != DDP_ON) {
1692 			SOCKBUF_UNLOCK(sb);
1693 			recycle_pageset(toep, ps);
1694 			aio_ddp_requeue_one(toep, job);
1695 			toep->ddp_queueing = NULL;
1696 			goto restart;
1697 		}
1698 
1699 		/*
1700 		 * An indicate might have arrived and been added to
1701 		 * the socket buffer while it was unlocked after the
1702 		 * copy to lock the INP.  If so, restart the copy.
1703 		 */
1704 		if (sbavail(sb) != 0)
1705 			goto sbcopy;
1706 	}
1707 	SOCKBUF_UNLOCK(sb);
1708 
1709 	if (prep_pageset(sc, toep, ps) == 0) {
1710 		recycle_pageset(toep, ps);
1711 		aio_ddp_requeue_one(toep, job);
1712 		toep->ddp_queueing = NULL;
1713 
1714 		/*
1715 		 * XXX: Need to retry this later.  Mostly need a trigger
1716 		 * when page pods are freed up.
1717 		 */
1718 		printf("%s: prep_pageset failed\n", __func__);
1719 		return;
1720 	}
1721 
1722 	/* Determine which DDP buffer to use. */
1723 	if (toep->db[0].job == NULL) {
1724 		db_idx = 0;
1725 	} else {
1726 		MPASS(toep->db[1].job == NULL);
1727 		db_idx = 1;
1728 	}
1729 
1730 	ddp_flags = 0;
1731 	ddp_flags_mask = 0;
1732 	if (db_idx == 0) {
1733 		ddp_flags |= V_TF_DDP_BUF0_VALID(1);
1734 		if (so->so_state & SS_NBIO)
1735 			ddp_flags |= V_TF_DDP_BUF0_FLUSH(1);
1736 		ddp_flags_mask |= V_TF_DDP_PSH_NO_INVALIDATE0(1) |
1737 		    V_TF_DDP_PUSH_DISABLE_0(1) | V_TF_DDP_PSHF_ENABLE_0(1) |
1738 		    V_TF_DDP_BUF0_FLUSH(1) | V_TF_DDP_BUF0_VALID(1);
1739 		buf_flag = DDP_BUF0_ACTIVE;
1740 	} else {
1741 		ddp_flags |= V_TF_DDP_BUF1_VALID(1);
1742 		if (so->so_state & SS_NBIO)
1743 			ddp_flags |= V_TF_DDP_BUF1_FLUSH(1);
1744 		ddp_flags_mask |= V_TF_DDP_PSH_NO_INVALIDATE1(1) |
1745 		    V_TF_DDP_PUSH_DISABLE_1(1) | V_TF_DDP_PSHF_ENABLE_1(1) |
1746 		    V_TF_DDP_BUF1_FLUSH(1) | V_TF_DDP_BUF1_VALID(1);
1747 		buf_flag = DDP_BUF1_ACTIVE;
1748 	}
1749 	MPASS((toep->ddp_flags & buf_flag) == 0);
1750 	if ((toep->ddp_flags & (DDP_BUF0_ACTIVE | DDP_BUF1_ACTIVE)) == 0) {
1751 		MPASS(db_idx == 0);
1752 		MPASS(toep->ddp_active_id == -1);
1753 		MPASS(toep->ddp_active_count == 0);
1754 		ddp_flags_mask |= V_TF_DDP_ACTIVE_BUF(1);
1755 	}
1756 
1757 	/*
1758 	 * The TID for this connection should still be valid.  If DDP_DEAD
1759 	 * is set, SBS_CANTRCVMORE should be set, so we shouldn't be
1760 	 * this far anyway.  Even if the socket is closing on the other
1761 	 * end, the AIO job holds a reference on this end of the socket
1762 	 * which will keep it open and keep the TCP PCB attached until
1763 	 * after the job is completed.
1764 	 */
1765 	wr = mk_update_tcb_for_ddp(sc, toep, db_idx, ps, job->aio_received,
1766 	    ddp_flags, ddp_flags_mask);
1767 	if (wr == NULL) {
1768 		recycle_pageset(toep, ps);
1769 		aio_ddp_requeue_one(toep, job);
1770 		toep->ddp_queueing = NULL;
1771 
1772 		/*
1773 		 * XXX: Need a way to kick a retry here.
1774 		 *
1775 		 * XXX: We know the fixed size needed and could
1776 		 * preallocate this using a blocking request at the
1777 		 * start of the task to avoid having to handle this
1778 		 * edge case.
1779 		 */
1780 		printf("%s: mk_update_tcb_for_ddp failed\n", __func__);
1781 		return;
1782 	}
1783 
1784 	if (!aio_set_cancel_function(job, t4_aio_cancel_active)) {
1785 		free_wrqe(wr);
1786 		recycle_pageset(toep, ps);
1787 		aio_ddp_cancel_one(job);
1788 		toep->ddp_queueing = NULL;
1789 		goto restart;
1790 	}
1791 
1792 #ifdef VERBOSE_TRACES
1793 	CTR5(KTR_CXGBE, "%s: scheduling %p for DDP[%d] (flags %#lx/%#lx)",
1794 	    __func__, job, db_idx, ddp_flags, ddp_flags_mask);
1795 #endif
1796 	/* Give the chip the go-ahead. */
1797 	t4_wrq_tx(sc, wr);
1798 	db = &toep->db[db_idx];
1799 	db->cancel_pending = 0;
1800 	db->job = job;
1801 	db->ps = ps;
1802 	toep->ddp_queueing = NULL;
1803 	toep->ddp_flags |= buf_flag;
1804 	toep->ddp_active_count++;
1805 	if (toep->ddp_active_count == 1) {
1806 		MPASS(toep->ddp_active_id == -1);
1807 		toep->ddp_active_id = db_idx;
1808 		CTR2(KTR_CXGBE, "%s: ddp_active_id = %d", __func__,
1809 		    toep->ddp_active_id);
1810 	}
1811 	goto restart;
1812 }
1813 
1814 void
1815 ddp_queue_toep(struct toepcb *toep)
1816 {
1817 
1818 	DDP_ASSERT_LOCKED(toep);
1819 	if (toep->ddp_flags & DDP_TASK_ACTIVE)
1820 		return;
1821 	toep->ddp_flags |= DDP_TASK_ACTIVE;
1822 	hold_toepcb(toep);
1823 	soaio_enqueue(&toep->ddp_requeue_task);
1824 }
1825 
1826 static void
1827 aio_ddp_requeue_task(void *context, int pending)
1828 {
1829 	struct toepcb *toep = context;
1830 
1831 	DDP_LOCK(toep);
1832 	aio_ddp_requeue(toep);
1833 	toep->ddp_flags &= ~DDP_TASK_ACTIVE;
1834 	DDP_UNLOCK(toep);
1835 
1836 	free_toepcb(toep);
1837 }
1838 
1839 static void
1840 t4_aio_cancel_active(struct kaiocb *job)
1841 {
1842 	struct socket *so = job->fd_file->f_data;
1843 	struct tcpcb *tp = so_sototcpcb(so);
1844 	struct toepcb *toep = tp->t_toe;
1845 	struct adapter *sc = td_adapter(toep->td);
1846 	uint64_t valid_flag;
1847 	int i;
1848 
1849 	DDP_LOCK(toep);
1850 	if (aio_cancel_cleared(job)) {
1851 		DDP_UNLOCK(toep);
1852 		aio_ddp_cancel_one(job);
1853 		return;
1854 	}
1855 
1856 	for (i = 0; i < nitems(toep->db); i++) {
1857 		if (toep->db[i].job == job) {
1858 			/* Should only ever get one cancel request for a job. */
1859 			MPASS(toep->db[i].cancel_pending == 0);
1860 
1861 			/*
1862 			 * Invalidate this buffer.  It will be
1863 			 * cancelled or partially completed once the
1864 			 * card ACKs the invalidate.
1865 			 */
1866 			valid_flag = i == 0 ? V_TF_DDP_BUF0_VALID(1) :
1867 			    V_TF_DDP_BUF1_VALID(1);
1868 			t4_set_tcb_field(sc, toep->ctrlq, toep->tid,
1869 			    W_TCB_RX_DDP_FLAGS, valid_flag, 0, 1,
1870 			    i + DDP_BUF0_INVALIDATED,
1871 			    toep->ofld_rxq->iq.abs_id);
1872 			toep->db[i].cancel_pending = 1;
1873 			CTR2(KTR_CXGBE, "%s: request %p marked pending",
1874 			    __func__, job);
1875 			break;
1876 		}
1877 	}
1878 	DDP_UNLOCK(toep);
1879 }
1880 
1881 static void
1882 t4_aio_cancel_queued(struct kaiocb *job)
1883 {
1884 	struct socket *so = job->fd_file->f_data;
1885 	struct tcpcb *tp = so_sototcpcb(so);
1886 	struct toepcb *toep = tp->t_toe;
1887 
1888 	DDP_LOCK(toep);
1889 	if (!aio_cancel_cleared(job)) {
1890 		TAILQ_REMOVE(&toep->ddp_aiojobq, job, list);
1891 		toep->ddp_waiting_count--;
1892 		if (toep->ddp_waiting_count == 0)
1893 			ddp_queue_toep(toep);
1894 	}
1895 	CTR2(KTR_CXGBE, "%s: request %p cancelled", __func__, job);
1896 	DDP_UNLOCK(toep);
1897 
1898 	aio_ddp_cancel_one(job);
1899 }
1900 
1901 int
1902 t4_aio_queue_ddp(struct socket *so, struct kaiocb *job)
1903 {
1904 	struct tcpcb *tp = so_sototcpcb(so);
1905 	struct toepcb *toep = tp->t_toe;
1906 
1907 
1908 	/* Ignore writes. */
1909 	if (job->uaiocb.aio_lio_opcode != LIO_READ)
1910 		return (EOPNOTSUPP);
1911 
1912 	DDP_LOCK(toep);
1913 
1914 	/*
1915 	 * XXX: Think about possibly returning errors for ENOTCONN,
1916 	 * etc.  Perhaps the caller would only queue the request
1917 	 * if it failed with EOPNOTSUPP?
1918 	 */
1919 
1920 #ifdef VERBOSE_TRACES
1921 	CTR2(KTR_CXGBE, "%s: queueing %p", __func__, job);
1922 #endif
1923 	if (!aio_set_cancel_function(job, t4_aio_cancel_queued))
1924 		panic("new job was cancelled");
1925 	TAILQ_INSERT_TAIL(&toep->ddp_aiojobq, job, list);
1926 	toep->ddp_waiting_count++;
1927 	toep->ddp_flags |= DDP_OK;
1928 
1929 	/*
1930 	 * Try to handle this request synchronously.  If this has
1931 	 * to block because the task is running, it will just bail
1932 	 * and let the task handle it instead.
1933 	 */
1934 	aio_ddp_requeue(toep);
1935 	DDP_UNLOCK(toep);
1936 	return (0);
1937 }
1938 
1939 int
1940 t4_ddp_mod_load(void)
1941 {
1942 
1943 	t4_register_cpl_handler(CPL_RX_DATA_DDP, do_rx_data_ddp);
1944 	t4_register_cpl_handler(CPL_RX_DDP_COMPLETE, do_rx_ddp_complete);
1945 	TAILQ_INIT(&ddp_orphan_pagesets);
1946 	mtx_init(&ddp_orphan_pagesets_lock, "ddp orphans", NULL, MTX_DEF);
1947 	TASK_INIT(&ddp_orphan_task, 0, ddp_free_orphan_pagesets, NULL);
1948 	return (0);
1949 }
1950 
1951 void
1952 t4_ddp_mod_unload(void)
1953 {
1954 
1955 	taskqueue_drain(taskqueue_thread, &ddp_orphan_task);
1956 	MPASS(TAILQ_EMPTY(&ddp_orphan_pagesets));
1957 	mtx_destroy(&ddp_orphan_pagesets_lock);
1958 	t4_register_cpl_handler(CPL_RX_DATA_DDP, NULL);
1959 	t4_register_cpl_handler(CPL_RX_DDP_COMPLETE, NULL);
1960 }
1961 #endif
1962