GNU Linux-libre 4.19.286-gnu1
[releases.git] / drivers / infiniband / hw / hfi1 / user_exp_rcv.c
1 /*
2  * Copyright(c) 2015-2018 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 <asm/page.h>
48 #include <linux/string.h>
49
50 #include "mmu_rb.h"
51 #include "user_exp_rcv.h"
52 #include "trace.h"
53
54 static void unlock_exp_tids(struct hfi1_ctxtdata *uctxt,
55                             struct exp_tid_set *set,
56                             struct hfi1_filedata *fd);
57 static u32 find_phys_blocks(struct tid_user_buf *tidbuf, unsigned int npages);
58 static int set_rcvarray_entry(struct hfi1_filedata *fd,
59                               struct tid_user_buf *tbuf,
60                               u32 rcventry, struct tid_group *grp,
61                               u16 pageidx, unsigned int npages);
62 static int tid_rb_insert(void *arg, struct mmu_rb_node *node);
63 static void cacheless_tid_rb_remove(struct hfi1_filedata *fdata,
64                                     struct tid_rb_node *tnode);
65 static void tid_rb_remove(void *arg, struct mmu_rb_node *node);
66 static int tid_rb_invalidate(void *arg, struct mmu_rb_node *mnode);
67 static int program_rcvarray(struct hfi1_filedata *fd, struct tid_user_buf *,
68                             struct tid_group *grp,
69                             unsigned int start, u16 count,
70                             u32 *tidlist, unsigned int *tididx,
71                             unsigned int *pmapped);
72 static int unprogram_rcvarray(struct hfi1_filedata *fd, u32 tidinfo,
73                               struct tid_group **grp);
74 static void clear_tid_node(struct hfi1_filedata *fd, struct tid_rb_node *node);
75
76 static struct mmu_rb_ops tid_rb_ops = {
77         .insert = tid_rb_insert,
78         .remove = tid_rb_remove,
79         .invalidate = tid_rb_invalidate
80 };
81
82 /*
83  * Initialize context and file private data needed for Expected
84  * receive caching. This needs to be done after the context has
85  * been configured with the eager/expected RcvEntry counts.
86  */
87 int hfi1_user_exp_rcv_init(struct hfi1_filedata *fd,
88                            struct hfi1_ctxtdata *uctxt)
89 {
90         struct hfi1_devdata *dd = uctxt->dd;
91         int ret = 0;
92
93         fd->entry_to_rb = kcalloc(uctxt->expected_count,
94                                   sizeof(struct rb_node *),
95                                   GFP_KERNEL);
96         if (!fd->entry_to_rb)
97                 return -ENOMEM;
98
99         if (!HFI1_CAP_UGET_MASK(uctxt->flags, TID_UNMAP)) {
100                 fd->invalid_tid_idx = 0;
101                 fd->invalid_tids = kcalloc(uctxt->expected_count,
102                                            sizeof(*fd->invalid_tids),
103                                            GFP_KERNEL);
104                 if (!fd->invalid_tids) {
105                         kfree(fd->entry_to_rb);
106                         fd->entry_to_rb = NULL;
107                         return -ENOMEM;
108                 }
109
110                 /*
111                  * Register MMU notifier callbacks. If the registration
112                  * fails, continue without TID caching for this context.
113                  */
114                 ret = hfi1_mmu_rb_register(fd, fd->mm, &tid_rb_ops,
115                                            dd->pport->hfi1_wq,
116                                            &fd->handler);
117                 if (ret) {
118                         dd_dev_info(dd,
119                                     "Failed MMU notifier registration %d\n",
120                                     ret);
121                         ret = 0;
122                 }
123         }
124
125         /*
126          * PSM does not have a good way to separate, count, and
127          * effectively enforce a limit on RcvArray entries used by
128          * subctxts (when context sharing is used) when TID caching
129          * is enabled. To help with that, we calculate a per-process
130          * RcvArray entry share and enforce that.
131          * If TID caching is not in use, PSM deals with usage on its
132          * own. In that case, we allow any subctxt to take all of the
133          * entries.
134          *
135          * Make sure that we set the tid counts only after successful
136          * init.
137          */
138         spin_lock(&fd->tid_lock);
139         if (uctxt->subctxt_cnt && fd->handler) {
140                 u16 remainder;
141
142                 fd->tid_limit = uctxt->expected_count / uctxt->subctxt_cnt;
143                 remainder = uctxt->expected_count % uctxt->subctxt_cnt;
144                 if (remainder && fd->subctxt < remainder)
145                         fd->tid_limit++;
146         } else {
147                 fd->tid_limit = uctxt->expected_count;
148         }
149         spin_unlock(&fd->tid_lock);
150
151         return ret;
152 }
153
154 void hfi1_user_exp_rcv_free(struct hfi1_filedata *fd)
155 {
156         struct hfi1_ctxtdata *uctxt = fd->uctxt;
157
158         /*
159          * The notifier would have been removed when the process'es mm
160          * was freed.
161          */
162         if (fd->handler) {
163                 hfi1_mmu_rb_unregister(fd->handler);
164         } else {
165                 mutex_lock(&uctxt->exp_mutex);
166                 if (!EXP_TID_SET_EMPTY(uctxt->tid_full_list))
167                         unlock_exp_tids(uctxt, &uctxt->tid_full_list, fd);
168                 if (!EXP_TID_SET_EMPTY(uctxt->tid_used_list))
169                         unlock_exp_tids(uctxt, &uctxt->tid_used_list, fd);
170                 mutex_unlock(&uctxt->exp_mutex);
171         }
172
173         kfree(fd->invalid_tids);
174         fd->invalid_tids = NULL;
175
176         kfree(fd->entry_to_rb);
177         fd->entry_to_rb = NULL;
178 }
179
180 /**
181  * Release pinned receive buffer pages.
182  *
183  * @mapped - true if the pages have been DMA mapped. false otherwise.
184  * @idx - Index of the first page to unpin.
185  * @npages - No of pages to unpin.
186  *
187  * If the pages have been DMA mapped (indicated by mapped parameter), their
188  * info will be passed via a struct tid_rb_node. If they haven't been mapped,
189  * their info will be passed via a struct tid_user_buf.
190  */
191 static void unpin_rcv_pages(struct hfi1_filedata *fd,
192                             struct tid_user_buf *tidbuf,
193                             struct tid_rb_node *node,
194                             unsigned int idx,
195                             unsigned int npages,
196                             bool mapped)
197 {
198         struct page **pages;
199         struct hfi1_devdata *dd = fd->uctxt->dd;
200
201         if (mapped) {
202                 pci_unmap_single(dd->pcidev, node->dma_addr,
203                                  node->mmu.len, PCI_DMA_FROMDEVICE);
204                 pages = &node->pages[idx];
205         } else {
206                 pages = &tidbuf->pages[idx];
207         }
208         hfi1_release_user_pages(fd->mm, pages, npages, mapped);
209         fd->tid_n_pinned -= npages;
210 }
211
212 /**
213  * Pin receive buffer pages.
214  */
215 static int pin_rcv_pages(struct hfi1_filedata *fd, struct tid_user_buf *tidbuf)
216 {
217         int pinned;
218         unsigned int npages = tidbuf->npages;
219         unsigned long vaddr = tidbuf->vaddr;
220         struct page **pages = NULL;
221         struct hfi1_devdata *dd = fd->uctxt->dd;
222
223         if (npages > fd->uctxt->expected_count) {
224                 dd_dev_err(dd, "Expected buffer too big\n");
225                 return -EINVAL;
226         }
227
228         /* Verify that access is OK for the user buffer */
229         if (!access_ok(VERIFY_WRITE, (void __user *)vaddr,
230                        npages * PAGE_SIZE)) {
231                 dd_dev_err(dd, "Fail vaddr %p, %u pages, !access_ok\n",
232                            (void *)vaddr, npages);
233                 return -EFAULT;
234         }
235         /* Allocate the array of struct page pointers needed for pinning */
236         pages = kcalloc(npages, sizeof(*pages), GFP_KERNEL);
237         if (!pages)
238                 return -ENOMEM;
239
240         /*
241          * Pin all the pages of the user buffer. If we can't pin all the
242          * pages, accept the amount pinned so far and program only that.
243          * User space knows how to deal with partially programmed buffers.
244          */
245         if (!hfi1_can_pin_pages(dd, fd->mm, fd->tid_n_pinned, npages)) {
246                 kfree(pages);
247                 return -ENOMEM;
248         }
249
250         pinned = hfi1_acquire_user_pages(fd->mm, vaddr, npages, true, pages);
251         if (pinned <= 0) {
252                 kfree(pages);
253                 return pinned;
254         }
255         tidbuf->pages = pages;
256         fd->tid_n_pinned += pinned;
257         return pinned;
258 }
259
260 /*
261  * RcvArray entry allocation for Expected Receives is done by the
262  * following algorithm:
263  *
264  * The context keeps 3 lists of groups of RcvArray entries:
265  *   1. List of empty groups - tid_group_list
266  *      This list is created during user context creation and
267  *      contains elements which describe sets (of 8) of empty
268  *      RcvArray entries.
269  *   2. List of partially used groups - tid_used_list
270  *      This list contains sets of RcvArray entries which are
271  *      not completely used up. Another mapping request could
272  *      use some of all of the remaining entries.
273  *   3. List of full groups - tid_full_list
274  *      This is the list where sets that are completely used
275  *      up go.
276  *
277  * An attempt to optimize the usage of RcvArray entries is
278  * made by finding all sets of physically contiguous pages in a
279  * user's buffer.
280  * These physically contiguous sets are further split into
281  * sizes supported by the receive engine of the HFI. The
282  * resulting sets of pages are stored in struct tid_pageset,
283  * which describes the sets as:
284  *    * .count - number of pages in this set
285  *    * .idx - starting index into struct page ** array
286  *                    of this set
287  *
288  * From this point on, the algorithm deals with the page sets
289  * described above. The number of pagesets is divided by the
290  * RcvArray group size to produce the number of full groups
291  * needed.
292  *
293  * Groups from the 3 lists are manipulated using the following
294  * rules:
295  *   1. For each set of 8 pagesets, a complete group from
296  *      tid_group_list is taken, programmed, and moved to
297  *      the tid_full_list list.
298  *   2. For all remaining pagesets:
299  *      2.1 If the tid_used_list is empty and the tid_group_list
300  *          is empty, stop processing pageset and return only
301  *          what has been programmed up to this point.
302  *      2.2 If the tid_used_list is empty and the tid_group_list
303  *          is not empty, move a group from tid_group_list to
304  *          tid_used_list.
305  *      2.3 For each group is tid_used_group, program as much as
306  *          can fit into the group. If the group becomes fully
307  *          used, move it to tid_full_list.
308  */
309 int hfi1_user_exp_rcv_setup(struct hfi1_filedata *fd,
310                             struct hfi1_tid_info *tinfo)
311 {
312         int ret = 0, need_group = 0, pinned;
313         struct hfi1_ctxtdata *uctxt = fd->uctxt;
314         struct hfi1_devdata *dd = uctxt->dd;
315         unsigned int ngroups, pageidx = 0, pageset_count,
316                 tididx = 0, mapped, mapped_pages = 0;
317         u32 *tidlist = NULL;
318         struct tid_user_buf *tidbuf;
319
320         if (!PAGE_ALIGNED(tinfo->vaddr))
321                 return -EINVAL;
322         if (tinfo->length == 0)
323                 return -EINVAL;
324
325         tidbuf = kzalloc(sizeof(*tidbuf), GFP_KERNEL);
326         if (!tidbuf)
327                 return -ENOMEM;
328
329         tidbuf->vaddr = tinfo->vaddr;
330         tidbuf->length = tinfo->length;
331         tidbuf->npages = num_user_pages(tidbuf->vaddr, tidbuf->length);
332         tidbuf->psets = kcalloc(uctxt->expected_count, sizeof(*tidbuf->psets),
333                                 GFP_KERNEL);
334         if (!tidbuf->psets) {
335                 ret = -ENOMEM;
336                 goto fail_release_mem;
337         }
338
339         pinned = pin_rcv_pages(fd, tidbuf);
340         if (pinned <= 0) {
341                 ret = (pinned < 0) ? pinned : -ENOSPC;
342                 goto fail_unpin;
343         }
344
345         /* Find sets of physically contiguous pages */
346         tidbuf->n_psets = find_phys_blocks(tidbuf, pinned);
347
348         /* Reserve the number of expected tids to be used. */
349         spin_lock(&fd->tid_lock);
350         if (fd->tid_used + tidbuf->n_psets > fd->tid_limit)
351                 pageset_count = fd->tid_limit - fd->tid_used;
352         else
353                 pageset_count = tidbuf->n_psets;
354         fd->tid_used += pageset_count;
355         spin_unlock(&fd->tid_lock);
356
357         if (!pageset_count) {
358                 ret = -ENOSPC;
359                 goto fail_unreserve;
360         }
361
362         ngroups = pageset_count / dd->rcv_entries.group_size;
363         tidlist = kcalloc(pageset_count, sizeof(*tidlist), GFP_KERNEL);
364         if (!tidlist) {
365                 ret = -ENOMEM;
366                 goto fail_unreserve;
367         }
368
369         tididx = 0;
370
371         /*
372          * From this point on, we are going to be using shared (between master
373          * and subcontexts) context resources. We need to take the lock.
374          */
375         mutex_lock(&uctxt->exp_mutex);
376         /*
377          * The first step is to program the RcvArray entries which are complete
378          * groups.
379          */
380         while (ngroups && uctxt->tid_group_list.count) {
381                 struct tid_group *grp =
382                         tid_group_pop(&uctxt->tid_group_list);
383
384                 ret = program_rcvarray(fd, tidbuf, grp,
385                                        pageidx, dd->rcv_entries.group_size,
386                                        tidlist, &tididx, &mapped);
387                 /*
388                  * If there was a failure to program the RcvArray
389                  * entries for the entire group, reset the grp fields
390                  * and add the grp back to the free group list.
391                  */
392                 if (ret <= 0) {
393                         tid_group_add_tail(grp, &uctxt->tid_group_list);
394                         hfi1_cdbg(TID,
395                                   "Failed to program RcvArray group %d", ret);
396                         goto unlock;
397                 }
398
399                 tid_group_add_tail(grp, &uctxt->tid_full_list);
400                 ngroups--;
401                 pageidx += ret;
402                 mapped_pages += mapped;
403         }
404
405         while (pageidx < pageset_count) {
406                 struct tid_group *grp, *ptr;
407                 /*
408                  * If we don't have any partially used tid groups, check
409                  * if we have empty groups. If so, take one from there and
410                  * put in the partially used list.
411                  */
412                 if (!uctxt->tid_used_list.count || need_group) {
413                         if (!uctxt->tid_group_list.count)
414                                 goto unlock;
415
416                         grp = tid_group_pop(&uctxt->tid_group_list);
417                         tid_group_add_tail(grp, &uctxt->tid_used_list);
418                         need_group = 0;
419                 }
420                 /*
421                  * There is an optimization opportunity here - instead of
422                  * fitting as many page sets as we can, check for a group
423                  * later on in the list that could fit all of them.
424                  */
425                 list_for_each_entry_safe(grp, ptr, &uctxt->tid_used_list.list,
426                                          list) {
427                         unsigned use = min_t(unsigned, pageset_count - pageidx,
428                                              grp->size - grp->used);
429
430                         ret = program_rcvarray(fd, tidbuf, grp,
431                                                pageidx, use, tidlist,
432                                                &tididx, &mapped);
433                         if (ret < 0) {
434                                 hfi1_cdbg(TID,
435                                           "Failed to program RcvArray entries %d",
436                                           ret);
437                                 goto unlock;
438                         } else if (ret > 0) {
439                                 if (grp->used == grp->size)
440                                         tid_group_move(grp,
441                                                        &uctxt->tid_used_list,
442                                                        &uctxt->tid_full_list);
443                                 pageidx += ret;
444                                 mapped_pages += mapped;
445                                 need_group = 0;
446                                 /* Check if we are done so we break out early */
447                                 if (pageidx >= pageset_count)
448                                         break;
449                         } else if (WARN_ON(ret == 0)) {
450                                 /*
451                                  * If ret is 0, we did not program any entries
452                                  * into this group, which can only happen if
453                                  * we've screwed up the accounting somewhere.
454                                  * Warn and try to continue.
455                                  */
456                                 need_group = 1;
457                         }
458                 }
459         }
460 unlock:
461         mutex_unlock(&uctxt->exp_mutex);
462         hfi1_cdbg(TID, "total mapped: tidpairs:%u pages:%u (%d)", tididx,
463                   mapped_pages, ret);
464
465         /* fail if nothing was programmed, set error if none provided */
466         if (tididx == 0) {
467                 if (ret >= 0)
468                         ret = -ENOSPC;
469                 goto fail_unreserve;
470         }
471
472         /* adjust reserved tid_used to actual count */
473         spin_lock(&fd->tid_lock);
474         fd->tid_used -= pageset_count - tididx;
475         spin_unlock(&fd->tid_lock);
476
477         /* unpin all pages not covered by a TID */
478         unpin_rcv_pages(fd, tidbuf, NULL, mapped_pages, pinned - mapped_pages,
479                         false);
480
481         tinfo->tidcnt = tididx;
482         tinfo->length = mapped_pages * PAGE_SIZE;
483
484         if (copy_to_user(u64_to_user_ptr(tinfo->tidlist),
485                          tidlist, sizeof(tidlist[0]) * tididx)) {
486                 ret = -EFAULT;
487                 goto fail_unprogram;
488         }
489
490         kfree(tidbuf->pages);
491         kfree(tidbuf->psets);
492         kfree(tidbuf);
493         kfree(tidlist);
494         return 0;
495
496 fail_unprogram:
497         /* unprogram, unmap, and unpin all allocated TIDs */
498         tinfo->tidlist = (unsigned long)tidlist;
499         hfi1_user_exp_rcv_clear(fd, tinfo);
500         tinfo->tidlist = 0;
501         pinned = 0;             /* nothing left to unpin */
502         pageset_count = 0;      /* nothing left reserved */
503 fail_unreserve:
504         spin_lock(&fd->tid_lock);
505         fd->tid_used -= pageset_count;
506         spin_unlock(&fd->tid_lock);
507 fail_unpin:
508         if (pinned > 0)
509                 unpin_rcv_pages(fd, tidbuf, NULL, 0, pinned, false);
510 fail_release_mem:
511         kfree(tidbuf->pages);
512         kfree(tidbuf->psets);
513         kfree(tidbuf);
514         kfree(tidlist);
515         return ret;
516 }
517
518 int hfi1_user_exp_rcv_clear(struct hfi1_filedata *fd,
519                             struct hfi1_tid_info *tinfo)
520 {
521         int ret = 0;
522         struct hfi1_ctxtdata *uctxt = fd->uctxt;
523         u32 *tidinfo;
524         unsigned tididx;
525
526         if (unlikely(tinfo->tidcnt > fd->tid_used))
527                 return -EINVAL;
528
529         tidinfo = memdup_user(u64_to_user_ptr(tinfo->tidlist),
530                               sizeof(tidinfo[0]) * tinfo->tidcnt);
531         if (IS_ERR(tidinfo))
532                 return PTR_ERR(tidinfo);
533
534         mutex_lock(&uctxt->exp_mutex);
535         for (tididx = 0; tididx < tinfo->tidcnt; tididx++) {
536                 ret = unprogram_rcvarray(fd, tidinfo[tididx], NULL);
537                 if (ret) {
538                         hfi1_cdbg(TID, "Failed to unprogram rcv array %d",
539                                   ret);
540                         break;
541                 }
542         }
543         spin_lock(&fd->tid_lock);
544         fd->tid_used -= tididx;
545         spin_unlock(&fd->tid_lock);
546         tinfo->tidcnt = tididx;
547         mutex_unlock(&uctxt->exp_mutex);
548
549         kfree(tidinfo);
550         return ret;
551 }
552
553 int hfi1_user_exp_rcv_invalid(struct hfi1_filedata *fd,
554                               struct hfi1_tid_info *tinfo)
555 {
556         struct hfi1_ctxtdata *uctxt = fd->uctxt;
557         unsigned long *ev = uctxt->dd->events +
558                 (uctxt_offset(uctxt) + fd->subctxt);
559         u32 *array;
560         int ret = 0;
561
562         /*
563          * copy_to_user() can sleep, which will leave the invalid_lock
564          * locked and cause the MMU notifier to be blocked on the lock
565          * for a long time.
566          * Copy the data to a local buffer so we can release the lock.
567          */
568         array = kcalloc(uctxt->expected_count, sizeof(*array), GFP_KERNEL);
569         if (!array)
570                 return -EFAULT;
571
572         spin_lock(&fd->invalid_lock);
573         if (fd->invalid_tid_idx) {
574                 memcpy(array, fd->invalid_tids, sizeof(*array) *
575                        fd->invalid_tid_idx);
576                 memset(fd->invalid_tids, 0, sizeof(*fd->invalid_tids) *
577                        fd->invalid_tid_idx);
578                 tinfo->tidcnt = fd->invalid_tid_idx;
579                 fd->invalid_tid_idx = 0;
580                 /*
581                  * Reset the user flag while still holding the lock.
582                  * Otherwise, PSM can miss events.
583                  */
584                 clear_bit(_HFI1_EVENT_TID_MMU_NOTIFY_BIT, ev);
585         } else {
586                 tinfo->tidcnt = 0;
587         }
588         spin_unlock(&fd->invalid_lock);
589
590         if (tinfo->tidcnt) {
591                 if (copy_to_user((void __user *)tinfo->tidlist,
592                                  array, sizeof(*array) * tinfo->tidcnt))
593                         ret = -EFAULT;
594         }
595         kfree(array);
596
597         return ret;
598 }
599
600 static u32 find_phys_blocks(struct tid_user_buf *tidbuf, unsigned int npages)
601 {
602         unsigned pagecount, pageidx, setcount = 0, i;
603         unsigned long pfn, this_pfn;
604         struct page **pages = tidbuf->pages;
605         struct tid_pageset *list = tidbuf->psets;
606
607         if (!npages)
608                 return 0;
609
610         /*
611          * Look for sets of physically contiguous pages in the user buffer.
612          * This will allow us to optimize Expected RcvArray entry usage by
613          * using the bigger supported sizes.
614          */
615         pfn = page_to_pfn(pages[0]);
616         for (pageidx = 0, pagecount = 1, i = 1; i <= npages; i++) {
617                 this_pfn = i < npages ? page_to_pfn(pages[i]) : 0;
618
619                 /*
620                  * If the pfn's are not sequential, pages are not physically
621                  * contiguous.
622                  */
623                 if (this_pfn != ++pfn) {
624                         /*
625                          * At this point we have to loop over the set of
626                          * physically contiguous pages and break them down it
627                          * sizes supported by the HW.
628                          * There are two main constraints:
629                          *     1. The max buffer size is MAX_EXPECTED_BUFFER.
630                          *        If the total set size is bigger than that
631                          *        program only a MAX_EXPECTED_BUFFER chunk.
632                          *     2. The buffer size has to be a power of two. If
633                          *        it is not, round down to the closes power of
634                          *        2 and program that size.
635                          */
636                         while (pagecount) {
637                                 int maxpages = pagecount;
638                                 u32 bufsize = pagecount * PAGE_SIZE;
639
640                                 if (bufsize > MAX_EXPECTED_BUFFER)
641                                         maxpages =
642                                                 MAX_EXPECTED_BUFFER >>
643                                                 PAGE_SHIFT;
644                                 else if (!is_power_of_2(bufsize))
645                                         maxpages =
646                                                 rounddown_pow_of_two(bufsize) >>
647                                                 PAGE_SHIFT;
648
649                                 list[setcount].idx = pageidx;
650                                 list[setcount].count = maxpages;
651                                 pagecount -= maxpages;
652                                 pageidx += maxpages;
653                                 setcount++;
654                         }
655                         pageidx = i;
656                         pagecount = 1;
657                         pfn = this_pfn;
658                 } else {
659                         pagecount++;
660                 }
661         }
662         return setcount;
663 }
664
665 /**
666  * program_rcvarray() - program an RcvArray group with receive buffers
667  * @fd: filedata pointer
668  * @tbuf: pointer to struct tid_user_buf that has the user buffer starting
669  *        virtual address, buffer length, page pointers, pagesets (array of
670  *        struct tid_pageset holding information on physically contiguous
671  *        chunks from the user buffer), and other fields.
672  * @grp: RcvArray group
673  * @start: starting index into sets array
674  * @count: number of struct tid_pageset's to program
675  * @tidlist: the array of u32 elements when the information about the
676  *           programmed RcvArray entries is to be encoded.
677  * @tididx: starting offset into tidlist
678  * @pmapped: (output parameter) number of pages programmed into the RcvArray
679  *           entries.
680  *
681  * This function will program up to 'count' number of RcvArray entries from the
682  * group 'grp'. To make best use of write-combining writes, the function will
683  * perform writes to the unused RcvArray entries which will be ignored by the
684  * HW. Each RcvArray entry will be programmed with a physically contiguous
685  * buffer chunk from the user's virtual buffer.
686  *
687  * Return:
688  * -EINVAL if the requested count is larger than the size of the group,
689  * -ENOMEM or -EFAULT on error from set_rcvarray_entry(), or
690  * number of RcvArray entries programmed.
691  */
692 static int program_rcvarray(struct hfi1_filedata *fd, struct tid_user_buf *tbuf,
693                             struct tid_group *grp,
694                             unsigned int start, u16 count,
695                             u32 *tidlist, unsigned int *tididx,
696                             unsigned int *pmapped)
697 {
698         struct hfi1_ctxtdata *uctxt = fd->uctxt;
699         struct hfi1_devdata *dd = uctxt->dd;
700         u16 idx;
701         u32 tidinfo = 0, rcventry, useidx = 0;
702         int mapped = 0;
703
704         /* Count should never be larger than the group size */
705         if (count > grp->size)
706                 return -EINVAL;
707
708         /* Find the first unused entry in the group */
709         for (idx = 0; idx < grp->size; idx++) {
710                 if (!(grp->map & (1 << idx))) {
711                         useidx = idx;
712                         break;
713                 }
714                 rcv_array_wc_fill(dd, grp->base + idx);
715         }
716
717         idx = 0;
718         while (idx < count) {
719                 u16 npages, pageidx, setidx = start + idx;
720                 int ret = 0;
721
722                 /*
723                  * If this entry in the group is used, move to the next one.
724                  * If we go past the end of the group, exit the loop.
725                  */
726                 if (useidx >= grp->size) {
727                         break;
728                 } else if (grp->map & (1 << useidx)) {
729                         rcv_array_wc_fill(dd, grp->base + useidx);
730                         useidx++;
731                         continue;
732                 }
733
734                 rcventry = grp->base + useidx;
735                 npages = tbuf->psets[setidx].count;
736                 pageidx = tbuf->psets[setidx].idx;
737
738                 ret = set_rcvarray_entry(fd, tbuf,
739                                          rcventry, grp, pageidx,
740                                          npages);
741                 if (ret)
742                         return ret;
743                 mapped += npages;
744
745                 tidinfo = rcventry2tidinfo(rcventry - uctxt->expected_base) |
746                         EXP_TID_SET(LEN, npages);
747                 tidlist[(*tididx)++] = tidinfo;
748                 grp->used++;
749                 grp->map |= 1 << useidx++;
750                 idx++;
751         }
752
753         /* Fill the rest of the group with "blank" writes */
754         for (; useidx < grp->size; useidx++)
755                 rcv_array_wc_fill(dd, grp->base + useidx);
756         *pmapped = mapped;
757         return idx;
758 }
759
760 static int set_rcvarray_entry(struct hfi1_filedata *fd,
761                               struct tid_user_buf *tbuf,
762                               u32 rcventry, struct tid_group *grp,
763                               u16 pageidx, unsigned int npages)
764 {
765         int ret;
766         struct hfi1_ctxtdata *uctxt = fd->uctxt;
767         struct tid_rb_node *node;
768         struct hfi1_devdata *dd = uctxt->dd;
769         dma_addr_t phys;
770         struct page **pages = tbuf->pages + pageidx;
771
772         /*
773          * Allocate the node first so we can handle a potential
774          * failure before we've programmed anything.
775          */
776         node = kzalloc(sizeof(*node) + (sizeof(struct page *) * npages),
777                        GFP_KERNEL);
778         if (!node)
779                 return -ENOMEM;
780
781         phys = pci_map_single(dd->pcidev,
782                               __va(page_to_phys(pages[0])),
783                               npages * PAGE_SIZE, PCI_DMA_FROMDEVICE);
784         if (dma_mapping_error(&dd->pcidev->dev, phys)) {
785                 dd_dev_err(dd, "Failed to DMA map Exp Rcv pages 0x%llx\n",
786                            phys);
787                 kfree(node);
788                 return -EFAULT;
789         }
790
791         node->mmu.addr = tbuf->vaddr + (pageidx * PAGE_SIZE);
792         node->mmu.len = npages * PAGE_SIZE;
793         node->phys = page_to_phys(pages[0]);
794         node->npages = npages;
795         node->rcventry = rcventry;
796         node->dma_addr = phys;
797         node->grp = grp;
798         node->freed = false;
799         memcpy(node->pages, pages, sizeof(struct page *) * npages);
800
801         if (!fd->handler)
802                 ret = tid_rb_insert(fd, &node->mmu);
803         else
804                 ret = hfi1_mmu_rb_insert(fd->handler, &node->mmu);
805
806         if (ret) {
807                 hfi1_cdbg(TID, "Failed to insert RB node %u 0x%lx, 0x%lx %d",
808                           node->rcventry, node->mmu.addr, node->phys, ret);
809                 pci_unmap_single(dd->pcidev, phys, npages * PAGE_SIZE,
810                                  PCI_DMA_FROMDEVICE);
811                 kfree(node);
812                 return -EFAULT;
813         }
814         hfi1_put_tid(dd, rcventry, PT_EXPECTED, phys, ilog2(npages) + 1);
815         trace_hfi1_exp_tid_reg(uctxt->ctxt, fd->subctxt, rcventry, npages,
816                                node->mmu.addr, node->phys, phys);
817         return 0;
818 }
819
820 static int unprogram_rcvarray(struct hfi1_filedata *fd, u32 tidinfo,
821                               struct tid_group **grp)
822 {
823         struct hfi1_ctxtdata *uctxt = fd->uctxt;
824         struct hfi1_devdata *dd = uctxt->dd;
825         struct tid_rb_node *node;
826         u8 tidctrl = EXP_TID_GET(tidinfo, CTRL);
827         u32 tididx = EXP_TID_GET(tidinfo, IDX) << 1, rcventry;
828
829         if (tididx >= uctxt->expected_count) {
830                 dd_dev_err(dd, "Invalid RcvArray entry (%u) index for ctxt %u\n",
831                            tididx, uctxt->ctxt);
832                 return -EINVAL;
833         }
834
835         if (tidctrl == 0x3)
836                 return -EINVAL;
837
838         rcventry = tididx + (tidctrl - 1);
839
840         node = fd->entry_to_rb[rcventry];
841         if (!node || node->rcventry != (uctxt->expected_base + rcventry))
842                 return -EBADF;
843
844         if (grp)
845                 *grp = node->grp;
846
847         if (!fd->handler)
848                 cacheless_tid_rb_remove(fd, node);
849         else
850                 hfi1_mmu_rb_remove(fd->handler, &node->mmu);
851
852         return 0;
853 }
854
855 static void clear_tid_node(struct hfi1_filedata *fd, struct tid_rb_node *node)
856 {
857         struct hfi1_ctxtdata *uctxt = fd->uctxt;
858         struct hfi1_devdata *dd = uctxt->dd;
859
860         trace_hfi1_exp_tid_unreg(uctxt->ctxt, fd->subctxt, node->rcventry,
861                                  node->npages, node->mmu.addr, node->phys,
862                                  node->dma_addr);
863
864         /*
865          * Make sure device has seen the write before we unpin the
866          * pages.
867          */
868         hfi1_put_tid(dd, node->rcventry, PT_INVALID_FLUSH, 0, 0);
869
870         unpin_rcv_pages(fd, NULL, node, 0, node->npages, true);
871
872         node->grp->used--;
873         node->grp->map &= ~(1 << (node->rcventry - node->grp->base));
874
875         if (node->grp->used == node->grp->size - 1)
876                 tid_group_move(node->grp, &uctxt->tid_full_list,
877                                &uctxt->tid_used_list);
878         else if (!node->grp->used)
879                 tid_group_move(node->grp, &uctxt->tid_used_list,
880                                &uctxt->tid_group_list);
881         kfree(node);
882 }
883
884 /*
885  * As a simple helper for hfi1_user_exp_rcv_free, this function deals with
886  * clearing nodes in the non-cached case.
887  */
888 static void unlock_exp_tids(struct hfi1_ctxtdata *uctxt,
889                             struct exp_tid_set *set,
890                             struct hfi1_filedata *fd)
891 {
892         struct tid_group *grp, *ptr;
893         int i;
894
895         list_for_each_entry_safe(grp, ptr, &set->list, list) {
896                 list_del_init(&grp->list);
897
898                 for (i = 0; i < grp->size; i++) {
899                         if (grp->map & (1 << i)) {
900                                 u16 rcventry = grp->base + i;
901                                 struct tid_rb_node *node;
902
903                                 node = fd->entry_to_rb[rcventry -
904                                                           uctxt->expected_base];
905                                 if (!node || node->rcventry != rcventry)
906                                         continue;
907
908                                 cacheless_tid_rb_remove(fd, node);
909                         }
910                 }
911         }
912 }
913
914 /*
915  * Always return 0 from this function.  A non-zero return indicates that the
916  * remove operation will be called and that memory should be unpinned.
917  * However, the driver cannot unpin out from under PSM.  Instead, retain the
918  * memory (by returning 0) and inform PSM that the memory is going away.  PSM
919  * will call back later when it has removed the memory from its list.
920  */
921 static int tid_rb_invalidate(void *arg, struct mmu_rb_node *mnode)
922 {
923         struct hfi1_filedata *fdata = arg;
924         struct hfi1_ctxtdata *uctxt = fdata->uctxt;
925         struct tid_rb_node *node =
926                 container_of(mnode, struct tid_rb_node, mmu);
927
928         if (node->freed)
929                 return 0;
930
931         trace_hfi1_exp_tid_inval(uctxt->ctxt, fdata->subctxt, node->mmu.addr,
932                                  node->rcventry, node->npages, node->dma_addr);
933         node->freed = true;
934
935         spin_lock(&fdata->invalid_lock);
936         if (fdata->invalid_tid_idx < uctxt->expected_count) {
937                 fdata->invalid_tids[fdata->invalid_tid_idx] =
938                         rcventry2tidinfo(node->rcventry - uctxt->expected_base);
939                 fdata->invalid_tids[fdata->invalid_tid_idx] |=
940                         EXP_TID_SET(LEN, node->npages);
941                 if (!fdata->invalid_tid_idx) {
942                         unsigned long *ev;
943
944                         /*
945                          * hfi1_set_uevent_bits() sets a user event flag
946                          * for all processes. Because calling into the
947                          * driver to process TID cache invalidations is
948                          * expensive and TID cache invalidations are
949                          * handled on a per-process basis, we can
950                          * optimize this to set the flag only for the
951                          * process in question.
952                          */
953                         ev = uctxt->dd->events +
954                                 (uctxt_offset(uctxt) + fdata->subctxt);
955                         set_bit(_HFI1_EVENT_TID_MMU_NOTIFY_BIT, ev);
956                 }
957                 fdata->invalid_tid_idx++;
958         }
959         spin_unlock(&fdata->invalid_lock);
960         return 0;
961 }
962
963 static int tid_rb_insert(void *arg, struct mmu_rb_node *node)
964 {
965         struct hfi1_filedata *fdata = arg;
966         struct tid_rb_node *tnode =
967                 container_of(node, struct tid_rb_node, mmu);
968         u32 base = fdata->uctxt->expected_base;
969
970         fdata->entry_to_rb[tnode->rcventry - base] = tnode;
971         return 0;
972 }
973
974 static void cacheless_tid_rb_remove(struct hfi1_filedata *fdata,
975                                     struct tid_rb_node *tnode)
976 {
977         u32 base = fdata->uctxt->expected_base;
978
979         fdata->entry_to_rb[tnode->rcventry - base] = NULL;
980         clear_tid_node(fdata, tnode);
981 }
982
983 static void tid_rb_remove(void *arg, struct mmu_rb_node *node)
984 {
985         struct hfi1_filedata *fdata = arg;
986         struct tid_rb_node *tnode =
987                 container_of(node, struct tid_rb_node, mmu);
988
989         cacheless_tid_rb_remove(fdata, tnode);
990 }