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