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