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