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