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