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