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