]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/staging/rdma/hfi1/user_sdma.c
Merge tag 'iio-for-4.4b' of git://git.kernel.org/pub/scm/linux/kernel/git/jic23/iio...
[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                 goto pq_nomem;
383
384         memsize = sizeof(*pq->reqs) * hfi1_sdma_comp_ring_size;
385         pq->reqs = kmalloc(memsize, GFP_KERNEL);
386         if (!pq->reqs)
387                 goto pq_reqs_nomem;
388
389         INIT_LIST_HEAD(&pq->list);
390         pq->dd = dd;
391         pq->ctxt = uctxt->ctxt;
392         pq->subctxt = subctxt_fp(fp);
393         pq->n_max_reqs = hfi1_sdma_comp_ring_size;
394         pq->state = SDMA_PKT_Q_INACTIVE;
395         atomic_set(&pq->n_reqs, 0);
396
397         iowait_init(&pq->busy, 0, NULL, defer_packet_queue,
398                     activate_packet_queue);
399         pq->reqidx = 0;
400         snprintf(buf, 64, "txreq-kmem-cache-%u-%u-%u", dd->unit, uctxt->ctxt,
401                  subctxt_fp(fp));
402         pq->txreq_cache = kmem_cache_create(buf,
403                                sizeof(struct user_sdma_txreq),
404                                             L1_CACHE_BYTES,
405                                             SLAB_HWCACHE_ALIGN,
406                                             sdma_kmem_cache_ctor);
407         if (!pq->txreq_cache) {
408                 dd_dev_err(dd, "[%u] Failed to allocate TxReq cache\n",
409                            uctxt->ctxt);
410                 goto pq_txreq_nomem;
411         }
412         user_sdma_pkt_fp(fp) = pq;
413         cq = kzalloc(sizeof(*cq), GFP_KERNEL);
414         if (!cq)
415                 goto cq_nomem;
416
417         memsize = ALIGN(sizeof(*cq->comps) * hfi1_sdma_comp_ring_size,
418                         PAGE_SIZE);
419         cq->comps = vmalloc_user(memsize);
420         if (!cq->comps)
421                 goto cq_comps_nomem;
422
423         cq->nentries = hfi1_sdma_comp_ring_size;
424         user_sdma_comp_fp(fp) = cq;
425
426         spin_lock_irqsave(&uctxt->sdma_qlock, flags);
427         list_add(&pq->list, &uctxt->sdma_queues);
428         spin_unlock_irqrestore(&uctxt->sdma_qlock, flags);
429         goto done;
430
431 cq_comps_nomem:
432         kfree(cq);
433 cq_nomem:
434         kmem_cache_destroy(pq->txreq_cache);
435 pq_txreq_nomem:
436         kfree(pq->reqs);
437 pq_reqs_nomem:
438         kfree(pq);
439         user_sdma_pkt_fp(fp) = NULL;
440 pq_nomem:
441         ret = -ENOMEM;
442 done:
443         return ret;
444 }
445
446 int hfi1_user_sdma_free_queues(struct hfi1_filedata *fd)
447 {
448         struct hfi1_ctxtdata *uctxt = fd->uctxt;
449         struct hfi1_user_sdma_pkt_q *pq;
450         unsigned long flags;
451
452         hfi1_cdbg(SDMA, "[%u:%u:%u] Freeing user SDMA queues", uctxt->dd->unit,
453                   uctxt->ctxt, fd->subctxt);
454         pq = fd->pq;
455         if (pq) {
456                 u16 i, j;
457
458                 spin_lock_irqsave(&uctxt->sdma_qlock, flags);
459                 if (!list_empty(&pq->list))
460                         list_del_init(&pq->list);
461                 spin_unlock_irqrestore(&uctxt->sdma_qlock, flags);
462                 iowait_sdma_drain(&pq->busy);
463                 if (pq->reqs) {
464                         for (i = 0, j = 0; i < atomic_read(&pq->n_reqs) &&
465                                      j < pq->n_max_reqs; j++) {
466                                 struct user_sdma_request *req = &pq->reqs[j];
467
468                                 if (test_bit(SDMA_REQ_IN_USE, &req->flags)) {
469                                         set_comp_state(req, ERROR, -ECOMM);
470                                         user_sdma_free_request(req);
471                                         i++;
472                                 }
473                         }
474                         kfree(pq->reqs);
475                 }
476                 kmem_cache_destroy(pq->txreq_cache);
477                 kfree(pq);
478                 fd->pq = NULL;
479         }
480         if (fd->cq) {
481                 if (fd->cq->comps)
482                         vfree(fd->cq->comps);
483                 kfree(fd->cq);
484                 fd->cq = NULL;
485         }
486         return 0;
487 }
488
489 int hfi1_user_sdma_process_request(struct file *fp, struct iovec *iovec,
490                                    unsigned long dim, unsigned long *count)
491 {
492         int ret = 0, i = 0, sent;
493         struct hfi1_ctxtdata *uctxt = ctxt_fp(fp);
494         struct hfi1_user_sdma_pkt_q *pq = user_sdma_pkt_fp(fp);
495         struct hfi1_user_sdma_comp_q *cq = user_sdma_comp_fp(fp);
496         struct hfi1_devdata *dd = pq->dd;
497         unsigned long idx = 0;
498         u8 pcount = initial_pkt_count;
499         struct sdma_req_info info;
500         struct user_sdma_request *req;
501         u8 opcode, sc, vl;
502
503         if (iovec[idx].iov_len < sizeof(info) + sizeof(req->hdr)) {
504                 hfi1_cdbg(
505                    SDMA,
506                    "[%u:%u:%u] First vector not big enough for header %lu/%lu",
507                    dd->unit, uctxt->ctxt, subctxt_fp(fp),
508                    iovec[idx].iov_len, sizeof(info) + sizeof(req->hdr));
509                 ret = -EINVAL;
510                 goto done;
511         }
512         ret = copy_from_user(&info, iovec[idx].iov_base, sizeof(info));
513         if (ret) {
514                 hfi1_cdbg(SDMA, "[%u:%u:%u] Failed to copy info QW (%d)",
515                           dd->unit, uctxt->ctxt, subctxt_fp(fp), ret);
516                 ret = -EFAULT;
517                 goto done;
518         }
519         trace_hfi1_sdma_user_reqinfo(dd, uctxt->ctxt, subctxt_fp(fp),
520                                      (u16 *)&info);
521         if (cq->comps[info.comp_idx].status == QUEUED) {
522                 hfi1_cdbg(SDMA, "[%u:%u:%u] Entry %u is in QUEUED state",
523                           dd->unit, uctxt->ctxt, subctxt_fp(fp),
524                           info.comp_idx);
525                 ret = -EBADSLT;
526                 goto done;
527         }
528         if (!info.fragsize) {
529                 hfi1_cdbg(SDMA,
530                           "[%u:%u:%u:%u] Request does not specify fragsize",
531                           dd->unit, uctxt->ctxt, subctxt_fp(fp), info.comp_idx);
532                 ret = -EINVAL;
533                 goto done;
534         }
535         /*
536          * We've done all the safety checks that we can up to this point,
537          * "allocate" the request entry.
538          */
539         hfi1_cdbg(SDMA, "[%u:%u:%u] Using req/comp entry %u\n", dd->unit,
540                   uctxt->ctxt, subctxt_fp(fp), info.comp_idx);
541         req = pq->reqs + info.comp_idx;
542         memset(req, 0, sizeof(*req));
543         /* Mark the request as IN_USE before we start filling it in. */
544         set_bit(SDMA_REQ_IN_USE, &req->flags);
545         req->data_iovs = req_iovcnt(info.ctrl) - 1;
546         req->pq = pq;
547         req->cq = cq;
548         INIT_LIST_HEAD(&req->txps);
549         spin_lock_init(&req->list_lock);
550         memcpy(&req->info, &info, sizeof(info));
551
552         if (req_opcode(info.ctrl) == EXPECTED)
553                 req->data_iovs--;
554
555         if (!info.npkts || req->data_iovs > MAX_VECTORS_PER_REQ) {
556                 SDMA_DBG(req, "Too many vectors (%u/%u)", req->data_iovs,
557                          MAX_VECTORS_PER_REQ);
558                 ret = -EINVAL;
559                 goto done;
560         }
561         /* Copy the header from the user buffer */
562         ret = copy_from_user(&req->hdr, iovec[idx].iov_base + sizeof(info),
563                              sizeof(req->hdr));
564         if (ret) {
565                 SDMA_DBG(req, "Failed to copy header template (%d)", ret);
566                 ret = -EFAULT;
567                 goto free_req;
568         }
569
570         /* If Static rate control is not enabled, sanitize the header. */
571         if (!HFI1_CAP_IS_USET(STATIC_RATE_CTRL))
572                 req->hdr.pbc[2] = 0;
573
574         /* Validate the opcode. Do not trust packets from user space blindly. */
575         opcode = (be32_to_cpu(req->hdr.bth[0]) >> 24) & 0xff;
576         if ((opcode & USER_OPCODE_CHECK_MASK) !=
577              USER_OPCODE_CHECK_VAL) {
578                 SDMA_DBG(req, "Invalid opcode (%d)", opcode);
579                 ret = -EINVAL;
580                 goto free_req;
581         }
582         /*
583          * Validate the vl. Do not trust packets from user space blindly.
584          * VL comes from PBC, SC comes from LRH, and the VL needs to
585          * match the SC look up.
586          */
587         vl = (le16_to_cpu(req->hdr.pbc[0]) >> 12) & 0xF;
588         sc = (((be16_to_cpu(req->hdr.lrh[0]) >> 12) & 0xF) |
589               (((le16_to_cpu(req->hdr.pbc[1]) >> 14) & 0x1) << 4));
590         if (vl >= dd->pport->vls_operational ||
591             vl != sc_to_vlt(dd, sc)) {
592                 SDMA_DBG(req, "Invalid SC(%u)/VL(%u)", sc, vl);
593                 ret = -EINVAL;
594                 goto free_req;
595         }
596
597         /*
598          * Also should check the BTH.lnh. If it says the next header is GRH then
599          * the RXE parsing will be off and will land in the middle of the KDETH
600          * or miss it entirely.
601          */
602         if ((be16_to_cpu(req->hdr.lrh[0]) & 0x3) == HFI1_LRH_GRH) {
603                 SDMA_DBG(req, "User tried to pass in a GRH");
604                 ret = -EINVAL;
605                 goto free_req;
606         }
607
608         req->koffset = le32_to_cpu(req->hdr.kdeth.swdata[6]);
609         /* Calculate the initial TID offset based on the values of
610            KDETH.OFFSET and KDETH.OM that are passed in. */
611         req->tidoffset = KDETH_GET(req->hdr.kdeth.ver_tid_offset, OFFSET) *
612                 (KDETH_GET(req->hdr.kdeth.ver_tid_offset, OM) ?
613                  KDETH_OM_LARGE : KDETH_OM_SMALL);
614         SDMA_DBG(req, "Initial TID offset %u", req->tidoffset);
615         idx++;
616
617         /* Save all the IO vector structures */
618         while (i < req->data_iovs) {
619                 memcpy(&req->iovs[i].iov, iovec + idx++, sizeof(struct iovec));
620                 req->iovs[i].offset = 0;
621                 req->data_len += req->iovs[i++].iov.iov_len;
622         }
623         SDMA_DBG(req, "total data length %u", req->data_len);
624
625         if (pcount > req->info.npkts)
626                 pcount = req->info.npkts;
627         /*
628          * Copy any TID info
629          * User space will provide the TID info only when the
630          * request type is EXPECTED. This is true even if there is
631          * only one packet in the request and the header is already
632          * setup. The reason for the singular TID case is that the
633          * driver needs to perform safety checks.
634          */
635         if (req_opcode(req->info.ctrl) == EXPECTED) {
636                 u16 ntids = iovec[idx].iov_len / sizeof(*req->tids);
637
638                 if (!ntids || ntids > MAX_TID_PAIR_ENTRIES) {
639                         ret = -EINVAL;
640                         goto free_req;
641                 }
642                 req->tids = kcalloc(ntids, sizeof(*req->tids), GFP_KERNEL);
643                 if (!req->tids) {
644                         ret = -ENOMEM;
645                         goto free_req;
646                 }
647                 /*
648                  * We have to copy all of the tids because they may vary
649                  * in size and, therefore, the TID count might not be
650                  * equal to the pkt count. However, there is no way to
651                  * tell at this point.
652                  */
653                 ret = copy_from_user(req->tids, iovec[idx].iov_base,
654                                      ntids * sizeof(*req->tids));
655                 if (ret) {
656                         SDMA_DBG(req, "Failed to copy %d TIDs (%d)",
657                                  ntids, ret);
658                         ret = -EFAULT;
659                         goto free_req;
660                 }
661                 req->n_tids = ntids;
662                 idx++;
663         }
664
665         /* Have to select the engine */
666         req->sde = sdma_select_engine_vl(dd,
667                                          (u32)(uctxt->ctxt + subctxt_fp(fp)),
668                                          vl);
669         if (!req->sde || !sdma_running(req->sde)) {
670                 ret = -ECOMM;
671                 goto free_req;
672         }
673
674         /* We don't need an AHG entry if the request contains only one packet */
675         if (req->info.npkts > 1 && HFI1_CAP_IS_USET(SDMA_AHG)) {
676                 int ahg = sdma_ahg_alloc(req->sde);
677
678                 if (likely(ahg >= 0)) {
679                         req->ahg_idx = (u8)ahg;
680                         set_bit(SDMA_REQ_HAVE_AHG, &req->flags);
681                 }
682         }
683
684         set_comp_state(req, QUEUED, 0);
685         /* Send the first N packets in the request to buy us some time */
686         sent = user_sdma_send_pkts(req, pcount);
687         if (unlikely(sent < 0)) {
688                 if (sent != -EBUSY) {
689                         ret = sent;
690                         goto send_err;
691                 } else
692                         sent = 0;
693         }
694         atomic_inc(&pq->n_reqs);
695
696         if (sent < req->info.npkts) {
697                 /* Take the references to the user's task and mm_struct */
698                 get_task_struct(current);
699                 req->user_proc = current;
700
701                 /*
702                  * This is a somewhat blocking send implementation.
703                  * The driver will block the caller until all packets of the
704                  * request have been submitted to the SDMA engine. However, it
705                  * will not wait for send completions.
706                  */
707                 while (!test_bit(SDMA_REQ_SEND_DONE, &req->flags)) {
708                         ret = user_sdma_send_pkts(req, pcount);
709                         if (ret < 0) {
710                                 if (ret != -EBUSY)
711                                         goto send_err;
712                                 wait_event_interruptible_timeout(
713                                         pq->busy.wait_dma,
714                                         (pq->state == SDMA_PKT_Q_ACTIVE),
715                                         msecs_to_jiffies(
716                                                 SDMA_IOWAIT_TIMEOUT));
717                         }
718                 }
719
720         }
721         ret = 0;
722         *count += idx;
723         goto done;
724 send_err:
725         set_comp_state(req, ERROR, ret);
726 free_req:
727         user_sdma_free_request(req);
728 done:
729         return ret;
730 }
731
732 static inline u32 compute_data_length(struct user_sdma_request *req,
733                                             struct user_sdma_txreq *tx)
734 {
735         /*
736          * Determine the proper size of the packet data.
737          * The size of the data of the first packet is in the header
738          * template. However, it includes the header and ICRC, which need
739          * to be subtracted.
740          * The size of the remaining packets is the minimum of the frag
741          * size (MTU) or remaining data in the request.
742          */
743         u32 len;
744
745         if (!req->seqnum) {
746                 len = ((be16_to_cpu(req->hdr.lrh[2]) << 2) -
747                        (sizeof(tx->hdr) - 4));
748         } else if (req_opcode(req->info.ctrl) == EXPECTED) {
749                 u32 tidlen = EXP_TID_GET(req->tids[req->tididx], LEN) *
750                         PAGE_SIZE;
751                 /* Get the data length based on the remaining space in the
752                  * TID pair. */
753                 len = min(tidlen - req->tidoffset, (u32)req->info.fragsize);
754                 /* If we've filled up the TID pair, move to the next one. */
755                 if (unlikely(!len) && ++req->tididx < req->n_tids &&
756                     req->tids[req->tididx]) {
757                         tidlen = EXP_TID_GET(req->tids[req->tididx],
758                                              LEN) * PAGE_SIZE;
759                         req->tidoffset = 0;
760                         len = min_t(u32, tidlen, req->info.fragsize);
761                 }
762                 /* Since the TID pairs map entire pages, make sure that we
763                  * are not going to try to send more data that we have
764                  * remaining. */
765                 len = min(len, req->data_len - req->sent);
766         } else
767                 len = min(req->data_len - req->sent, (u32)req->info.fragsize);
768         SDMA_DBG(req, "Data Length = %u", len);
769         return len;
770 }
771
772 static inline u32 get_lrh_len(struct hfi1_pkt_header hdr, u32 len)
773 {
774         /* (Size of complete header - size of PBC) + 4B ICRC + data length */
775         return ((sizeof(hdr) - sizeof(hdr.pbc)) + 4 + len);
776 }
777
778 static int user_sdma_send_pkts(struct user_sdma_request *req, unsigned maxpkts)
779 {
780         int ret = 0;
781         unsigned npkts = 0;
782         struct user_sdma_txreq *tx = NULL;
783         struct hfi1_user_sdma_pkt_q *pq = NULL;
784         struct user_sdma_iovec *iovec = NULL;
785
786         if (!req->pq) {
787                 ret = -EINVAL;
788                 goto done;
789         }
790
791         pq = req->pq;
792
793         /*
794          * Check if we might have sent the entire request already
795          */
796         if (unlikely(req->seqnum == req->info.npkts)) {
797                 if (!list_empty(&req->txps))
798                         goto dosend;
799                 goto done;
800         }
801
802         if (!maxpkts || maxpkts > req->info.npkts - req->seqnum)
803                 maxpkts = req->info.npkts - req->seqnum;
804
805         while (npkts < maxpkts) {
806                 u32 datalen = 0, queued = 0, data_sent = 0;
807                 u64 iov_offset = 0;
808
809                 /*
810                  * Check whether any of the completions have come back
811                  * with errors. If so, we are not going to process any
812                  * more packets from this request.
813                  */
814                 if (test_bit(SDMA_REQ_HAS_ERROR, &req->flags)) {
815                         set_bit(SDMA_REQ_DONE_ERROR, &req->flags);
816                         ret = -EFAULT;
817                         goto done;
818                 }
819
820                 tx = kmem_cache_alloc(pq->txreq_cache, GFP_KERNEL);
821                 if (!tx) {
822                         ret = -ENOMEM;
823                         goto done;
824                 }
825                 tx->flags = 0;
826                 tx->req = req;
827                 tx->busycount = 0;
828                 tx->iovec1 = NULL;
829                 tx->iovec2 = NULL;
830
831                 if (req->seqnum == req->info.npkts - 1)
832                         tx->flags |= USER_SDMA_TXREQ_FLAGS_LAST_PKT;
833
834                 /*
835                  * Calculate the payload size - this is min of the fragment
836                  * (MTU) size or the remaining bytes in the request but only
837                  * if we have payload data.
838                  */
839                 if (req->data_len) {
840                         iovec = &req->iovs[req->iov_idx];
841                         if (ACCESS_ONCE(iovec->offset) == iovec->iov.iov_len) {
842                                 if (++req->iov_idx == req->data_iovs) {
843                                         ret = -EFAULT;
844                                         goto free_txreq;
845                                 }
846                                 iovec = &req->iovs[req->iov_idx];
847                                 WARN_ON(iovec->offset);
848                         }
849
850                         /*
851                          * This request might include only a header and no user
852                          * data, so pin pages only if there is data and it the
853                          * pages have not been pinned already.
854                          */
855                         if (unlikely(!iovec->pages && iovec->iov.iov_len)) {
856                                 ret = pin_vector_pages(req, iovec);
857                                 if (ret)
858                                         goto free_tx;
859                         }
860
861                         tx->iovec1 = iovec;
862                         datalen = compute_data_length(req, tx);
863                         if (!datalen) {
864                                 SDMA_DBG(req,
865                                          "Request has data but pkt len is 0");
866                                 ret = -EFAULT;
867                                 goto free_tx;
868                         }
869                 }
870
871                 if (test_bit(SDMA_REQ_HAVE_AHG, &req->flags)) {
872                         if (!req->seqnum) {
873                                 u16 pbclen = le16_to_cpu(req->hdr.pbc[0]);
874                                 u32 lrhlen = get_lrh_len(req->hdr, datalen);
875                                 /*
876                                  * Copy the request header into the tx header
877                                  * because the HW needs a cacheline-aligned
878                                  * address.
879                                  * This copy can be optimized out if the hdr
880                                  * member of user_sdma_request were also
881                                  * cacheline aligned.
882                                  */
883                                 memcpy(&tx->hdr, &req->hdr, sizeof(tx->hdr));
884                                 if (PBC2LRH(pbclen) != lrhlen) {
885                                         pbclen = (pbclen & 0xf000) |
886                                                 LRH2PBC(lrhlen);
887                                         tx->hdr.pbc[0] = cpu_to_le16(pbclen);
888                                 }
889                                 ret = sdma_txinit_ahg(&tx->txreq,
890                                                       SDMA_TXREQ_F_AHG_COPY,
891                                                       sizeof(tx->hdr) + datalen,
892                                                       req->ahg_idx, 0, NULL, 0,
893                                                       user_sdma_txreq_cb);
894                                 if (ret)
895                                         goto free_tx;
896                                 ret = sdma_txadd_kvaddr(pq->dd, &tx->txreq,
897                                                         &tx->hdr,
898                                                         sizeof(tx->hdr));
899                                 if (ret)
900                                         goto free_txreq;
901                         } else {
902                                 int changes;
903
904                                 changes = set_txreq_header_ahg(req, tx,
905                                                                datalen);
906                                 if (changes < 0)
907                                         goto free_tx;
908                                 sdma_txinit_ahg(&tx->txreq,
909                                                 SDMA_TXREQ_F_USE_AHG,
910                                                 datalen, req->ahg_idx, changes,
911                                                 req->ahg, sizeof(req->hdr),
912                                                 user_sdma_txreq_cb);
913                         }
914                 } else {
915                         ret = sdma_txinit(&tx->txreq, 0, sizeof(req->hdr) +
916                                           datalen, user_sdma_txreq_cb);
917                         if (ret)
918                                 goto free_tx;
919                         /*
920                          * Modify the header for this packet. This only needs
921                          * to be done if we are not going to use AHG. Otherwise,
922                          * the HW will do it based on the changes we gave it
923                          * during sdma_txinit_ahg().
924                          */
925                         ret = set_txreq_header(req, tx, datalen);
926                         if (ret)
927                                 goto free_txreq;
928                 }
929
930                 /*
931                  * If the request contains any data vectors, add up to
932                  * fragsize bytes to the descriptor.
933                  */
934                 while (queued < datalen &&
935                        (req->sent + data_sent) < req->data_len) {
936                         unsigned long base, offset;
937                         unsigned pageidx, len;
938
939                         base = (unsigned long)iovec->iov.iov_base;
940                         offset = ((base + iovec->offset + iov_offset) &
941                                   ~PAGE_MASK);
942                         pageidx = (((iovec->offset + iov_offset +
943                                      base) - (base & PAGE_MASK)) >> PAGE_SHIFT);
944                         len = offset + req->info.fragsize > PAGE_SIZE ?
945                                 PAGE_SIZE - offset : req->info.fragsize;
946                         len = min((datalen - queued), len);
947                         ret = sdma_txadd_page(pq->dd, &tx->txreq,
948                                               iovec->pages[pageidx],
949                                               offset, len);
950                         if (ret) {
951                                 dd_dev_err(pq->dd,
952                                            "SDMA txreq add page failed %d\n",
953                                            ret);
954                                 iovec_set_complete(iovec);
955                                 goto free_txreq;
956                         }
957                         iov_offset += len;
958                         queued += len;
959                         data_sent += len;
960                         if (unlikely(queued < datalen &&
961                                      pageidx == iovec->npages &&
962                                      req->iov_idx < req->data_iovs - 1)) {
963                                 iovec->offset += iov_offset;
964                                 iovec = &req->iovs[++req->iov_idx];
965                                 if (!iovec->pages) {
966                                         ret = pin_vector_pages(req, iovec);
967                                         if (ret)
968                                                 goto free_txreq;
969                                 }
970                                 iov_offset = 0;
971                                 tx->iovec2 = iovec;
972
973                         }
974                 }
975                 /*
976                  * The txreq was submitted successfully so we can update
977                  * the counters.
978                  */
979                 req->koffset += datalen;
980                 if (req_opcode(req->info.ctrl) == EXPECTED)
981                         req->tidoffset += datalen;
982                 req->sent += data_sent;
983                 if (req->data_len) {
984                         if (tx->iovec1 && !tx->iovec2)
985                                 tx->iovec1->offset += iov_offset;
986                         else if (tx->iovec2)
987                                 tx->iovec2->offset += iov_offset;
988                 }
989                 /*
990                  * It is important to increment this here as it is used to
991                  * generate the BTH.PSN and, therefore, can't be bulk-updated
992                  * outside of the loop.
993                  */
994                 tx->seqnum = req->seqnum++;
995                 list_add_tail(&tx->txreq.list, &req->txps);
996                 npkts++;
997         }
998 dosend:
999         ret = sdma_send_txlist(req->sde, &pq->busy, &req->txps);
1000         if (list_empty(&req->txps))
1001                 if (req->seqnum == req->info.npkts) {
1002                         set_bit(SDMA_REQ_SEND_DONE, &req->flags);
1003                         /*
1004                          * The txreq has already been submitted to the HW queue
1005                          * so we can free the AHG entry now. Corruption will not
1006                          * happen due to the sequential manner in which
1007                          * descriptors are processed.
1008                          */
1009                         if (test_bit(SDMA_REQ_HAVE_AHG, &req->flags))
1010                                 sdma_ahg_free(req->sde, req->ahg_idx);
1011                 }
1012         goto done;
1013 free_txreq:
1014         sdma_txclean(pq->dd, &tx->txreq);
1015 free_tx:
1016         kmem_cache_free(pq->txreq_cache, tx);
1017 done:
1018         return ret;
1019 }
1020
1021 /*
1022  * How many pages in this iovec element?
1023  */
1024 static inline int num_user_pages(const struct iovec *iov)
1025 {
1026         const unsigned long addr  = (unsigned long) iov->iov_base;
1027         const unsigned long len   = iov->iov_len;
1028         const unsigned long spage = addr & PAGE_MASK;
1029         const unsigned long epage = (addr + len - 1) & PAGE_MASK;
1030
1031         return 1 + ((epage - spage) >> PAGE_SHIFT);
1032 }
1033
1034 static int pin_vector_pages(struct user_sdma_request *req,
1035                             struct user_sdma_iovec *iovec) {
1036         int ret = 0;
1037         unsigned pinned;
1038
1039         iovec->npages = num_user_pages(&iovec->iov);
1040         iovec->pages = kcalloc(iovec->npages, sizeof(*iovec->pages),
1041                                GFP_KERNEL);
1042         if (!iovec->pages) {
1043                 SDMA_DBG(req, "Failed page array alloc");
1044                 ret = -ENOMEM;
1045                 goto done;
1046         }
1047         /* If called by the kernel thread, use the user's mm */
1048         if (current->flags & PF_KTHREAD)
1049                 use_mm(req->user_proc->mm);
1050         pinned = get_user_pages_fast(
1051                 (unsigned long)iovec->iov.iov_base,
1052                 iovec->npages, 0, iovec->pages);
1053         /* If called by the kernel thread, unuse the user's mm */
1054         if (current->flags & PF_KTHREAD)
1055                 unuse_mm(req->user_proc->mm);
1056         if (pinned != iovec->npages) {
1057                 SDMA_DBG(req, "Failed to pin pages (%u/%u)", pinned,
1058                          iovec->npages);
1059                 ret = -EFAULT;
1060                 goto pfree;
1061         }
1062         goto done;
1063 pfree:
1064         unpin_vector_pages(iovec);
1065 done:
1066         return ret;
1067 }
1068
1069 static void unpin_vector_pages(struct user_sdma_iovec *iovec)
1070 {
1071         unsigned i;
1072
1073         if (ACCESS_ONCE(iovec->offset) != iovec->iov.iov_len) {
1074                 hfi1_cdbg(SDMA,
1075                           "the complete vector has not been sent yet %llu %zu",
1076                           iovec->offset, iovec->iov.iov_len);
1077                 return;
1078         }
1079         for (i = 0; i < iovec->npages; i++)
1080                 if (iovec->pages[i])
1081                         put_page(iovec->pages[i]);
1082         kfree(iovec->pages);
1083         iovec->pages = NULL;
1084         iovec->npages = 0;
1085         iovec->offset = 0;
1086 }
1087
1088 static int check_header_template(struct user_sdma_request *req,
1089                                  struct hfi1_pkt_header *hdr, u32 lrhlen,
1090                                  u32 datalen)
1091 {
1092         /*
1093          * Perform safety checks for any type of packet:
1094          *    - transfer size is multiple of 64bytes
1095          *    - packet length is multiple of 4bytes
1096          *    - entire request length is multiple of 4bytes
1097          *    - packet length is not larger than MTU size
1098          *
1099          * These checks are only done for the first packet of the
1100          * transfer since the header is "given" to us by user space.
1101          * For the remainder of the packets we compute the values.
1102          */
1103         if (req->info.fragsize % PIO_BLOCK_SIZE ||
1104             lrhlen & 0x3 || req->data_len & 0x3  ||
1105             lrhlen > get_lrh_len(*hdr, req->info.fragsize))
1106                 return -EINVAL;
1107
1108         if (req_opcode(req->info.ctrl) == EXPECTED) {
1109                 /*
1110                  * The header is checked only on the first packet. Furthermore,
1111                  * we ensure that at least one TID entry is copied when the
1112                  * request is submitted. Therefore, we don't have to verify that
1113                  * tididx points to something sane.
1114                  */
1115                 u32 tidval = req->tids[req->tididx],
1116                         tidlen = EXP_TID_GET(tidval, LEN) * PAGE_SIZE,
1117                         tididx = EXP_TID_GET(tidval, IDX),
1118                         tidctrl = EXP_TID_GET(tidval, CTRL),
1119                         tidoff;
1120                 __le32 kval = hdr->kdeth.ver_tid_offset;
1121
1122                 tidoff = KDETH_GET(kval, OFFSET) *
1123                           (KDETH_GET(req->hdr.kdeth.ver_tid_offset, OM) ?
1124                            KDETH_OM_LARGE : KDETH_OM_SMALL);
1125                 /*
1126                  * Expected receive packets have the following
1127                  * additional checks:
1128                  *     - offset is not larger than the TID size
1129                  *     - TIDCtrl values match between header and TID array
1130                  *     - TID indexes match between header and TID array
1131                  */
1132                 if ((tidoff + datalen > tidlen) ||
1133                     KDETH_GET(kval, TIDCTRL) != tidctrl ||
1134                     KDETH_GET(kval, TID) != tididx)
1135                         return -EINVAL;
1136         }
1137         return 0;
1138 }
1139
1140 /*
1141  * Correctly set the BTH.PSN field based on type of
1142  * transfer - eager packets can just increment the PSN but
1143  * expected packets encode generation and sequence in the
1144  * BTH.PSN field so just incrementing will result in errors.
1145  */
1146 static inline u32 set_pkt_bth_psn(__be32 bthpsn, u8 expct, u32 frags)
1147 {
1148         u32 val = be32_to_cpu(bthpsn),
1149                 mask = (HFI1_CAP_IS_KSET(EXTENDED_PSN) ? 0x7fffffffull :
1150                         0xffffffull),
1151                 psn = val & mask;
1152         if (expct)
1153                 psn = (psn & ~BTH_SEQ_MASK) | ((psn + frags) & BTH_SEQ_MASK);
1154         else
1155                 psn = psn + frags;
1156         return psn & mask;
1157 }
1158
1159 static int set_txreq_header(struct user_sdma_request *req,
1160                             struct user_sdma_txreq *tx, u32 datalen)
1161 {
1162         struct hfi1_user_sdma_pkt_q *pq = req->pq;
1163         struct hfi1_pkt_header *hdr = &tx->hdr;
1164         u16 pbclen;
1165         int ret;
1166         u32 tidval = 0, lrhlen = get_lrh_len(*hdr, datalen);
1167
1168         /* Copy the header template to the request before modification */
1169         memcpy(hdr, &req->hdr, sizeof(*hdr));
1170
1171         /*
1172          * Check if the PBC and LRH length are mismatched. If so
1173          * adjust both in the header.
1174          */
1175         pbclen = le16_to_cpu(hdr->pbc[0]);
1176         if (PBC2LRH(pbclen) != lrhlen) {
1177                 pbclen = (pbclen & 0xf000) | LRH2PBC(lrhlen);
1178                 hdr->pbc[0] = cpu_to_le16(pbclen);
1179                 hdr->lrh[2] = cpu_to_be16(lrhlen >> 2);
1180                 /*
1181                  * Third packet
1182                  * This is the first packet in the sequence that has
1183                  * a "static" size that can be used for the rest of
1184                  * the packets (besides the last one).
1185                  */
1186                 if (unlikely(req->seqnum == 2)) {
1187                         /*
1188                          * From this point on the lengths in both the
1189                          * PBC and LRH are the same until the last
1190                          * packet.
1191                          * Adjust the template so we don't have to update
1192                          * every packet
1193                          */
1194                         req->hdr.pbc[0] = hdr->pbc[0];
1195                         req->hdr.lrh[2] = hdr->lrh[2];
1196                 }
1197         }
1198         /*
1199          * We only have to modify the header if this is not the
1200          * first packet in the request. Otherwise, we use the
1201          * header given to us.
1202          */
1203         if (unlikely(!req->seqnum)) {
1204                 ret = check_header_template(req, hdr, lrhlen, datalen);
1205                 if (ret)
1206                         return ret;
1207                 goto done;
1208
1209         }
1210
1211         hdr->bth[2] = cpu_to_be32(
1212                 set_pkt_bth_psn(hdr->bth[2],
1213                                 (req_opcode(req->info.ctrl) == EXPECTED),
1214                                 req->seqnum));
1215
1216         /* Set ACK request on last packet */
1217         if (unlikely(tx->flags & USER_SDMA_TXREQ_FLAGS_LAST_PKT))
1218                 hdr->bth[2] |= cpu_to_be32(1UL<<31);
1219
1220         /* Set the new offset */
1221         hdr->kdeth.swdata[6] = cpu_to_le32(req->koffset);
1222         /* Expected packets have to fill in the new TID information */
1223         if (req_opcode(req->info.ctrl) == EXPECTED) {
1224                 tidval = req->tids[req->tididx];
1225                 /*
1226                  * If the offset puts us at the end of the current TID,
1227                  * advance everything.
1228                  */
1229                 if ((req->tidoffset) == (EXP_TID_GET(tidval, LEN) *
1230                                          PAGE_SIZE)) {
1231                         req->tidoffset = 0;
1232                         /* Since we don't copy all the TIDs, all at once,
1233                          * we have to check again. */
1234                         if (++req->tididx > req->n_tids - 1 ||
1235                             !req->tids[req->tididx]) {
1236                                 return -EINVAL;
1237                         }
1238                         tidval = req->tids[req->tididx];
1239                 }
1240                 req->omfactor = EXP_TID_GET(tidval, LEN) * PAGE_SIZE >=
1241                         KDETH_OM_MAX_SIZE ? KDETH_OM_LARGE : KDETH_OM_SMALL;
1242                 /* Set KDETH.TIDCtrl based on value for this TID. */
1243                 KDETH_SET(hdr->kdeth.ver_tid_offset, TIDCTRL,
1244                           EXP_TID_GET(tidval, CTRL));
1245                 /* Set KDETH.TID based on value for this TID */
1246                 KDETH_SET(hdr->kdeth.ver_tid_offset, TID,
1247                           EXP_TID_GET(tidval, IDX));
1248                 /* Clear KDETH.SH only on the last packet */
1249                 if (unlikely(tx->flags & USER_SDMA_TXREQ_FLAGS_LAST_PKT))
1250                         KDETH_SET(hdr->kdeth.ver_tid_offset, SH, 0);
1251                 /*
1252                  * Set the KDETH.OFFSET and KDETH.OM based on size of
1253                  * transfer.
1254                  */
1255                 SDMA_DBG(req, "TID offset %ubytes %uunits om%u",
1256                          req->tidoffset, req->tidoffset / req->omfactor,
1257                          !!(req->omfactor - KDETH_OM_SMALL));
1258                 KDETH_SET(hdr->kdeth.ver_tid_offset, OFFSET,
1259                           req->tidoffset / req->omfactor);
1260                 KDETH_SET(hdr->kdeth.ver_tid_offset, OM,
1261                           !!(req->omfactor - KDETH_OM_SMALL));
1262         }
1263 done:
1264         trace_hfi1_sdma_user_header(pq->dd, pq->ctxt, pq->subctxt,
1265                                     req->info.comp_idx, hdr, tidval);
1266         return sdma_txadd_kvaddr(pq->dd, &tx->txreq, hdr, sizeof(*hdr));
1267 }
1268
1269 static int set_txreq_header_ahg(struct user_sdma_request *req,
1270                                 struct user_sdma_txreq *tx, u32 len)
1271 {
1272         int diff = 0;
1273         struct hfi1_user_sdma_pkt_q *pq = req->pq;
1274         struct hfi1_pkt_header *hdr = &req->hdr;
1275         u16 pbclen = le16_to_cpu(hdr->pbc[0]);
1276         u32 val32, tidval = 0, lrhlen = get_lrh_len(*hdr, len);
1277
1278         if (PBC2LRH(pbclen) != lrhlen) {
1279                 /* PBC.PbcLengthDWs */
1280                 AHG_HEADER_SET(req->ahg, diff, 0, 0, 12,
1281                                cpu_to_le16(LRH2PBC(lrhlen)));
1282                 /* LRH.PktLen (we need the full 16 bits due to byte swap) */
1283                 AHG_HEADER_SET(req->ahg, diff, 3, 0, 16,
1284                                cpu_to_be16(lrhlen >> 2));
1285         }
1286
1287         /*
1288          * Do the common updates
1289          */
1290         /* BTH.PSN and BTH.A */
1291         val32 = (be32_to_cpu(hdr->bth[2]) + req->seqnum) &
1292                 (HFI1_CAP_IS_KSET(EXTENDED_PSN) ? 0x7fffffff : 0xffffff);
1293         if (unlikely(tx->flags & USER_SDMA_TXREQ_FLAGS_LAST_PKT))
1294                 val32 |= 1UL << 31;
1295         AHG_HEADER_SET(req->ahg, diff, 6, 0, 16, cpu_to_be16(val32 >> 16));
1296         AHG_HEADER_SET(req->ahg, diff, 6, 16, 16, cpu_to_be16(val32 & 0xffff));
1297         /* KDETH.Offset */
1298         AHG_HEADER_SET(req->ahg, diff, 15, 0, 16,
1299                        cpu_to_le16(req->koffset & 0xffff));
1300         AHG_HEADER_SET(req->ahg, diff, 15, 16, 16,
1301                        cpu_to_le16(req->koffset >> 16));
1302         if (req_opcode(req->info.ctrl) == EXPECTED) {
1303                 __le16 val;
1304
1305                 tidval = req->tids[req->tididx];
1306
1307                 /*
1308                  * If the offset puts us at the end of the current TID,
1309                  * advance everything.
1310                  */
1311                 if ((req->tidoffset) == (EXP_TID_GET(tidval, LEN) *
1312                                          PAGE_SIZE)) {
1313                         req->tidoffset = 0;
1314                         /* Since we don't copy all the TIDs, all at once,
1315                          * we have to check again. */
1316                         if (++req->tididx > req->n_tids - 1 ||
1317                             !req->tids[req->tididx]) {
1318                                 return -EINVAL;
1319                         }
1320                         tidval = req->tids[req->tididx];
1321                 }
1322                 req->omfactor = ((EXP_TID_GET(tidval, LEN) *
1323                                   PAGE_SIZE) >=
1324                                  KDETH_OM_MAX_SIZE) ? KDETH_OM_LARGE :
1325                         KDETH_OM_SMALL;
1326                 /* KDETH.OM and KDETH.OFFSET (TID) */
1327                 AHG_HEADER_SET(req->ahg, diff, 7, 0, 16,
1328                                ((!!(req->omfactor - KDETH_OM_SMALL)) << 15 |
1329                                 ((req->tidoffset / req->omfactor) & 0x7fff)));
1330                 /* KDETH.TIDCtrl, KDETH.TID */
1331                 val = cpu_to_le16(((EXP_TID_GET(tidval, CTRL) & 0x3) << 10) |
1332                                         (EXP_TID_GET(tidval, IDX) & 0x3ff));
1333                 /* Clear KDETH.SH on last packet */
1334                 if (unlikely(tx->flags & USER_SDMA_TXREQ_FLAGS_LAST_PKT)) {
1335                         val |= cpu_to_le16(KDETH_GET(hdr->kdeth.ver_tid_offset,
1336                                                                 INTR) >> 16);
1337                         val &= cpu_to_le16(~(1U << 13));
1338                         AHG_HEADER_SET(req->ahg, diff, 7, 16, 14, val);
1339                 } else
1340                         AHG_HEADER_SET(req->ahg, diff, 7, 16, 12, val);
1341         }
1342
1343         trace_hfi1_sdma_user_header_ahg(pq->dd, pq->ctxt, pq->subctxt,
1344                                         req->info.comp_idx, req->sde->this_idx,
1345                                         req->ahg_idx, req->ahg, diff, tidval);
1346         return diff;
1347 }
1348
1349 static void user_sdma_txreq_cb(struct sdma_txreq *txreq, int status,
1350                                int drain)
1351 {
1352         struct user_sdma_txreq *tx =
1353                 container_of(txreq, struct user_sdma_txreq, txreq);
1354         struct user_sdma_request *req = tx->req;
1355         struct hfi1_user_sdma_pkt_q *pq = req ? req->pq : NULL;
1356         u64 tx_seqnum;
1357
1358         if (unlikely(!req || !pq))
1359                 return;
1360
1361         if (tx->iovec1)
1362                 iovec_may_free(tx->iovec1, unpin_vector_pages);
1363         if (tx->iovec2)
1364                 iovec_may_free(tx->iovec2, unpin_vector_pages);
1365
1366         tx_seqnum = tx->seqnum;
1367         kmem_cache_free(pq->txreq_cache, tx);
1368
1369         if (status != SDMA_TXREQ_S_OK) {
1370                 dd_dev_err(pq->dd, "SDMA completion with error %d", status);
1371                 set_comp_state(req, ERROR, status);
1372                 set_bit(SDMA_REQ_HAS_ERROR, &req->flags);
1373                 /* Do not free the request until the sender loop has ack'ed
1374                  * the error and we've seen all txreqs. */
1375                 if (tx_seqnum == ACCESS_ONCE(req->seqnum) &&
1376                     test_bit(SDMA_REQ_DONE_ERROR, &req->flags)) {
1377                         atomic_dec(&pq->n_reqs);
1378                         user_sdma_free_request(req);
1379                 }
1380         } else {
1381                 if (tx_seqnum == req->info.npkts - 1) {
1382                         /* We've sent and completed all packets in this
1383                          * request. Signal completion to the user */
1384                         atomic_dec(&pq->n_reqs);
1385                         set_comp_state(req, COMPLETE, 0);
1386                         user_sdma_free_request(req);
1387                 }
1388         }
1389         if (!atomic_read(&pq->n_reqs))
1390                 xchg(&pq->state, SDMA_PKT_Q_INACTIVE);
1391 }
1392
1393 static void user_sdma_free_request(struct user_sdma_request *req)
1394 {
1395         if (!list_empty(&req->txps)) {
1396                 struct sdma_txreq *t, *p;
1397
1398                 list_for_each_entry_safe(t, p, &req->txps, list) {
1399                         struct user_sdma_txreq *tx =
1400                                 container_of(t, struct user_sdma_txreq, txreq);
1401                         list_del_init(&t->list);
1402                         sdma_txclean(req->pq->dd, t);
1403                         kmem_cache_free(req->pq->txreq_cache, tx);
1404                 }
1405         }
1406         if (req->data_iovs) {
1407                 int i;
1408
1409                 for (i = 0; i < req->data_iovs; i++)
1410                         if (req->iovs[i].npages && req->iovs[i].pages)
1411                                 unpin_vector_pages(&req->iovs[i]);
1412         }
1413         if (req->user_proc)
1414                 put_task_struct(req->user_proc);
1415         kfree(req->tids);
1416         clear_bit(SDMA_REQ_IN_USE, &req->flags);
1417 }
1418
1419 static inline void set_comp_state(struct user_sdma_request *req,
1420                                         enum hfi1_sdma_comp_state state,
1421                                         int ret)
1422 {
1423         SDMA_DBG(req, "Setting completion status %u %d", state, ret);
1424         req->cq->comps[req->info.comp_idx].status = state;
1425         if (state == ERROR)
1426                 req->cq->comps[req->info.comp_idx].errcode = -ret;
1427         trace_hfi1_sdma_user_completion(req->pq->dd, req->pq->ctxt,
1428                                         req->pq->subctxt, req->info.comp_idx,
1429                                         state, ret);
1430 }