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