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