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