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