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