]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/staging/rdma/hfi1/user_sdma.c
Merge 4.3-rc5 into staging-next
[karo-tx-linux.git] / drivers / staging / rdma / hfi1 / user_sdma.c
1 /*
2  *
3  * This file is provided under a dual BSD/GPLv2 license.  When using or
4  * redistributing this file, you may do so under either license.
5  *
6  * GPL LICENSE SUMMARY
7  *
8  * Copyright(c) 2015 Intel Corporation.
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of version 2 of the GNU General Public License as
12  * published by the Free Software Foundation.
13  *
14  * This program is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * General Public License for more details.
18  *
19  * BSD LICENSE
20  *
21  * Copyright(c) 2015 Intel Corporation.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  *
27  *  - Redistributions of source code must retain the above copyright
28  *    notice, this list of conditions and the following disclaimer.
29  *  - Redistributions in binary form must reproduce the above copyright
30  *    notice, this list of conditions and the following disclaimer in
31  *    the documentation and/or other materials provided with the
32  *    distribution.
33  *  - Neither the name of Intel Corporation nor the names of its
34  *    contributors may be used to endorse or promote products derived
35  *    from this software without specific prior written permission.
36  *
37  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
38  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
39  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
40  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
41  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
43  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
44  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
45  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
46  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
47  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48  *
49  */
50 #include <linux/mm.h>
51 #include <linux/types.h>
52 #include <linux/device.h>
53 #include <linux/dmapool.h>
54 #include <linux/slab.h>
55 #include <linux/list.h>
56 #include <linux/highmem.h>
57 #include <linux/io.h>
58 #include <linux/uio.h>
59 #include <linux/rbtree.h>
60 #include <linux/spinlock.h>
61 #include <linux/delay.h>
62 #include <linux/kthread.h>
63 #include <linux/mmu_context.h>
64 #include <linux/module.h>
65 #include <linux/vmalloc.h>
66
67 #include "hfi.h"
68 #include "sdma.h"
69 #include "user_sdma.h"
70 #include "sdma.h"
71 #include "verbs.h"  /* for the headers */
72 #include "common.h" /* for struct hfi1_tid_info */
73 #include "trace.h"
74
75 static uint hfi1_sdma_comp_ring_size = 128;
76 module_param_named(sdma_comp_size, hfi1_sdma_comp_ring_size, uint, S_IRUGO);
77 MODULE_PARM_DESC(sdma_comp_size, "Size of User SDMA completion ring. Default: 128");
78
79 /* The maximum number of Data io vectors per message/request */
80 #define MAX_VECTORS_PER_REQ 8
81 /*
82  * Maximum number of packet to send from each message/request
83  * before moving to the next one.
84  */
85 #define MAX_PKTS_PER_QUEUE 16
86
87 #define num_pages(x) (1 + ((((x) - 1) & PAGE_MASK) >> PAGE_SHIFT))
88
89 #define req_opcode(x) \
90         (((x) >> HFI1_SDMA_REQ_OPCODE_SHIFT) & HFI1_SDMA_REQ_OPCODE_MASK)
91 #define req_version(x) \
92         (((x) >> HFI1_SDMA_REQ_VERSION_SHIFT) & HFI1_SDMA_REQ_OPCODE_MASK)
93 #define req_iovcnt(x) \
94         (((x) >> HFI1_SDMA_REQ_IOVCNT_SHIFT) & HFI1_SDMA_REQ_IOVCNT_MASK)
95
96 /* Number of BTH.PSN bits used for sequence number in expected rcvs */
97 #define BTH_SEQ_MASK 0x7ffull
98
99 /*
100  * Define fields in the KDETH header so we can update the header
101  * template.
102  */
103 #define KDETH_OFFSET_SHIFT        0
104 #define KDETH_OFFSET_MASK         0x7fff
105 #define KDETH_OM_SHIFT            15
106 #define KDETH_OM_MASK             0x1
107 #define KDETH_TID_SHIFT           16
108 #define KDETH_TID_MASK            0x3ff
109 #define KDETH_TIDCTRL_SHIFT       26
110 #define KDETH_TIDCTRL_MASK        0x3
111 #define KDETH_INTR_SHIFT          28
112 #define KDETH_INTR_MASK           0x1
113 #define KDETH_SH_SHIFT            29
114 #define KDETH_SH_MASK             0x1
115 #define KDETH_HCRC_UPPER_SHIFT    16
116 #define KDETH_HCRC_UPPER_MASK     0xff
117 #define KDETH_HCRC_LOWER_SHIFT    24
118 #define KDETH_HCRC_LOWER_MASK     0xff
119
120 #define PBC2LRH(x) ((((x) & 0xfff) << 2) - 4)
121 #define LRH2PBC(x) ((((x) >> 2) + 1) & 0xfff)
122
123 #define KDETH_GET(val, field)                                           \
124         (((le32_to_cpu((val))) >> KDETH_##field##_SHIFT) & KDETH_##field##_MASK)
125 #define KDETH_SET(dw, field, val) do {                                  \
126                 u32 dwval = le32_to_cpu(dw);                            \
127                 dwval &= ~(KDETH_##field##_MASK << KDETH_##field##_SHIFT); \
128                 dwval |= (((val) & KDETH_##field##_MASK) << \
129                           KDETH_##field##_SHIFT);                       \
130                 dw = cpu_to_le32(dwval);                                \
131         } while (0)
132
133 #define AHG_HEADER_SET(arr, idx, dw, bit, width, value)                 \
134         do {                                                            \
135                 if ((idx) < ARRAY_SIZE((arr)))                          \
136                         (arr)[(idx++)] = sdma_build_ahg_descriptor(     \
137                                 (__force u16)(value), (dw), (bit),      \
138                                                         (width));       \
139                 else                                                    \
140                         return -ERANGE;                                 \
141         } while (0)
142
143 /* KDETH OM multipliers and switch over point */
144 #define KDETH_OM_SMALL     4
145 #define KDETH_OM_LARGE     64
146 #define KDETH_OM_MAX_SIZE  (1 << ((KDETH_OM_LARGE / KDETH_OM_SMALL) + 1))
147
148 /* Last packet in the request */
149 #define USER_SDMA_TXREQ_FLAGS_LAST_PKT   (1 << 0)
150
151 #define SDMA_REQ_IN_USE     0
152 #define SDMA_REQ_FOR_THREAD 1
153 #define SDMA_REQ_SEND_DONE  2
154 #define SDMA_REQ_HAVE_AHG   3
155 #define SDMA_REQ_HAS_ERROR  4
156 #define SDMA_REQ_DONE_ERROR 5
157
158 #define SDMA_PKT_Q_INACTIVE (1 << 0)
159 #define SDMA_PKT_Q_ACTIVE   (1 << 1)
160 #define SDMA_PKT_Q_DEFERRED (1 << 2)
161
162 /*
163  * Maximum retry attempts to submit a TX request
164  * before putting the process to sleep.
165  */
166 #define MAX_DEFER_RETRY_COUNT 1
167
168 static unsigned initial_pkt_count = 8;
169
170 #define SDMA_IOWAIT_TIMEOUT 1000 /* in milliseconds */
171
172 struct user_sdma_iovec {
173         struct iovec iov;
174         /* number of pages in this vector */
175         unsigned npages;
176         /* array of pinned pages for this vector */
177         struct page **pages;
178         /* offset into the virtual address space of the vector at
179          * which we last left off. */
180         u64 offset;
181 };
182
183 struct user_sdma_request {
184         struct sdma_req_info info;
185         struct hfi1_user_sdma_pkt_q *pq;
186         struct hfi1_user_sdma_comp_q *cq;
187         /* This is the original header from user space */
188         struct hfi1_pkt_header hdr;
189         /*
190          * Pointer to the SDMA engine for this request.
191          * Since different request could be on different VLs,
192          * each request will need it's own engine pointer.
193          */
194         struct sdma_engine *sde;
195         u8 ahg_idx;
196         u32 ahg[9];
197         /*
198          * KDETH.Offset (Eager) field
199          * We need to remember the initial value so the headers
200          * can be updated properly.
201          */
202         u32 koffset;
203         /*
204          * KDETH.OFFSET (TID) field
205          * The offset can cover multiple packets, depending on the
206          * size of the TID entry.
207          */
208         u32 tidoffset;
209         /*
210          * KDETH.OM
211          * Remember this because the header template always sets it
212          * to 0.
213          */
214         u8 omfactor;
215         /*
216          * pointer to the user's task_struct. We are going to
217          * get a reference to it so we can process io vectors
218          * at a later time.
219          */
220         struct task_struct *user_proc;
221         /*
222          * pointer to the user's mm_struct. We are going to
223          * get a reference to it so it doesn't get freed
224          * since we might not be in process context when we
225          * are processing the iov's.
226          * Using this mm_struct, we can get vma based on the
227          * iov's address (find_vma()).
228          */
229         struct mm_struct *user_mm;
230         /*
231          * We copy the iovs for this request (based on
232          * info.iovcnt). These are only the data vectors
233          */
234         unsigned data_iovs;
235         /* total length of the data in the request */
236         u32 data_len;
237         /* progress index moving along the iovs array */
238         unsigned iov_idx;
239         struct user_sdma_iovec iovs[MAX_VECTORS_PER_REQ];
240         /* number of elements copied to the tids array */
241         u16 n_tids;
242         /* TID array values copied from the tid_iov vector */
243         u32 *tids;
244         u16 tididx;
245         u32 sent;
246         u64 seqnum;
247         spinlock_t list_lock;
248         struct list_head txps;
249         unsigned long flags;
250 };
251
252 struct user_sdma_txreq {
253         /* Packet header for the txreq */
254         struct hfi1_pkt_header hdr;
255         struct sdma_txreq txreq;
256         struct user_sdma_request *req;
257         struct user_sdma_iovec *iovec1;
258         struct user_sdma_iovec *iovec2;
259         u16 flags;
260         unsigned busycount;
261         u64 seqnum;
262 };
263
264 #define SDMA_DBG(req, fmt, ...)                              \
265         hfi1_cdbg(SDMA, "[%u:%u:%u:%u] " fmt, (req)->pq->dd->unit, \
266                  (req)->pq->ctxt, (req)->pq->subctxt, (req)->info.comp_idx, \
267                  ##__VA_ARGS__)
268 #define SDMA_Q_DBG(pq, fmt, ...)                         \
269         hfi1_cdbg(SDMA, "[%u:%u:%u] " fmt, (pq)->dd->unit, (pq)->ctxt, \
270                  (pq)->subctxt, ##__VA_ARGS__)
271
272 static int user_sdma_send_pkts(struct user_sdma_request *, unsigned);
273 static int num_user_pages(const struct iovec *);
274 static void user_sdma_txreq_cb(struct sdma_txreq *, int, int);
275 static void user_sdma_free_request(struct user_sdma_request *);
276 static int pin_vector_pages(struct user_sdma_request *,
277                             struct user_sdma_iovec *);
278 static void unpin_vector_pages(struct user_sdma_iovec *);
279 static int check_header_template(struct user_sdma_request *,
280                                  struct hfi1_pkt_header *, u32, u32);
281 static int set_txreq_header(struct user_sdma_request *,
282                             struct user_sdma_txreq *, u32);
283 static int set_txreq_header_ahg(struct user_sdma_request *,
284                                 struct user_sdma_txreq *, u32);
285 static inline void set_comp_state(struct user_sdma_request *,
286                                         enum hfi1_sdma_comp_state, int);
287 static inline u32 set_pkt_bth_psn(__be32, u8, u32);
288 static inline u32 get_lrh_len(struct hfi1_pkt_header, u32 len);
289
290 static int defer_packet_queue(
291         struct sdma_engine *,
292         struct iowait *,
293         struct sdma_txreq *,
294         unsigned seq);
295 static void activate_packet_queue(struct iowait *, int);
296
297 static inline int iovec_may_free(struct user_sdma_iovec *iovec,
298                                        void (*free)(struct user_sdma_iovec *))
299 {
300         if (ACCESS_ONCE(iovec->offset) == iovec->iov.iov_len) {
301                 free(iovec);
302                 return 1;
303         }
304         return 0;
305 }
306
307 static inline void iovec_set_complete(struct user_sdma_iovec *iovec)
308 {
309         iovec->offset = iovec->iov.iov_len;
310 }
311
312 static int defer_packet_queue(
313         struct sdma_engine *sde,
314         struct iowait *wait,
315         struct sdma_txreq *txreq,
316         unsigned seq)
317 {
318         struct hfi1_user_sdma_pkt_q *pq =
319                 container_of(wait, struct hfi1_user_sdma_pkt_q, busy);
320         struct hfi1_ibdev *dev = &pq->dd->verbs_dev;
321         struct user_sdma_txreq *tx =
322                 container_of(txreq, struct user_sdma_txreq, txreq);
323
324         if (sdma_progress(sde, seq, txreq)) {
325                 if (tx->busycount++ < MAX_DEFER_RETRY_COUNT)
326                         goto eagain;
327         }
328         /*
329          * We are assuming that if the list is enqueued somewhere, it
330          * is to the dmawait list since that is the only place where
331          * it is supposed to be enqueued.
332          */
333         xchg(&pq->state, SDMA_PKT_Q_DEFERRED);
334         write_seqlock(&dev->iowait_lock);
335         if (list_empty(&pq->busy.list))
336                 list_add_tail(&pq->busy.list, &sde->dmawait);
337         write_sequnlock(&dev->iowait_lock);
338         return -EBUSY;
339 eagain:
340         return -EAGAIN;
341 }
342
343 static void activate_packet_queue(struct iowait *wait, int reason)
344 {
345         struct hfi1_user_sdma_pkt_q *pq =
346                 container_of(wait, struct hfi1_user_sdma_pkt_q, busy);
347         xchg(&pq->state, SDMA_PKT_Q_ACTIVE);
348         wake_up(&wait->wait_dma);
349 };
350
351 static void sdma_kmem_cache_ctor(void *obj)
352 {
353         struct user_sdma_txreq *tx = (struct user_sdma_txreq *)obj;
354
355         memset(tx, 0, sizeof(*tx));
356 }
357
358 int hfi1_user_sdma_alloc_queues(struct hfi1_ctxtdata *uctxt, struct file *fp)
359 {
360         int ret = 0;
361         unsigned memsize;
362         char buf[64];
363         struct hfi1_devdata *dd;
364         struct hfi1_user_sdma_comp_q *cq;
365         struct hfi1_user_sdma_pkt_q *pq;
366         unsigned long flags;
367
368         if (!uctxt || !fp) {
369                 ret = -EBADF;
370                 goto done;
371         }
372
373         if (!hfi1_sdma_comp_ring_size) {
374                 ret = -EINVAL;
375                 goto done;
376         }
377
378         dd = uctxt->dd;
379
380         pq = kzalloc(sizeof(*pq), GFP_KERNEL);
381         if (!pq) {
382                 dd_dev_err(dd,
383                            "[%u:%u] Failed to allocate SDMA request struct\n",
384                            uctxt->ctxt, subctxt_fp(fp));
385                 goto pq_nomem;
386         }
387         memsize = sizeof(*pq->reqs) * hfi1_sdma_comp_ring_size;
388         pq->reqs = kmalloc(memsize, GFP_KERNEL);
389         if (!pq->reqs) {
390                 dd_dev_err(dd,
391                            "[%u:%u] Failed to allocate SDMA request queue (%u)\n",
392                            uctxt->ctxt, subctxt_fp(fp), memsize);
393                 goto pq_reqs_nomem;
394         }
395         INIT_LIST_HEAD(&pq->list);
396         pq->dd = dd;
397         pq->ctxt = uctxt->ctxt;
398         pq->subctxt = subctxt_fp(fp);
399         pq->n_max_reqs = hfi1_sdma_comp_ring_size;
400         pq->state = SDMA_PKT_Q_INACTIVE;
401         atomic_set(&pq->n_reqs, 0);
402
403         iowait_init(&pq->busy, 0, NULL, defer_packet_queue,
404                     activate_packet_queue);
405         pq->reqidx = 0;
406         snprintf(buf, 64, "txreq-kmem-cache-%u-%u-%u", dd->unit, uctxt->ctxt,
407                  subctxt_fp(fp));
408         pq->txreq_cache = kmem_cache_create(buf,
409                                sizeof(struct user_sdma_txreq),
410                                             L1_CACHE_BYTES,
411                                             SLAB_HWCACHE_ALIGN,
412                                             sdma_kmem_cache_ctor);
413         if (!pq->txreq_cache) {
414                 dd_dev_err(dd, "[%u] Failed to allocate TxReq cache\n",
415                            uctxt->ctxt);
416                 goto pq_txreq_nomem;
417         }
418         user_sdma_pkt_fp(fp) = pq;
419         cq = kzalloc(sizeof(*cq), GFP_KERNEL);
420         if (!cq) {
421                 dd_dev_err(dd,
422                            "[%u:%u] Failed to allocate SDMA completion queue\n",
423                            uctxt->ctxt, subctxt_fp(fp));
424                 goto cq_nomem;
425         }
426
427         memsize = ALIGN(sizeof(*cq->comps) * hfi1_sdma_comp_ring_size,
428                         PAGE_SIZE);
429         cq->comps = vmalloc_user(memsize);
430         if (!cq->comps) {
431                 dd_dev_err(dd,
432                       "[%u:%u] Failed to allocate SDMA completion queue entries\n",
433                       uctxt->ctxt, subctxt_fp(fp));
434                 goto cq_comps_nomem;
435         }
436         cq->nentries = hfi1_sdma_comp_ring_size;
437         user_sdma_comp_fp(fp) = cq;
438
439         spin_lock_irqsave(&uctxt->sdma_qlock, flags);
440         list_add(&pq->list, &uctxt->sdma_queues);
441         spin_unlock_irqrestore(&uctxt->sdma_qlock, flags);
442         goto done;
443
444 cq_comps_nomem:
445         kfree(cq);
446 cq_nomem:
447         kmem_cache_destroy(pq->txreq_cache);
448 pq_txreq_nomem:
449         kfree(pq->reqs);
450 pq_reqs_nomem:
451         kfree(pq);
452         user_sdma_pkt_fp(fp) = NULL;
453 pq_nomem:
454         ret = -ENOMEM;
455 done:
456         return ret;
457 }
458
459 int hfi1_user_sdma_free_queues(struct hfi1_filedata *fd)
460 {
461         struct hfi1_ctxtdata *uctxt = fd->uctxt;
462         struct hfi1_user_sdma_pkt_q *pq;
463         unsigned long flags;
464
465         hfi1_cdbg(SDMA, "[%u:%u:%u] Freeing user SDMA queues", uctxt->dd->unit,
466                   uctxt->ctxt, fd->subctxt);
467         pq = fd->pq;
468         if (pq) {
469                 u16 i, j;
470
471                 spin_lock_irqsave(&uctxt->sdma_qlock, flags);
472                 if (!list_empty(&pq->list))
473                         list_del_init(&pq->list);
474                 spin_unlock_irqrestore(&uctxt->sdma_qlock, flags);
475                 iowait_sdma_drain(&pq->busy);
476                 if (pq->reqs) {
477                         for (i = 0, j = 0; i < atomic_read(&pq->n_reqs) &&
478                                      j < pq->n_max_reqs; j++) {
479                                 struct user_sdma_request *req = &pq->reqs[j];
480
481                                 if (test_bit(SDMA_REQ_IN_USE, &req->flags)) {
482                                         set_comp_state(req, ERROR, -ECOMM);
483                                         user_sdma_free_request(req);
484                                         i++;
485                                 }
486                         }
487                         kfree(pq->reqs);
488                 }
489                 kmem_cache_destroy(pq->txreq_cache);
490                 kfree(pq);
491                 fd->pq = NULL;
492         }
493         if (fd->cq) {
494                 if (fd->cq->comps)
495                         vfree(fd->cq->comps);
496                 kfree(fd->cq);
497                 fd->cq = NULL;
498         }
499         return 0;
500 }
501
502 int hfi1_user_sdma_process_request(struct file *fp, struct iovec *iovec,
503                                    unsigned long dim, unsigned long *count)
504 {
505         int ret = 0, i = 0, sent;
506         struct hfi1_ctxtdata *uctxt = ctxt_fp(fp);
507         struct hfi1_user_sdma_pkt_q *pq = user_sdma_pkt_fp(fp);
508         struct hfi1_user_sdma_comp_q *cq = user_sdma_comp_fp(fp);
509         struct hfi1_devdata *dd = pq->dd;
510         unsigned long idx = 0;
511         u8 pcount = initial_pkt_count;
512         struct sdma_req_info info;
513         struct user_sdma_request *req;
514         u8 opcode, sc, vl;
515
516         if (iovec[idx].iov_len < sizeof(info) + sizeof(req->hdr)) {
517                 hfi1_cdbg(
518                    SDMA,
519                    "[%u:%u:%u] First vector not big enough for header %lu/%lu",
520                    dd->unit, uctxt->ctxt, subctxt_fp(fp),
521                    iovec[idx].iov_len, sizeof(info) + sizeof(req->hdr));
522                 ret = -EINVAL;
523                 goto done;
524         }
525         ret = copy_from_user(&info, iovec[idx].iov_base, sizeof(info));
526         if (ret) {
527                 hfi1_cdbg(SDMA, "[%u:%u:%u] Failed to copy info QW (%d)",
528                           dd->unit, uctxt->ctxt, subctxt_fp(fp), ret);
529                 ret = -EFAULT;
530                 goto done;
531         }
532         trace_hfi1_sdma_user_reqinfo(dd, uctxt->ctxt, subctxt_fp(fp),
533                                      (u16 *)&info);
534         if (cq->comps[info.comp_idx].status == QUEUED) {
535                 hfi1_cdbg(SDMA, "[%u:%u:%u] Entry %u is in QUEUED state",
536                           dd->unit, uctxt->ctxt, subctxt_fp(fp),
537                           info.comp_idx);
538                 ret = -EBADSLT;
539                 goto done;
540         }
541         if (!info.fragsize) {
542                 hfi1_cdbg(SDMA,
543                           "[%u:%u:%u:%u] Request does not specify fragsize",
544                           dd->unit, uctxt->ctxt, subctxt_fp(fp), info.comp_idx);
545                 ret = -EINVAL;
546                 goto done;
547         }
548         /*
549          * We've done all the safety checks that we can up to this point,
550          * "allocate" the request entry.
551          */
552         hfi1_cdbg(SDMA, "[%u:%u:%u] Using req/comp entry %u\n", dd->unit,
553                   uctxt->ctxt, subctxt_fp(fp), info.comp_idx);
554         req = pq->reqs + info.comp_idx;
555         memset(req, 0, sizeof(*req));
556         /* Mark the request as IN_USE before we start filling it in. */
557         set_bit(SDMA_REQ_IN_USE, &req->flags);
558         req->data_iovs = req_iovcnt(info.ctrl) - 1;
559         req->pq = pq;
560         req->cq = cq;
561         INIT_LIST_HEAD(&req->txps);
562         spin_lock_init(&req->list_lock);
563         memcpy(&req->info, &info, sizeof(info));
564
565         if (req_opcode(info.ctrl) == EXPECTED)
566                 req->data_iovs--;
567
568         if (!info.npkts || req->data_iovs > MAX_VECTORS_PER_REQ) {
569                 SDMA_DBG(req, "Too many vectors (%u/%u)", req->data_iovs,
570                          MAX_VECTORS_PER_REQ);
571                 ret = -EINVAL;
572                 goto done;
573         }
574         /* Copy the header from the user buffer */
575         ret = copy_from_user(&req->hdr, iovec[idx].iov_base + sizeof(info),
576                              sizeof(req->hdr));
577         if (ret) {
578                 SDMA_DBG(req, "Failed to copy header template (%d)", ret);
579                 ret = -EFAULT;
580                 goto free_req;
581         }
582
583         /* If Static rate control is not enabled, sanitize the header. */
584         if (!HFI1_CAP_IS_USET(STATIC_RATE_CTRL))
585                 req->hdr.pbc[2] = 0;
586
587         /* Validate the opcode. Do not trust packets from user space blindly. */
588         opcode = (be32_to_cpu(req->hdr.bth[0]) >> 24) & 0xff;
589         if ((opcode & USER_OPCODE_CHECK_MASK) !=
590              USER_OPCODE_CHECK_VAL) {
591                 SDMA_DBG(req, "Invalid opcode (%d)", opcode);
592                 ret = -EINVAL;
593                 goto free_req;
594         }
595         /*
596          * Validate the vl. Do not trust packets from user space blindly.
597          * VL comes from PBC, SC comes from LRH, and the VL needs to
598          * match the SC look up.
599          */
600         vl = (le16_to_cpu(req->hdr.pbc[0]) >> 12) & 0xF;
601         sc = (((be16_to_cpu(req->hdr.lrh[0]) >> 12) & 0xF) |
602               (((le16_to_cpu(req->hdr.pbc[1]) >> 14) & 0x1) << 4));
603         if (vl >= dd->pport->vls_operational ||
604             vl != sc_to_vlt(dd, sc)) {
605                 SDMA_DBG(req, "Invalid SC(%u)/VL(%u)", sc, vl);
606                 ret = -EINVAL;
607                 goto free_req;
608         }
609
610         /*
611          * Also should check the BTH.lnh. If it says the next header is GRH then
612          * the RXE parsing will be off and will land in the middle of the KDETH
613          * or miss it entirely.
614          */
615         if ((be16_to_cpu(req->hdr.lrh[0]) & 0x3) == HFI1_LRH_GRH) {
616                 SDMA_DBG(req, "User tried to pass in a GRH");
617                 ret = -EINVAL;
618                 goto free_req;
619         }
620
621         req->koffset = le32_to_cpu(req->hdr.kdeth.swdata[6]);
622         /* Calculate the initial TID offset based on the values of
623            KDETH.OFFSET and KDETH.OM that are passed in. */
624         req->tidoffset = KDETH_GET(req->hdr.kdeth.ver_tid_offset, OFFSET) *
625                 (KDETH_GET(req->hdr.kdeth.ver_tid_offset, OM) ?
626                  KDETH_OM_LARGE : KDETH_OM_SMALL);
627         SDMA_DBG(req, "Initial TID offset %u", req->tidoffset);
628         idx++;
629
630         /* Save all the IO vector structures */
631         while (i < req->data_iovs) {
632                 memcpy(&req->iovs[i].iov, iovec + idx++, sizeof(struct iovec));
633                 req->iovs[i].offset = 0;
634                 req->data_len += req->iovs[i++].iov.iov_len;
635         }
636         SDMA_DBG(req, "total data length %u", req->data_len);
637
638         if (pcount > req->info.npkts)
639                 pcount = req->info.npkts;
640         /*
641          * Copy any TID info
642          * User space will provide the TID info only when the
643          * request type is EXPECTED. This is true even if there is
644          * only one packet in the request and the header is already
645          * setup. The reason for the singular TID case is that the
646          * driver needs to perform safety checks.
647          */
648         if (req_opcode(req->info.ctrl) == EXPECTED) {
649                 u16 ntids = iovec[idx].iov_len / sizeof(*req->tids);
650
651                 if (!ntids || ntids > MAX_TID_PAIR_ENTRIES) {
652                         ret = -EINVAL;
653                         goto free_req;
654                 }
655                 req->tids = kcalloc(ntids, sizeof(*req->tids), GFP_KERNEL);
656                 if (!req->tids) {
657                         ret = -ENOMEM;
658                         goto free_req;
659                 }
660                 /*
661                  * We have to copy all of the tids because they may vary
662                  * in size and, therefore, the TID count might not be
663                  * equal to the pkt count. However, there is no way to
664                  * tell at this point.
665                  */
666                 ret = copy_from_user(req->tids, iovec[idx].iov_base,
667                                      ntids * sizeof(*req->tids));
668                 if (ret) {
669                         SDMA_DBG(req, "Failed to copy %d TIDs (%d)",
670                                  ntids, ret);
671                         ret = -EFAULT;
672                         goto free_req;
673                 }
674                 req->n_tids = ntids;
675                 idx++;
676         }
677
678         /* Have to select the engine */
679         req->sde = sdma_select_engine_vl(dd,
680                                          (u32)(uctxt->ctxt + subctxt_fp(fp)),
681                                          vl);
682         if (!req->sde || !sdma_running(req->sde)) {
683                 ret = -ECOMM;
684                 goto free_req;
685         }
686
687         /* We don't need an AHG entry if the request contains only one packet */
688         if (req->info.npkts > 1 && HFI1_CAP_IS_USET(SDMA_AHG)) {
689                 int ahg = sdma_ahg_alloc(req->sde);
690
691                 if (likely(ahg >= 0)) {
692                         req->ahg_idx = (u8)ahg;
693                         set_bit(SDMA_REQ_HAVE_AHG, &req->flags);
694                 }
695         }
696
697         set_comp_state(req, QUEUED, 0);
698         /* Send the first N packets in the request to buy us some time */
699         sent = user_sdma_send_pkts(req, pcount);
700         if (unlikely(sent < 0)) {
701                 if (sent != -EBUSY) {
702                         ret = sent;
703                         goto send_err;
704                 } else
705                         sent = 0;
706         }
707         atomic_inc(&pq->n_reqs);
708
709         if (sent < req->info.npkts) {
710                 /* Take the references to the user's task and mm_struct */
711                 get_task_struct(current);
712                 req->user_proc = current;
713
714                 /*
715                  * This is a somewhat blocking send implementation.
716                  * The driver will block the caller until all packets of the
717                  * request have been submitted to the SDMA engine. However, it
718                  * will not wait for send completions.
719                  */
720                 while (!test_bit(SDMA_REQ_SEND_DONE, &req->flags)) {
721                         ret = user_sdma_send_pkts(req, pcount);
722                         if (ret < 0) {
723                                 if (ret != -EBUSY)
724                                         goto send_err;
725                                 wait_event_interruptible_timeout(
726                                         pq->busy.wait_dma,
727                                         (pq->state == SDMA_PKT_Q_ACTIVE),
728                                         msecs_to_jiffies(
729                                                 SDMA_IOWAIT_TIMEOUT));
730                         }
731                 }
732
733         }
734         ret = 0;
735         *count += idx;
736         goto done;
737 send_err:
738         set_comp_state(req, ERROR, ret);
739 free_req:
740         user_sdma_free_request(req);
741 done:
742         return ret;
743 }
744
745 static inline u32 compute_data_length(struct user_sdma_request *req,
746                                             struct user_sdma_txreq *tx)
747 {
748         /*
749          * Determine the proper size of the packet data.
750          * The size of the data of the first packet is in the header
751          * template. However, it includes the header and ICRC, which need
752          * to be subtracted.
753          * The size of the remaining packets is the minimum of the frag
754          * size (MTU) or remaining data in the request.
755          */
756         u32 len;
757
758         if (!req->seqnum) {
759                 len = ((be16_to_cpu(req->hdr.lrh[2]) << 2) -
760                        (sizeof(tx->hdr) - 4));
761         } else if (req_opcode(req->info.ctrl) == EXPECTED) {
762                 u32 tidlen = EXP_TID_GET(req->tids[req->tididx], LEN) *
763                         PAGE_SIZE;
764                 /* Get the data length based on the remaining space in the
765                  * TID pair. */
766                 len = min(tidlen - req->tidoffset, (u32)req->info.fragsize);
767                 /* If we've filled up the TID pair, move to the next one. */
768                 if (unlikely(!len) && ++req->tididx < req->n_tids &&
769                     req->tids[req->tididx]) {
770                         tidlen = EXP_TID_GET(req->tids[req->tididx],
771                                              LEN) * PAGE_SIZE;
772                         req->tidoffset = 0;
773                         len = min_t(u32, tidlen, req->info.fragsize);
774                 }
775                 /* Since the TID pairs map entire pages, make sure that we
776                  * are not going to try to send more data that we have
777                  * remaining. */
778                 len = min(len, req->data_len - req->sent);
779         } else
780                 len = min(req->data_len - req->sent, (u32)req->info.fragsize);
781         SDMA_DBG(req, "Data Length = %u", len);
782         return len;
783 }
784
785 static inline u32 get_lrh_len(struct hfi1_pkt_header hdr, u32 len)
786 {
787         /* (Size of complete header - size of PBC) + 4B ICRC + data length */
788         return ((sizeof(hdr) - sizeof(hdr.pbc)) + 4 + len);
789 }
790
791 static int user_sdma_send_pkts(struct user_sdma_request *req, unsigned maxpkts)
792 {
793         int ret = 0;
794         unsigned npkts = 0;
795         struct user_sdma_txreq *tx = NULL;
796         struct hfi1_user_sdma_pkt_q *pq = NULL;
797         struct user_sdma_iovec *iovec = NULL;
798
799         if (!req->pq) {
800                 ret = -EINVAL;
801                 goto done;
802         }
803
804         pq = req->pq;
805
806         /*
807          * Check if we might have sent the entire request already
808          */
809         if (unlikely(req->seqnum == req->info.npkts)) {
810                 if (!list_empty(&req->txps))
811                         goto dosend;
812                 goto done;
813         }
814
815         if (!maxpkts || maxpkts > req->info.npkts - req->seqnum)
816                 maxpkts = req->info.npkts - req->seqnum;
817
818         while (npkts < maxpkts) {
819                 u32 datalen = 0, queued = 0, data_sent = 0;
820                 u64 iov_offset = 0;
821
822                 /*
823                  * Check whether any of the completions have come back
824                  * with errors. If so, we are not going to process any
825                  * more packets from this request.
826                  */
827                 if (test_bit(SDMA_REQ_HAS_ERROR, &req->flags)) {
828                         set_bit(SDMA_REQ_DONE_ERROR, &req->flags);
829                         ret = -EFAULT;
830                         goto done;
831                 }
832
833                 tx = kmem_cache_alloc(pq->txreq_cache, GFP_KERNEL);
834                 if (!tx) {
835                         ret = -ENOMEM;
836                         goto done;
837                 }
838                 tx->flags = 0;
839                 tx->req = req;
840                 tx->busycount = 0;
841                 tx->iovec1 = NULL;
842                 tx->iovec2 = NULL;
843
844                 if (req->seqnum == req->info.npkts - 1)
845                         tx->flags |= USER_SDMA_TXREQ_FLAGS_LAST_PKT;
846
847                 /*
848                  * Calculate the payload size - this is min of the fragment
849                  * (MTU) size or the remaining bytes in the request but only
850                  * if we have payload data.
851                  */
852                 if (req->data_len) {
853                         iovec = &req->iovs[req->iov_idx];
854                         if (ACCESS_ONCE(iovec->offset) == iovec->iov.iov_len) {
855                                 if (++req->iov_idx == req->data_iovs) {
856                                         ret = -EFAULT;
857                                         goto free_txreq;
858                                 }
859                                 iovec = &req->iovs[req->iov_idx];
860                                 WARN_ON(iovec->offset);
861                         }
862
863                         /*
864                          * This request might include only a header and no user
865                          * data, so pin pages only if there is data and it the
866                          * pages have not been pinned already.
867                          */
868                         if (unlikely(!iovec->pages && iovec->iov.iov_len)) {
869                                 ret = pin_vector_pages(req, iovec);
870                                 if (ret)
871                                         goto free_tx;
872                         }
873
874                         tx->iovec1 = iovec;
875                         datalen = compute_data_length(req, tx);
876                         if (!datalen) {
877                                 SDMA_DBG(req,
878                                          "Request has data but pkt len is 0");
879                                 ret = -EFAULT;
880                                 goto free_tx;
881                         }
882                 }
883
884                 if (test_bit(SDMA_REQ_HAVE_AHG, &req->flags)) {
885                         if (!req->seqnum) {
886                                 u16 pbclen = le16_to_cpu(req->hdr.pbc[0]);
887                                 u32 lrhlen = get_lrh_len(req->hdr, datalen);
888                                 /*
889                                  * Copy the request header into the tx header
890                                  * because the HW needs a cacheline-aligned
891                                  * address.
892                                  * This copy can be optimized out if the hdr
893                                  * member of user_sdma_request were also
894                                  * cacheline aligned.
895                                  */
896                                 memcpy(&tx->hdr, &req->hdr, sizeof(tx->hdr));
897                                 if (PBC2LRH(pbclen) != lrhlen) {
898                                         pbclen = (pbclen & 0xf000) |
899                                                 LRH2PBC(lrhlen);
900                                         tx->hdr.pbc[0] = cpu_to_le16(pbclen);
901                                 }
902                                 ret = sdma_txinit_ahg(&tx->txreq,
903                                                       SDMA_TXREQ_F_AHG_COPY,
904                                                       sizeof(tx->hdr) + datalen,
905                                                       req->ahg_idx, 0, NULL, 0,
906                                                       user_sdma_txreq_cb);
907                                 if (ret)
908                                         goto free_tx;
909                                 ret = sdma_txadd_kvaddr(pq->dd, &tx->txreq,
910                                                         &tx->hdr,
911                                                         sizeof(tx->hdr));
912                                 if (ret)
913                                         goto free_txreq;
914                         } else {
915                                 int changes;
916
917                                 changes = set_txreq_header_ahg(req, tx,
918                                                                datalen);
919                                 if (changes < 0)
920                                         goto free_tx;
921                                 sdma_txinit_ahg(&tx->txreq,
922                                                 SDMA_TXREQ_F_USE_AHG,
923                                                 datalen, req->ahg_idx, changes,
924                                                 req->ahg, sizeof(req->hdr),
925                                                 user_sdma_txreq_cb);
926                         }
927                 } else {
928                         ret = sdma_txinit(&tx->txreq, 0, sizeof(req->hdr) +
929                                           datalen, user_sdma_txreq_cb);
930                         if (ret)
931                                 goto free_tx;
932                         /*
933                          * Modify the header for this packet. This only needs
934                          * to be done if we are not going to use AHG. Otherwise,
935                          * the HW will do it based on the changes we gave it
936                          * during sdma_txinit_ahg().
937                          */
938                         ret = set_txreq_header(req, tx, datalen);
939                         if (ret)
940                                 goto free_txreq;
941                 }
942
943                 /*
944                  * If the request contains any data vectors, add up to
945                  * fragsize bytes to the descriptor.
946                  */
947                 while (queued < datalen &&
948                        (req->sent + data_sent) < req->data_len) {
949                         unsigned long base, offset;
950                         unsigned pageidx, len;
951
952                         base = (unsigned long)iovec->iov.iov_base;
953                         offset = ((base + iovec->offset + iov_offset) &
954                                   ~PAGE_MASK);
955                         pageidx = (((iovec->offset + iov_offset +
956                                      base) - (base & PAGE_MASK)) >> PAGE_SHIFT);
957                         len = offset + req->info.fragsize > PAGE_SIZE ?
958                                 PAGE_SIZE - offset : req->info.fragsize;
959                         len = min((datalen - queued), len);
960                         ret = sdma_txadd_page(pq->dd, &tx->txreq,
961                                               iovec->pages[pageidx],
962                                               offset, len);
963                         if (ret) {
964                                 dd_dev_err(pq->dd,
965                                            "SDMA txreq add page failed %d\n",
966                                            ret);
967                                 iovec_set_complete(iovec);
968                                 goto free_txreq;
969                         }
970                         iov_offset += len;
971                         queued += len;
972                         data_sent += len;
973                         if (unlikely(queued < datalen &&
974                                      pageidx == iovec->npages &&
975                                      req->iov_idx < req->data_iovs - 1)) {
976                                 iovec->offset += iov_offset;
977                                 iovec = &req->iovs[++req->iov_idx];
978                                 if (!iovec->pages) {
979                                         ret = pin_vector_pages(req, iovec);
980                                         if (ret)
981                                                 goto free_txreq;
982                                 }
983                                 iov_offset = 0;
984                                 tx->iovec2 = iovec;
985
986                         }
987                 }
988                 /*
989                  * The txreq was submitted successfully so we can update
990                  * the counters.
991                  */
992                 req->koffset += datalen;
993                 if (req_opcode(req->info.ctrl) == EXPECTED)
994                         req->tidoffset += datalen;
995                 req->sent += data_sent;
996                 if (req->data_len) {
997                         if (tx->iovec1 && !tx->iovec2)
998                                 tx->iovec1->offset += iov_offset;
999                         else if (tx->iovec2)
1000                                 tx->iovec2->offset += iov_offset;
1001                 }
1002                 /*
1003                  * It is important to increment this here as it is used to
1004                  * generate the BTH.PSN and, therefore, can't be bulk-updated
1005                  * outside of the loop.
1006                  */
1007                 tx->seqnum = req->seqnum++;
1008                 list_add_tail(&tx->txreq.list, &req->txps);
1009                 npkts++;
1010         }
1011 dosend:
1012         ret = sdma_send_txlist(req->sde, &pq->busy, &req->txps);
1013         if (list_empty(&req->txps))
1014                 if (req->seqnum == req->info.npkts) {
1015                         set_bit(SDMA_REQ_SEND_DONE, &req->flags);
1016                         /*
1017                          * The txreq has already been submitted to the HW queue
1018                          * so we can free the AHG entry now. Corruption will not
1019                          * happen due to the sequential manner in which
1020                          * descriptors are processed.
1021                          */
1022                         if (test_bit(SDMA_REQ_HAVE_AHG, &req->flags))
1023                                 sdma_ahg_free(req->sde, req->ahg_idx);
1024                 }
1025         goto done;
1026 free_txreq:
1027         sdma_txclean(pq->dd, &tx->txreq);
1028 free_tx:
1029         kmem_cache_free(pq->txreq_cache, tx);
1030 done:
1031         return ret;
1032 }
1033
1034 /*
1035  * How many pages in this iovec element?
1036  */
1037 static inline int num_user_pages(const struct iovec *iov)
1038 {
1039         const unsigned long addr  = (unsigned long) iov->iov_base;
1040         const unsigned long len   = iov->iov_len;
1041         const unsigned long spage = addr & PAGE_MASK;
1042         const unsigned long epage = (addr + len - 1) & PAGE_MASK;
1043
1044         return 1 + ((epage - spage) >> PAGE_SHIFT);
1045 }
1046
1047 static int pin_vector_pages(struct user_sdma_request *req,
1048                             struct user_sdma_iovec *iovec) {
1049         int ret = 0;
1050         unsigned pinned;
1051
1052         iovec->npages = num_user_pages(&iovec->iov);
1053         iovec->pages = kzalloc(sizeof(*iovec->pages) *
1054                                iovec->npages, GFP_KERNEL);
1055         if (!iovec->pages) {
1056                 SDMA_DBG(req, "Failed page array alloc");
1057                 ret = -ENOMEM;
1058                 goto done;
1059         }
1060         /* If called by the kernel thread, use the user's mm */
1061         if (current->flags & PF_KTHREAD)
1062                 use_mm(req->user_proc->mm);
1063         pinned = get_user_pages_fast(
1064                 (unsigned long)iovec->iov.iov_base,
1065                 iovec->npages, 0, iovec->pages);
1066         /* If called by the kernel thread, unuse the user's mm */
1067         if (current->flags & PF_KTHREAD)
1068                 unuse_mm(req->user_proc->mm);
1069         if (pinned != iovec->npages) {
1070                 SDMA_DBG(req, "Failed to pin pages (%u/%u)", pinned,
1071                          iovec->npages);
1072                 ret = -EFAULT;
1073                 goto pfree;
1074         }
1075         goto done;
1076 pfree:
1077         unpin_vector_pages(iovec);
1078 done:
1079         return ret;
1080 }
1081
1082 static void unpin_vector_pages(struct user_sdma_iovec *iovec)
1083 {
1084         unsigned i;
1085
1086         if (ACCESS_ONCE(iovec->offset) != iovec->iov.iov_len) {
1087                 hfi1_cdbg(SDMA,
1088                           "the complete vector has not been sent yet %llu %zu",
1089                           iovec->offset, iovec->iov.iov_len);
1090                 return;
1091         }
1092         for (i = 0; i < iovec->npages; i++)
1093                 if (iovec->pages[i])
1094                         put_page(iovec->pages[i]);
1095         kfree(iovec->pages);
1096         iovec->pages = NULL;
1097         iovec->npages = 0;
1098         iovec->offset = 0;
1099 }
1100
1101 static int check_header_template(struct user_sdma_request *req,
1102                                  struct hfi1_pkt_header *hdr, u32 lrhlen,
1103                                  u32 datalen)
1104 {
1105         /*
1106          * Perform safety checks for any type of packet:
1107          *    - transfer size is multiple of 64bytes
1108          *    - packet length is multiple of 4bytes
1109          *    - entire request length is multiple of 4bytes
1110          *    - packet length is not larger than MTU size
1111          *
1112          * These checks are only done for the first packet of the
1113          * transfer since the header is "given" to us by user space.
1114          * For the remainder of the packets we compute the values.
1115          */
1116         if (req->info.fragsize % PIO_BLOCK_SIZE ||
1117             lrhlen & 0x3 || req->data_len & 0x3  ||
1118             lrhlen > get_lrh_len(*hdr, req->info.fragsize))
1119                 return -EINVAL;
1120
1121         if (req_opcode(req->info.ctrl) == EXPECTED) {
1122                 /*
1123                  * The header is checked only on the first packet. Furthermore,
1124                  * we ensure that at least one TID entry is copied when the
1125                  * request is submitted. Therefore, we don't have to verify that
1126                  * tididx points to something sane.
1127                  */
1128                 u32 tidval = req->tids[req->tididx],
1129                         tidlen = EXP_TID_GET(tidval, LEN) * PAGE_SIZE,
1130                         tididx = EXP_TID_GET(tidval, IDX),
1131                         tidctrl = EXP_TID_GET(tidval, CTRL),
1132                         tidoff;
1133                 __le32 kval = hdr->kdeth.ver_tid_offset;
1134
1135                 tidoff = KDETH_GET(kval, OFFSET) *
1136                           (KDETH_GET(req->hdr.kdeth.ver_tid_offset, OM) ?
1137                            KDETH_OM_LARGE : KDETH_OM_SMALL);
1138                 /*
1139                  * Expected receive packets have the following
1140                  * additional checks:
1141                  *     - offset is not larger than the TID size
1142                  *     - TIDCtrl values match between header and TID array
1143                  *     - TID indexes match between header and TID array
1144                  */
1145                 if ((tidoff + datalen > tidlen) ||
1146                     KDETH_GET(kval, TIDCTRL) != tidctrl ||
1147                     KDETH_GET(kval, TID) != tididx)
1148                         return -EINVAL;
1149         }
1150         return 0;
1151 }
1152
1153 /*
1154  * Correctly set the BTH.PSN field based on type of
1155  * transfer - eager packets can just increment the PSN but
1156  * expected packets encode generation and sequence in the
1157  * BTH.PSN field so just incrementing will result in errors.
1158  */
1159 static inline u32 set_pkt_bth_psn(__be32 bthpsn, u8 expct, u32 frags)
1160 {
1161         u32 val = be32_to_cpu(bthpsn),
1162                 mask = (HFI1_CAP_IS_KSET(EXTENDED_PSN) ? 0x7fffffffull :
1163                         0xffffffull),
1164                 psn = val & mask;
1165         if (expct)
1166                 psn = (psn & ~BTH_SEQ_MASK) | ((psn + frags) & BTH_SEQ_MASK);
1167         else
1168                 psn = psn + frags;
1169         return psn & mask;
1170 }
1171
1172 static int set_txreq_header(struct user_sdma_request *req,
1173                             struct user_sdma_txreq *tx, u32 datalen)
1174 {
1175         struct hfi1_user_sdma_pkt_q *pq = req->pq;
1176         struct hfi1_pkt_header *hdr = &tx->hdr;
1177         u16 pbclen;
1178         int ret;
1179         u32 tidval = 0, lrhlen = get_lrh_len(*hdr, datalen);
1180
1181         /* Copy the header template to the request before modification */
1182         memcpy(hdr, &req->hdr, sizeof(*hdr));
1183
1184         /*
1185          * Check if the PBC and LRH length are mismatched. If so
1186          * adjust both in the header.
1187          */
1188         pbclen = le16_to_cpu(hdr->pbc[0]);
1189         if (PBC2LRH(pbclen) != lrhlen) {
1190                 pbclen = (pbclen & 0xf000) | LRH2PBC(lrhlen);
1191                 hdr->pbc[0] = cpu_to_le16(pbclen);
1192                 hdr->lrh[2] = cpu_to_be16(lrhlen >> 2);
1193                 /*
1194                  * Third packet
1195                  * This is the first packet in the sequence that has
1196                  * a "static" size that can be used for the rest of
1197                  * the packets (besides the last one).
1198                  */
1199                 if (unlikely(req->seqnum == 2)) {
1200                         /*
1201                          * From this point on the lengths in both the
1202                          * PBC and LRH are the same until the last
1203                          * packet.
1204                          * Adjust the template so we don't have to update
1205                          * every packet
1206                          */
1207                         req->hdr.pbc[0] = hdr->pbc[0];
1208                         req->hdr.lrh[2] = hdr->lrh[2];
1209                 }
1210         }
1211         /*
1212          * We only have to modify the header if this is not the
1213          * first packet in the request. Otherwise, we use the
1214          * header given to us.
1215          */
1216         if (unlikely(!req->seqnum)) {
1217                 ret = check_header_template(req, hdr, lrhlen, datalen);
1218                 if (ret)
1219                         return ret;
1220                 goto done;
1221
1222         }
1223
1224         hdr->bth[2] = cpu_to_be32(
1225                 set_pkt_bth_psn(hdr->bth[2],
1226                                 (req_opcode(req->info.ctrl) == EXPECTED),
1227                                 req->seqnum));
1228
1229         /* Set ACK request on last packet */
1230         if (unlikely(tx->flags & USER_SDMA_TXREQ_FLAGS_LAST_PKT))
1231                 hdr->bth[2] |= cpu_to_be32(1UL<<31);
1232
1233         /* Set the new offset */
1234         hdr->kdeth.swdata[6] = cpu_to_le32(req->koffset);
1235         /* Expected packets have to fill in the new TID information */
1236         if (req_opcode(req->info.ctrl) == EXPECTED) {
1237                 tidval = req->tids[req->tididx];
1238                 /*
1239                  * If the offset puts us at the end of the current TID,
1240                  * advance everything.
1241                  */
1242                 if ((req->tidoffset) == (EXP_TID_GET(tidval, LEN) *
1243                                          PAGE_SIZE)) {
1244                         req->tidoffset = 0;
1245                         /* Since we don't copy all the TIDs, all at once,
1246                          * we have to check again. */
1247                         if (++req->tididx > req->n_tids - 1 ||
1248                             !req->tids[req->tididx]) {
1249                                 return -EINVAL;
1250                         }
1251                         tidval = req->tids[req->tididx];
1252                 }
1253                 req->omfactor = EXP_TID_GET(tidval, LEN) * PAGE_SIZE >=
1254                         KDETH_OM_MAX_SIZE ? KDETH_OM_LARGE : KDETH_OM_SMALL;
1255                 /* Set KDETH.TIDCtrl based on value for this TID. */
1256                 KDETH_SET(hdr->kdeth.ver_tid_offset, TIDCTRL,
1257                           EXP_TID_GET(tidval, CTRL));
1258                 /* Set KDETH.TID based on value for this TID */
1259                 KDETH_SET(hdr->kdeth.ver_tid_offset, TID,
1260                           EXP_TID_GET(tidval, IDX));
1261                 /* Clear KDETH.SH only on the last packet */
1262                 if (unlikely(tx->flags & USER_SDMA_TXREQ_FLAGS_LAST_PKT))
1263                         KDETH_SET(hdr->kdeth.ver_tid_offset, SH, 0);
1264                 /*
1265                  * Set the KDETH.OFFSET and KDETH.OM based on size of
1266                  * transfer.
1267                  */
1268                 SDMA_DBG(req, "TID offset %ubytes %uunits om%u",
1269                          req->tidoffset, req->tidoffset / req->omfactor,
1270                          !!(req->omfactor - KDETH_OM_SMALL));
1271                 KDETH_SET(hdr->kdeth.ver_tid_offset, OFFSET,
1272                           req->tidoffset / req->omfactor);
1273                 KDETH_SET(hdr->kdeth.ver_tid_offset, OM,
1274                           !!(req->omfactor - KDETH_OM_SMALL));
1275         }
1276 done:
1277         trace_hfi1_sdma_user_header(pq->dd, pq->ctxt, pq->subctxt,
1278                                     req->info.comp_idx, hdr, tidval);
1279         return sdma_txadd_kvaddr(pq->dd, &tx->txreq, hdr, sizeof(*hdr));
1280 }
1281
1282 static int set_txreq_header_ahg(struct user_sdma_request *req,
1283                                 struct user_sdma_txreq *tx, u32 len)
1284 {
1285         int diff = 0;
1286         struct hfi1_user_sdma_pkt_q *pq = req->pq;
1287         struct hfi1_pkt_header *hdr = &req->hdr;
1288         u16 pbclen = le16_to_cpu(hdr->pbc[0]);
1289         u32 val32, tidval = 0, lrhlen = get_lrh_len(*hdr, len);
1290
1291         if (PBC2LRH(pbclen) != lrhlen) {
1292                 /* PBC.PbcLengthDWs */
1293                 AHG_HEADER_SET(req->ahg, diff, 0, 0, 12,
1294                                cpu_to_le16(LRH2PBC(lrhlen)));
1295                 /* LRH.PktLen (we need the full 16 bits due to byte swap) */
1296                 AHG_HEADER_SET(req->ahg, diff, 3, 0, 16,
1297                                cpu_to_be16(lrhlen >> 2));
1298         }
1299
1300         /*
1301          * Do the common updates
1302          */
1303         /* BTH.PSN and BTH.A */
1304         val32 = (be32_to_cpu(hdr->bth[2]) + req->seqnum) &
1305                 (HFI1_CAP_IS_KSET(EXTENDED_PSN) ? 0x7fffffff : 0xffffff);
1306         if (unlikely(tx->flags & USER_SDMA_TXREQ_FLAGS_LAST_PKT))
1307                 val32 |= 1UL << 31;
1308         AHG_HEADER_SET(req->ahg, diff, 6, 0, 16, cpu_to_be16(val32 >> 16));
1309         AHG_HEADER_SET(req->ahg, diff, 6, 16, 16, cpu_to_be16(val32 & 0xffff));
1310         /* KDETH.Offset */
1311         AHG_HEADER_SET(req->ahg, diff, 15, 0, 16,
1312                        cpu_to_le16(req->koffset & 0xffff));
1313         AHG_HEADER_SET(req->ahg, diff, 15, 16, 16,
1314                        cpu_to_le16(req->koffset >> 16));
1315         if (req_opcode(req->info.ctrl) == EXPECTED) {
1316                 __le16 val;
1317
1318                 tidval = req->tids[req->tididx];
1319
1320                 /*
1321                  * If the offset puts us at the end of the current TID,
1322                  * advance everything.
1323                  */
1324                 if ((req->tidoffset) == (EXP_TID_GET(tidval, LEN) *
1325                                          PAGE_SIZE)) {
1326                         req->tidoffset = 0;
1327                         /* Since we don't copy all the TIDs, all at once,
1328                          * we have to check again. */
1329                         if (++req->tididx > req->n_tids - 1 ||
1330                             !req->tids[req->tididx]) {
1331                                 return -EINVAL;
1332                         }
1333                         tidval = req->tids[req->tididx];
1334                 }
1335                 req->omfactor = ((EXP_TID_GET(tidval, LEN) *
1336                                   PAGE_SIZE) >=
1337                                  KDETH_OM_MAX_SIZE) ? KDETH_OM_LARGE :
1338                         KDETH_OM_SMALL;
1339                 /* KDETH.OM and KDETH.OFFSET (TID) */
1340                 AHG_HEADER_SET(req->ahg, diff, 7, 0, 16,
1341                                ((!!(req->omfactor - KDETH_OM_SMALL)) << 15 |
1342                                 ((req->tidoffset / req->omfactor) & 0x7fff)));
1343                 /* KDETH.TIDCtrl, KDETH.TID */
1344                 val = cpu_to_le16(((EXP_TID_GET(tidval, CTRL) & 0x3) << 10) |
1345                                         (EXP_TID_GET(tidval, IDX) & 0x3ff));
1346                 /* Clear KDETH.SH on last packet */
1347                 if (unlikely(tx->flags & USER_SDMA_TXREQ_FLAGS_LAST_PKT)) {
1348                         val |= cpu_to_le16(KDETH_GET(hdr->kdeth.ver_tid_offset,
1349                                                                 INTR) >> 16);
1350                         val &= cpu_to_le16(~(1U << 13));
1351                         AHG_HEADER_SET(req->ahg, diff, 7, 16, 14, val);
1352                 } else
1353                         AHG_HEADER_SET(req->ahg, diff, 7, 16, 12, val);
1354         }
1355
1356         trace_hfi1_sdma_user_header_ahg(pq->dd, pq->ctxt, pq->subctxt,
1357                                         req->info.comp_idx, req->sde->this_idx,
1358                                         req->ahg_idx, req->ahg, diff, tidval);
1359         return diff;
1360 }
1361
1362 static void user_sdma_txreq_cb(struct sdma_txreq *txreq, int status,
1363                                int drain)
1364 {
1365         struct user_sdma_txreq *tx =
1366                 container_of(txreq, struct user_sdma_txreq, txreq);
1367         struct user_sdma_request *req = tx->req;
1368         struct hfi1_user_sdma_pkt_q *pq = req ? req->pq : NULL;
1369         u64 tx_seqnum;
1370
1371         if (unlikely(!req || !pq))
1372                 return;
1373
1374         if (tx->iovec1)
1375                 iovec_may_free(tx->iovec1, unpin_vector_pages);
1376         if (tx->iovec2)
1377                 iovec_may_free(tx->iovec2, unpin_vector_pages);
1378
1379         tx_seqnum = tx->seqnum;
1380         kmem_cache_free(pq->txreq_cache, tx);
1381
1382         if (status != SDMA_TXREQ_S_OK) {
1383                 dd_dev_err(pq->dd, "SDMA completion with error %d", status);
1384                 set_comp_state(req, ERROR, status);
1385                 set_bit(SDMA_REQ_HAS_ERROR, &req->flags);
1386                 /* Do not free the request until the sender loop has ack'ed
1387                  * the error and we've seen all txreqs. */
1388                 if (tx_seqnum == ACCESS_ONCE(req->seqnum) &&
1389                     test_bit(SDMA_REQ_DONE_ERROR, &req->flags)) {
1390                         atomic_dec(&pq->n_reqs);
1391                         user_sdma_free_request(req);
1392                 }
1393         } else {
1394                 if (tx_seqnum == req->info.npkts - 1) {
1395                         /* We've sent and completed all packets in this
1396                          * request. Signal completion to the user */
1397                         atomic_dec(&pq->n_reqs);
1398                         set_comp_state(req, COMPLETE, 0);
1399                         user_sdma_free_request(req);
1400                 }
1401         }
1402         if (!atomic_read(&pq->n_reqs))
1403                 xchg(&pq->state, SDMA_PKT_Q_INACTIVE);
1404 }
1405
1406 static void user_sdma_free_request(struct user_sdma_request *req)
1407 {
1408         if (!list_empty(&req->txps)) {
1409                 struct sdma_txreq *t, *p;
1410
1411                 list_for_each_entry_safe(t, p, &req->txps, list) {
1412                         struct user_sdma_txreq *tx =
1413                                 container_of(t, struct user_sdma_txreq, txreq);
1414                         list_del_init(&t->list);
1415                         sdma_txclean(req->pq->dd, t);
1416                         kmem_cache_free(req->pq->txreq_cache, tx);
1417                 }
1418         }
1419         if (req->data_iovs) {
1420                 int i;
1421
1422                 for (i = 0; i < req->data_iovs; i++)
1423                         if (req->iovs[i].npages && req->iovs[i].pages)
1424                                 unpin_vector_pages(&req->iovs[i]);
1425         }
1426         if (req->user_proc)
1427                 put_task_struct(req->user_proc);
1428         kfree(req->tids);
1429         clear_bit(SDMA_REQ_IN_USE, &req->flags);
1430 }
1431
1432 static inline void set_comp_state(struct user_sdma_request *req,
1433                                         enum hfi1_sdma_comp_state state,
1434                                         int ret)
1435 {
1436         SDMA_DBG(req, "Setting completion status %u %d", state, ret);
1437         req->cq->comps[req->info.comp_idx].status = state;
1438         if (state == ERROR)
1439                 req->cq->comps[req->info.comp_idx].errcode = -ret;
1440         trace_hfi1_sdma_user_completion(req->pq->dd, req->pq->ctxt,
1441                                         req->pq->subctxt, req->info.comp_idx,
1442                                         state, ret);
1443 }