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