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