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