f8538bbd0bfae72c11128d773f00aadc91f0c1ba
[pandora-kernel.git] / drivers / misc / sgi-gru / grumain.c
1 /*
2  * SN Platform GRU Driver
3  *
4  *            DRIVER TABLE MANAGER + GRU CONTEXT LOAD/UNLOAD
5  *
6  *  Copyright (c) 2008 Silicon Graphics, Inc.  All Rights Reserved.
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
21  */
22
23 #include <linux/kernel.h>
24 #include <linux/slab.h>
25 #include <linux/mm.h>
26 #include <linux/spinlock.h>
27 #include <linux/sched.h>
28 #include <linux/device.h>
29 #include <linux/list.h>
30 #include <linux/err.h>
31 #include <asm/uv/uv_hub.h>
32 #include "gru.h"
33 #include "grutables.h"
34 #include "gruhandles.h"
35
36 unsigned long gru_options __read_mostly;
37
38 static struct device_driver gru_driver = {
39         .name = "gru"
40 };
41
42 static struct device gru_device = {
43         .init_name = "",
44         .driver = &gru_driver,
45 };
46
47 struct device *grudev = &gru_device;
48
49 /*
50  * Select a gru fault map to be used by the current cpu. Note that
51  * multiple cpus may be using the same map.
52  *      ZZZ should be inline but did not work on emulator
53  */
54 int gru_cpu_fault_map_id(void)
55 {
56 #ifdef CONFIG_IA64
57         return uv_blade_processor_id() % GRU_NUM_TFM;
58 #else
59         int cpu = smp_processor_id();
60         int id, core;
61
62         core = uv_cpu_core_number(cpu);
63         id = core + UV_MAX_INT_CORES * uv_cpu_socket_number(cpu);
64         return id;
65 #endif
66 }
67
68 /*--------- ASID Management -------------------------------------------
69  *
70  *  Initially, assign asids sequentially from MIN_ASID .. MAX_ASID.
71  *  Once MAX is reached, flush the TLB & start over. However,
72  *  some asids may still be in use. There won't be many (percentage wise) still
73  *  in use. Search active contexts & determine the value of the first
74  *  asid in use ("x"s below). Set "limit" to this value.
75  *  This defines a block of assignable asids.
76  *
77  *  When "limit" is reached, search forward from limit+1 and determine the
78  *  next block of assignable asids.
79  *
80  *  Repeat until MAX_ASID is reached, then start over again.
81  *
82  *  Each time MAX_ASID is reached, increment the asid generation. Since
83  *  the search for in-use asids only checks contexts with GRUs currently
84  *  assigned, asids in some contexts will be missed. Prior to loading
85  *  a context, the asid generation of the GTS asid is rechecked. If it
86  *  doesn't match the current generation, a new asid will be assigned.
87  *
88  *      0---------------x------------x---------------------x----|
89  *        ^-next        ^-limit                                 ^-MAX_ASID
90  *
91  * All asid manipulation & context loading/unloading is protected by the
92  * gs_lock.
93  */
94
95 /* Hit the asid limit. Start over */
96 static int gru_wrap_asid(struct gru_state *gru)
97 {
98         gru_dbg(grudev, "gid %d\n", gru->gs_gid);
99         STAT(asid_wrap);
100         gru->gs_asid_gen++;
101         return MIN_ASID;
102 }
103
104 /* Find the next chunk of unused asids */
105 static int gru_reset_asid_limit(struct gru_state *gru, int asid)
106 {
107         int i, gid, inuse_asid, limit;
108
109         gru_dbg(grudev, "gid %d, asid 0x%x\n", gru->gs_gid, asid);
110         STAT(asid_next);
111         limit = MAX_ASID;
112         if (asid >= limit)
113                 asid = gru_wrap_asid(gru);
114         gru_flush_all_tlb(gru);
115         gid = gru->gs_gid;
116 again:
117         for (i = 0; i < GRU_NUM_CCH; i++) {
118                 if (!gru->gs_gts[i] || is_kernel_context(gru->gs_gts[i]))
119                         continue;
120                 inuse_asid = gru->gs_gts[i]->ts_gms->ms_asids[gid].mt_asid;
121                 gru_dbg(grudev, "gid %d, gts %p, gms %p, inuse 0x%x, cxt %d\n",
122                         gru->gs_gid, gru->gs_gts[i], gru->gs_gts[i]->ts_gms,
123                         inuse_asid, i);
124                 if (inuse_asid == asid) {
125                         asid += ASID_INC;
126                         if (asid >= limit) {
127                                 /*
128                                  * empty range: reset the range limit and
129                                  * start over
130                                  */
131                                 limit = MAX_ASID;
132                                 if (asid >= MAX_ASID)
133                                         asid = gru_wrap_asid(gru);
134                                 goto again;
135                         }
136                 }
137
138                 if ((inuse_asid > asid) && (inuse_asid < limit))
139                         limit = inuse_asid;
140         }
141         gru->gs_asid_limit = limit;
142         gru->gs_asid = asid;
143         gru_dbg(grudev, "gid %d, new asid 0x%x, new_limit 0x%x\n", gru->gs_gid,
144                                         asid, limit);
145         return asid;
146 }
147
148 /* Assign a new ASID to a thread context.  */
149 static int gru_assign_asid(struct gru_state *gru)
150 {
151         int asid;
152
153         gru->gs_asid += ASID_INC;
154         asid = gru->gs_asid;
155         if (asid >= gru->gs_asid_limit)
156                 asid = gru_reset_asid_limit(gru, asid);
157
158         gru_dbg(grudev, "gid %d, asid 0x%x\n", gru->gs_gid, asid);
159         return asid;
160 }
161
162 /*
163  * Clear n bits in a word. Return a word indicating the bits that were cleared.
164  * Optionally, build an array of chars that contain the bit numbers allocated.
165  */
166 static unsigned long reserve_resources(unsigned long *p, int n, int mmax,
167                                        char *idx)
168 {
169         unsigned long bits = 0;
170         int i;
171
172         while (n--) {
173                 i = find_first_bit(p, mmax);
174                 if (i == mmax)
175                         BUG();
176                 __clear_bit(i, p);
177                 __set_bit(i, &bits);
178                 if (idx)
179                         *idx++ = i;
180         }
181         return bits;
182 }
183
184 unsigned long gru_reserve_cb_resources(struct gru_state *gru, int cbr_au_count,
185                                        char *cbmap)
186 {
187         return reserve_resources(&gru->gs_cbr_map, cbr_au_count, GRU_CBR_AU,
188                                  cbmap);
189 }
190
191 unsigned long gru_reserve_ds_resources(struct gru_state *gru, int dsr_au_count,
192                                        char *dsmap)
193 {
194         return reserve_resources(&gru->gs_dsr_map, dsr_au_count, GRU_DSR_AU,
195                                  dsmap);
196 }
197
198 static void reserve_gru_resources(struct gru_state *gru,
199                                   struct gru_thread_state *gts)
200 {
201         gru->gs_active_contexts++;
202         gts->ts_cbr_map =
203             gru_reserve_cb_resources(gru, gts->ts_cbr_au_count,
204                                      gts->ts_cbr_idx);
205         gts->ts_dsr_map =
206             gru_reserve_ds_resources(gru, gts->ts_dsr_au_count, NULL);
207 }
208
209 static void free_gru_resources(struct gru_state *gru,
210                                struct gru_thread_state *gts)
211 {
212         gru->gs_active_contexts--;
213         gru->gs_cbr_map |= gts->ts_cbr_map;
214         gru->gs_dsr_map |= gts->ts_dsr_map;
215 }
216
217 /*
218  * Check if a GRU has sufficient free resources to satisfy an allocation
219  * request. Note: GRU locks may or may not be held when this is called. If
220  * not held, recheck after acquiring the appropriate locks.
221  *
222  * Returns 1 if sufficient resources, 0 if not
223  */
224 static int check_gru_resources(struct gru_state *gru, int cbr_au_count,
225                                int dsr_au_count, int max_active_contexts)
226 {
227         return hweight64(gru->gs_cbr_map) >= cbr_au_count
228                 && hweight64(gru->gs_dsr_map) >= dsr_au_count
229                 && gru->gs_active_contexts < max_active_contexts;
230 }
231
232 /*
233  * TLB manangment requires tracking all GRU chiplets that have loaded a GSEG
234  * context.
235  */
236 static int gru_load_mm_tracker(struct gru_state *gru,
237                                         struct gru_thread_state *gts)
238 {
239         struct gru_mm_struct *gms = gts->ts_gms;
240         struct gru_mm_tracker *asids = &gms->ms_asids[gru->gs_gid];
241         unsigned short ctxbitmap = (1 << gts->ts_ctxnum);
242         int asid;
243
244         spin_lock(&gms->ms_asid_lock);
245         asid = asids->mt_asid;
246
247         spin_lock(&gru->gs_asid_lock);
248         if (asid == 0 || (asids->mt_ctxbitmap == 0 && asids->mt_asid_gen !=
249                           gru->gs_asid_gen)) {
250                 asid = gru_assign_asid(gru);
251                 asids->mt_asid = asid;
252                 asids->mt_asid_gen = gru->gs_asid_gen;
253                 STAT(asid_new);
254         } else {
255                 STAT(asid_reuse);
256         }
257         spin_unlock(&gru->gs_asid_lock);
258
259         BUG_ON(asids->mt_ctxbitmap & ctxbitmap);
260         asids->mt_ctxbitmap |= ctxbitmap;
261         if (!test_bit(gru->gs_gid, gms->ms_asidmap))
262                 __set_bit(gru->gs_gid, gms->ms_asidmap);
263         spin_unlock(&gms->ms_asid_lock);
264
265         gru_dbg(grudev,
266                 "gid %d, gts %p, gms %p, ctxnum %d, asid 0x%x, asidmap 0x%lx\n",
267                 gru->gs_gid, gts, gms, gts->ts_ctxnum, asid,
268                 gms->ms_asidmap[0]);
269         return asid;
270 }
271
272 static void gru_unload_mm_tracker(struct gru_state *gru,
273                                         struct gru_thread_state *gts)
274 {
275         struct gru_mm_struct *gms = gts->ts_gms;
276         struct gru_mm_tracker *asids;
277         unsigned short ctxbitmap;
278
279         asids = &gms->ms_asids[gru->gs_gid];
280         ctxbitmap = (1 << gts->ts_ctxnum);
281         spin_lock(&gms->ms_asid_lock);
282         spin_lock(&gru->gs_asid_lock);
283         BUG_ON((asids->mt_ctxbitmap & ctxbitmap) != ctxbitmap);
284         asids->mt_ctxbitmap ^= ctxbitmap;
285         gru_dbg(grudev, "gid %d, gts %p, gms %p, ctxnum 0x%d, asidmap 0x%lx\n",
286                 gru->gs_gid, gts, gms, gts->ts_ctxnum, gms->ms_asidmap[0]);
287         spin_unlock(&gru->gs_asid_lock);
288         spin_unlock(&gms->ms_asid_lock);
289 }
290
291 /*
292  * Decrement the reference count on a GTS structure. Free the structure
293  * if the reference count goes to zero.
294  */
295 void gts_drop(struct gru_thread_state *gts)
296 {
297         if (gts && atomic_dec_return(&gts->ts_refcnt) == 0) {
298                 if (gts->ts_gms)
299                         gru_drop_mmu_notifier(gts->ts_gms);
300                 kfree(gts);
301                 STAT(gts_free);
302         }
303 }
304
305 /*
306  * Locate the GTS structure for the current thread.
307  */
308 static struct gru_thread_state *gru_find_current_gts_nolock(struct gru_vma_data
309                             *vdata, int tsid)
310 {
311         struct gru_thread_state *gts;
312
313         list_for_each_entry(gts, &vdata->vd_head, ts_next)
314             if (gts->ts_tsid == tsid)
315                 return gts;
316         return NULL;
317 }
318
319 /*
320  * Allocate a thread state structure.
321  */
322 struct gru_thread_state *gru_alloc_gts(struct vm_area_struct *vma,
323                 int cbr_au_count, int dsr_au_count,
324                 unsigned char tlb_preload_count, int options, int tsid)
325 {
326         struct gru_thread_state *gts;
327         struct gru_mm_struct *gms;
328         int bytes;
329
330         bytes = DSR_BYTES(dsr_au_count) + CBR_BYTES(cbr_au_count);
331         bytes += sizeof(struct gru_thread_state);
332         gts = kmalloc(bytes, GFP_KERNEL);
333         if (!gts)
334                 return ERR_PTR(-ENOMEM);
335
336         STAT(gts_alloc);
337         memset(gts, 0, sizeof(struct gru_thread_state)); /* zero out header */
338         atomic_set(&gts->ts_refcnt, 1);
339         mutex_init(&gts->ts_ctxlock);
340         gts->ts_cbr_au_count = cbr_au_count;
341         gts->ts_dsr_au_count = dsr_au_count;
342         gts->ts_tlb_preload_count = tlb_preload_count;
343         gts->ts_user_options = options;
344         gts->ts_user_blade_id = -1;
345         gts->ts_user_chiplet_id = -1;
346         gts->ts_tsid = tsid;
347         gts->ts_ctxnum = NULLCTX;
348         gts->ts_tlb_int_select = -1;
349         gts->ts_cch_req_slice = -1;
350         gts->ts_sizeavail = GRU_SIZEAVAIL(PAGE_SHIFT);
351         if (vma) {
352                 gts->ts_mm = current->mm;
353                 gts->ts_vma = vma;
354                 gms = gru_register_mmu_notifier();
355                 if (IS_ERR(gms))
356                         goto err;
357                 gts->ts_gms = gms;
358         }
359
360         gru_dbg(grudev, "alloc gts %p\n", gts);
361         return gts;
362
363 err:
364         gts_drop(gts);
365         return ERR_CAST(gms);
366 }
367
368 /*
369  * Allocate a vma private data structure.
370  */
371 struct gru_vma_data *gru_alloc_vma_data(struct vm_area_struct *vma, int tsid)
372 {
373         struct gru_vma_data *vdata = NULL;
374
375         vdata = kmalloc(sizeof(*vdata), GFP_KERNEL);
376         if (!vdata)
377                 return NULL;
378
379         STAT(vdata_alloc);
380         INIT_LIST_HEAD(&vdata->vd_head);
381         spin_lock_init(&vdata->vd_lock);
382         gru_dbg(grudev, "alloc vdata %p\n", vdata);
383         return vdata;
384 }
385
386 /*
387  * Find the thread state structure for the current thread.
388  */
389 struct gru_thread_state *gru_find_thread_state(struct vm_area_struct *vma,
390                                         int tsid)
391 {
392         struct gru_vma_data *vdata = vma->vm_private_data;
393         struct gru_thread_state *gts;
394
395         spin_lock(&vdata->vd_lock);
396         gts = gru_find_current_gts_nolock(vdata, tsid);
397         spin_unlock(&vdata->vd_lock);
398         gru_dbg(grudev, "vma %p, gts %p\n", vma, gts);
399         return gts;
400 }
401
402 /*
403  * Allocate a new thread state for a GSEG. Note that races may allow
404  * another thread to race to create a gts.
405  */
406 struct gru_thread_state *gru_alloc_thread_state(struct vm_area_struct *vma,
407                                         int tsid)
408 {
409         struct gru_vma_data *vdata = vma->vm_private_data;
410         struct gru_thread_state *gts, *ngts;
411
412         gts = gru_alloc_gts(vma, vdata->vd_cbr_au_count,
413                             vdata->vd_dsr_au_count,
414                             vdata->vd_tlb_preload_count,
415                             vdata->vd_user_options, tsid);
416         if (IS_ERR(gts))
417                 return gts;
418
419         spin_lock(&vdata->vd_lock);
420         ngts = gru_find_current_gts_nolock(vdata, tsid);
421         if (ngts) {
422                 gts_drop(gts);
423                 gts = ngts;
424                 STAT(gts_double_allocate);
425         } else {
426                 list_add(&gts->ts_next, &vdata->vd_head);
427         }
428         spin_unlock(&vdata->vd_lock);
429         gru_dbg(grudev, "vma %p, gts %p\n", vma, gts);
430         return gts;
431 }
432
433 /*
434  * Free the GRU context assigned to the thread state.
435  */
436 static void gru_free_gru_context(struct gru_thread_state *gts)
437 {
438         struct gru_state *gru;
439
440         gru = gts->ts_gru;
441         gru_dbg(grudev, "gts %p, gid %d\n", gts, gru->gs_gid);
442
443         spin_lock(&gru->gs_lock);
444         gru->gs_gts[gts->ts_ctxnum] = NULL;
445         free_gru_resources(gru, gts);
446         BUG_ON(test_bit(gts->ts_ctxnum, &gru->gs_context_map) == 0);
447         __clear_bit(gts->ts_ctxnum, &gru->gs_context_map);
448         gts->ts_ctxnum = NULLCTX;
449         gts->ts_gru = NULL;
450         gts->ts_blade = -1;
451         spin_unlock(&gru->gs_lock);
452
453         gts_drop(gts);
454         STAT(free_context);
455 }
456
457 /*
458  * Prefetching cachelines help hardware performance.
459  * (Strictly a performance enhancement. Not functionally required).
460  */
461 static void prefetch_data(void *p, int num, int stride)
462 {
463         while (num-- > 0) {
464                 prefetchw(p);
465                 p += stride;
466         }
467 }
468
469 static inline long gru_copy_handle(void *d, void *s)
470 {
471         memcpy(d, s, GRU_HANDLE_BYTES);
472         return GRU_HANDLE_BYTES;
473 }
474
475 static void gru_prefetch_context(void *gseg, void *cb, void *cbe,
476                                 unsigned long cbrmap, unsigned long length)
477 {
478         int i, scr;
479
480         prefetch_data(gseg + GRU_DS_BASE, length / GRU_CACHE_LINE_BYTES,
481                       GRU_CACHE_LINE_BYTES);
482
483         for_each_cbr_in_allocation_map(i, &cbrmap, scr) {
484                 prefetch_data(cb, 1, GRU_CACHE_LINE_BYTES);
485                 prefetch_data(cbe + i * GRU_HANDLE_STRIDE, 1,
486                               GRU_CACHE_LINE_BYTES);
487                 cb += GRU_HANDLE_STRIDE;
488         }
489 }
490
491 static void gru_load_context_data(void *save, void *grubase, int ctxnum,
492                                   unsigned long cbrmap, unsigned long dsrmap,
493                                   int data_valid)
494 {
495         void *gseg, *cb, *cbe;
496         unsigned long length;
497         int i, scr;
498
499         gseg = grubase + ctxnum * GRU_GSEG_STRIDE;
500         cb = gseg + GRU_CB_BASE;
501         cbe = grubase + GRU_CBE_BASE;
502         length = hweight64(dsrmap) * GRU_DSR_AU_BYTES;
503         gru_prefetch_context(gseg, cb, cbe, cbrmap, length);
504
505         for_each_cbr_in_allocation_map(i, &cbrmap, scr) {
506                 if (data_valid) {
507                         save += gru_copy_handle(cb, save);
508                         save += gru_copy_handle(cbe + i * GRU_HANDLE_STRIDE,
509                                                 save);
510                 } else {
511                         memset(cb, 0, GRU_CACHE_LINE_BYTES);
512                         memset(cbe + i * GRU_HANDLE_STRIDE, 0,
513                                                 GRU_CACHE_LINE_BYTES);
514                 }
515                 /* Flush CBE to hide race in context restart */
516                 mb();
517                 gru_flush_cache(cbe + i * GRU_HANDLE_STRIDE);
518                 cb += GRU_HANDLE_STRIDE;
519         }
520
521         if (data_valid)
522                 memcpy(gseg + GRU_DS_BASE, save, length);
523         else
524                 memset(gseg + GRU_DS_BASE, 0, length);
525 }
526
527 static void gru_unload_context_data(void *save, void *grubase, int ctxnum,
528                                     unsigned long cbrmap, unsigned long dsrmap)
529 {
530         void *gseg, *cb, *cbe;
531         unsigned long length;
532         int i, scr;
533
534         gseg = grubase + ctxnum * GRU_GSEG_STRIDE;
535         cb = gseg + GRU_CB_BASE;
536         cbe = grubase + GRU_CBE_BASE;
537         length = hweight64(dsrmap) * GRU_DSR_AU_BYTES;
538
539         /* CBEs may not be coherent. Flush them from cache */
540         for_each_cbr_in_allocation_map(i, &cbrmap, scr)
541                 gru_flush_cache(cbe + i * GRU_HANDLE_STRIDE);
542         mb();           /* Let the CL flush complete */
543
544         gru_prefetch_context(gseg, cb, cbe, cbrmap, length);
545
546         for_each_cbr_in_allocation_map(i, &cbrmap, scr) {
547                 save += gru_copy_handle(save, cb);
548                 save += gru_copy_handle(save, cbe + i * GRU_HANDLE_STRIDE);
549                 cb += GRU_HANDLE_STRIDE;
550         }
551         memcpy(save, gseg + GRU_DS_BASE, length);
552 }
553
554 void gru_unload_context(struct gru_thread_state *gts, int savestate)
555 {
556         struct gru_state *gru = gts->ts_gru;
557         struct gru_context_configuration_handle *cch;
558         int ctxnum = gts->ts_ctxnum;
559
560         if (!is_kernel_context(gts))
561                 zap_vma_ptes(gts->ts_vma, UGRUADDR(gts), GRU_GSEG_PAGESIZE);
562         cch = get_cch(gru->gs_gru_base_vaddr, ctxnum);
563
564         gru_dbg(grudev, "gts %p, cbrmap 0x%lx, dsrmap 0x%lx\n",
565                 gts, gts->ts_cbr_map, gts->ts_dsr_map);
566         lock_cch_handle(cch);
567         if (cch_interrupt_sync(cch))
568                 BUG();
569
570         if (!is_kernel_context(gts))
571                 gru_unload_mm_tracker(gru, gts);
572         if (savestate) {
573                 gru_unload_context_data(gts->ts_gdata, gru->gs_gru_base_vaddr,
574                                         ctxnum, gts->ts_cbr_map,
575                                         gts->ts_dsr_map);
576                 gts->ts_data_valid = 1;
577         }
578
579         if (cch_deallocate(cch))
580                 BUG();
581         unlock_cch_handle(cch);
582
583         gru_free_gru_context(gts);
584 }
585
586 /*
587  * Load a GRU context by copying it from the thread data structure in memory
588  * to the GRU.
589  */
590 void gru_load_context(struct gru_thread_state *gts)
591 {
592         struct gru_state *gru = gts->ts_gru;
593         struct gru_context_configuration_handle *cch;
594         int i, err, asid, ctxnum = gts->ts_ctxnum;
595
596         cch = get_cch(gru->gs_gru_base_vaddr, ctxnum);
597         lock_cch_handle(cch);
598         cch->tfm_fault_bit_enable =
599             (gts->ts_user_options == GRU_OPT_MISS_FMM_POLL
600              || gts->ts_user_options == GRU_OPT_MISS_FMM_INTR);
601         cch->tlb_int_enable = (gts->ts_user_options == GRU_OPT_MISS_FMM_INTR);
602         if (cch->tlb_int_enable) {
603                 gts->ts_tlb_int_select = gru_cpu_fault_map_id();
604                 cch->tlb_int_select = gts->ts_tlb_int_select;
605         }
606         if (gts->ts_cch_req_slice >= 0) {
607                 cch->req_slice_set_enable = 1;
608                 cch->req_slice = gts->ts_cch_req_slice;
609         } else {
610                 cch->req_slice_set_enable =0;
611         }
612         cch->tfm_done_bit_enable = 0;
613         cch->dsr_allocation_map = gts->ts_dsr_map;
614         cch->cbr_allocation_map = gts->ts_cbr_map;
615
616         if (is_kernel_context(gts)) {
617                 cch->unmap_enable = 1;
618                 cch->tfm_done_bit_enable = 1;
619                 cch->cb_int_enable = 1;
620                 cch->tlb_int_select = 0;        /* For now, ints go to cpu 0 */
621         } else {
622                 cch->unmap_enable = 0;
623                 cch->tfm_done_bit_enable = 0;
624                 cch->cb_int_enable = 0;
625                 asid = gru_load_mm_tracker(gru, gts);
626                 for (i = 0; i < 8; i++) {
627                         cch->asid[i] = asid + i;
628                         cch->sizeavail[i] = gts->ts_sizeavail;
629                 }
630         }
631
632         err = cch_allocate(cch);
633         if (err) {
634                 gru_dbg(grudev,
635                         "err %d: cch %p, gts %p, cbr 0x%lx, dsr 0x%lx\n",
636                         err, cch, gts, gts->ts_cbr_map, gts->ts_dsr_map);
637                 BUG();
638         }
639
640         gru_load_context_data(gts->ts_gdata, gru->gs_gru_base_vaddr, ctxnum,
641                         gts->ts_cbr_map, gts->ts_dsr_map, gts->ts_data_valid);
642
643         if (cch_start(cch))
644                 BUG();
645         unlock_cch_handle(cch);
646
647         gru_dbg(grudev, "gid %d, gts %p, cbrmap 0x%lx, dsrmap 0x%lx, tie %d, tis %d\n",
648                 gts->ts_gru->gs_gid, gts, gts->ts_cbr_map, gts->ts_dsr_map,
649                 (gts->ts_user_options == GRU_OPT_MISS_FMM_INTR), gts->ts_tlb_int_select);
650 }
651
652 /*
653  * Update fields in an active CCH:
654  *      - retarget interrupts on local blade
655  *      - update sizeavail mask
656  */
657 int gru_update_cch(struct gru_thread_state *gts)
658 {
659         struct gru_context_configuration_handle *cch;
660         struct gru_state *gru = gts->ts_gru;
661         int i, ctxnum = gts->ts_ctxnum, ret = 0;
662
663         cch = get_cch(gru->gs_gru_base_vaddr, ctxnum);
664
665         lock_cch_handle(cch);
666         if (cch->state == CCHSTATE_ACTIVE) {
667                 if (gru->gs_gts[gts->ts_ctxnum] != gts)
668                         goto exit;
669                 if (cch_interrupt(cch))
670                         BUG();
671                 for (i = 0; i < 8; i++)
672                         cch->sizeavail[i] = gts->ts_sizeavail;
673                 gts->ts_tlb_int_select = gru_cpu_fault_map_id();
674                 cch->tlb_int_select = gru_cpu_fault_map_id();
675                 cch->tfm_fault_bit_enable =
676                   (gts->ts_user_options == GRU_OPT_MISS_FMM_POLL
677                     || gts->ts_user_options == GRU_OPT_MISS_FMM_INTR);
678                 if (cch_start(cch))
679                         BUG();
680                 ret = 1;
681         }
682 exit:
683         unlock_cch_handle(cch);
684         return ret;
685 }
686
687 /*
688  * Update CCH tlb interrupt select. Required when all the following is true:
689  *      - task's GRU context is loaded into a GRU
690  *      - task is using interrupt notification for TLB faults
691  *      - task has migrated to a different cpu on the same blade where
692  *        it was previously running.
693  */
694 static int gru_retarget_intr(struct gru_thread_state *gts)
695 {
696         if (gts->ts_tlb_int_select < 0
697             || gts->ts_tlb_int_select == gru_cpu_fault_map_id())
698                 return 0;
699
700         gru_dbg(grudev, "retarget from %d to %d\n", gts->ts_tlb_int_select,
701                 gru_cpu_fault_map_id());
702         return gru_update_cch(gts);
703 }
704
705 /*
706  * Check if a GRU context is allowed to use a specific chiplet. By default
707  * a context is assigned to any blade-local chiplet. However, users can
708  * override this.
709  *      Returns 1 if assignment allowed, 0 otherwise
710  */
711 static int gru_check_chiplet_assignment(struct gru_state *gru,
712                                         struct gru_thread_state *gts)
713 {
714         int blade_id;
715         int chiplet_id;
716
717         blade_id = gts->ts_user_blade_id;
718         if (blade_id < 0)
719                 blade_id = uv_numa_blade_id();
720
721         chiplet_id = gts->ts_user_chiplet_id;
722         return gru->gs_blade_id == blade_id &&
723                 (chiplet_id < 0 || chiplet_id == gru->gs_chiplet_id);
724 }
725
726 /*
727  * Unload the gru context if it is not assigned to the correct blade or
728  * chiplet. Misassignment can occur if the process migrates to a different
729  * blade or if the user changes the selected blade/chiplet.
730  */
731 void gru_check_context_placement(struct gru_thread_state *gts)
732 {
733         struct gru_state *gru;
734
735         /*
736          * If the current task is the context owner, verify that the
737          * context is correctly placed. This test is skipped for non-owner
738          * references. Pthread apps use non-owner references to the CBRs.
739          */
740         gru = gts->ts_gru;
741         if (!gru || gts->ts_tgid_owner != current->tgid)
742                 return;
743
744         if (!gru_check_chiplet_assignment(gru, gts)) {
745                 STAT(check_context_unload);
746                 gru_unload_context(gts, 1);
747         } else if (gru_retarget_intr(gts)) {
748                 STAT(check_context_retarget_intr);
749         }
750 }
751
752
753 /*
754  * Insufficient GRU resources available on the local blade. Steal a context from
755  * a process. This is a hack until a _real_ resource scheduler is written....
756  */
757 #define next_ctxnum(n)  ((n) <  GRU_NUM_CCH - 2 ? (n) + 1 : 0)
758 #define next_gru(b, g)  (((g) < &(b)->bs_grus[GRU_CHIPLETS_PER_BLADE - 1]) ?  \
759                                  ((g)+1) : &(b)->bs_grus[0])
760
761 static int is_gts_stealable(struct gru_thread_state *gts,
762                 struct gru_blade_state *bs)
763 {
764         if (is_kernel_context(gts))
765                 return down_write_trylock(&bs->bs_kgts_sema);
766         else
767                 return mutex_trylock(&gts->ts_ctxlock);
768 }
769
770 static void gts_stolen(struct gru_thread_state *gts,
771                 struct gru_blade_state *bs)
772 {
773         if (is_kernel_context(gts)) {
774                 up_write(&bs->bs_kgts_sema);
775                 STAT(steal_kernel_context);
776         } else {
777                 mutex_unlock(&gts->ts_ctxlock);
778                 STAT(steal_user_context);
779         }
780 }
781
782 void gru_steal_context(struct gru_thread_state *gts)
783 {
784         struct gru_blade_state *blade;
785         struct gru_state *gru, *gru0;
786         struct gru_thread_state *ngts = NULL;
787         int ctxnum, ctxnum0, flag = 0, cbr, dsr;
788         int blade_id;
789
790         blade_id = gts->ts_user_blade_id;
791         if (blade_id < 0)
792                 blade_id = uv_numa_blade_id();
793         cbr = gts->ts_cbr_au_count;
794         dsr = gts->ts_dsr_au_count;
795
796         blade = gru_base[blade_id];
797         spin_lock(&blade->bs_lock);
798
799         ctxnum = next_ctxnum(blade->bs_lru_ctxnum);
800         gru = blade->bs_lru_gru;
801         if (ctxnum == 0)
802                 gru = next_gru(blade, gru);
803         blade->bs_lru_gru = gru;
804         blade->bs_lru_ctxnum = ctxnum;
805         ctxnum0 = ctxnum;
806         gru0 = gru;
807         while (1) {
808                 if (gru_check_chiplet_assignment(gru, gts)) {
809                         if (check_gru_resources(gru, cbr, dsr, GRU_NUM_CCH))
810                                 break;
811                         spin_lock(&gru->gs_lock);
812                         for (; ctxnum < GRU_NUM_CCH; ctxnum++) {
813                                 if (flag && gru == gru0 && ctxnum == ctxnum0)
814                                         break;
815                                 ngts = gru->gs_gts[ctxnum];
816                                 /*
817                                 * We are grabbing locks out of order, so trylock is
818                                 * needed. GTSs are usually not locked, so the odds of
819                                 * success are high. If trylock fails, try to steal a
820                                 * different GSEG.
821                                 */
822                                 if (ngts && is_gts_stealable(ngts, blade))
823                                         break;
824                                 ngts = NULL;
825                         }
826                         spin_unlock(&gru->gs_lock);
827                         if (ngts || (flag && gru == gru0 && ctxnum == ctxnum0))
828                                 break;
829                 }
830                 if (flag && gru == gru0)
831                         break;
832                 flag = 1;
833                 ctxnum = 0;
834                 gru = next_gru(blade, gru);
835         }
836         spin_unlock(&blade->bs_lock);
837
838         if (ngts) {
839                 gts->ustats.context_stolen++;
840                 ngts->ts_steal_jiffies = jiffies;
841                 gru_unload_context(ngts, is_kernel_context(ngts) ? 0 : 1);
842                 gts_stolen(ngts, blade);
843         } else {
844                 STAT(steal_context_failed);
845         }
846         gru_dbg(grudev,
847                 "stole gid %d, ctxnum %d from gts %p. Need cb %d, ds %d;"
848                 " avail cb %ld, ds %ld\n",
849                 gru->gs_gid, ctxnum, ngts, cbr, dsr, hweight64(gru->gs_cbr_map),
850                 hweight64(gru->gs_dsr_map));
851 }
852
853 /*
854  * Assign a gru context.
855  */
856 static int gru_assign_context_number(struct gru_state *gru)
857 {
858         int ctxnum;
859
860         ctxnum = find_first_zero_bit(&gru->gs_context_map, GRU_NUM_CCH);
861         __set_bit(ctxnum, &gru->gs_context_map);
862         return ctxnum;
863 }
864
865 /*
866  * Scan the GRUs on the local blade & assign a GRU context.
867  */
868 struct gru_state *gru_assign_gru_context(struct gru_thread_state *gts)
869 {
870         struct gru_state *gru, *grux;
871         int i, max_active_contexts;
872         int blade_id = gts->ts_user_blade_id;
873
874         if (blade_id < 0)
875                 blade_id = uv_numa_blade_id();
876 again:
877         gru = NULL;
878         max_active_contexts = GRU_NUM_CCH;
879         for_each_gru_on_blade(grux, blade_id, i) {
880                 if (!gru_check_chiplet_assignment(grux, gts))
881                         continue;
882                 if (check_gru_resources(grux, gts->ts_cbr_au_count,
883                                         gts->ts_dsr_au_count,
884                                         max_active_contexts)) {
885                         gru = grux;
886                         max_active_contexts = grux->gs_active_contexts;
887                         if (max_active_contexts == 0)
888                                 break;
889                 }
890         }
891
892         if (gru) {
893                 spin_lock(&gru->gs_lock);
894                 if (!check_gru_resources(gru, gts->ts_cbr_au_count,
895                                          gts->ts_dsr_au_count, GRU_NUM_CCH)) {
896                         spin_unlock(&gru->gs_lock);
897                         goto again;
898                 }
899                 reserve_gru_resources(gru, gts);
900                 gts->ts_gru = gru;
901                 gts->ts_blade = gru->gs_blade_id;
902                 gts->ts_ctxnum = gru_assign_context_number(gru);
903                 atomic_inc(&gts->ts_refcnt);
904                 gru->gs_gts[gts->ts_ctxnum] = gts;
905                 spin_unlock(&gru->gs_lock);
906
907                 STAT(assign_context);
908                 gru_dbg(grudev,
909                         "gseg %p, gts %p, gid %d, ctx %d, cbr %d, dsr %d\n",
910                         gseg_virtual_address(gts->ts_gru, gts->ts_ctxnum), gts,
911                         gts->ts_gru->gs_gid, gts->ts_ctxnum,
912                         gts->ts_cbr_au_count, gts->ts_dsr_au_count);
913         } else {
914                 gru_dbg(grudev, "failed to allocate a GTS %s\n", "");
915                 STAT(assign_context_failed);
916         }
917
918         return gru;
919 }
920
921 /*
922  * gru_nopage
923  *
924  * Map the user's GRU segment
925  *
926  *      Note: gru segments alway mmaped on GRU_GSEG_PAGESIZE boundaries.
927  */
928 int gru_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
929 {
930         struct gru_thread_state *gts;
931         unsigned long paddr, vaddr;
932
933         vaddr = (unsigned long)vmf->virtual_address;
934         gru_dbg(grudev, "vma %p, vaddr 0x%lx (0x%lx)\n",
935                 vma, vaddr, GSEG_BASE(vaddr));
936         STAT(nopfn);
937
938         /* The following check ensures vaddr is a valid address in the VMA */
939         gts = gru_find_thread_state(vma, TSID(vaddr, vma));
940         if (!gts)
941                 return VM_FAULT_SIGBUS;
942
943 again:
944         mutex_lock(&gts->ts_ctxlock);
945         preempt_disable();
946
947         gru_check_context_placement(gts);
948
949         if (!gts->ts_gru) {
950                 STAT(load_user_context);
951                 if (!gru_assign_gru_context(gts)) {
952                         preempt_enable();
953                         mutex_unlock(&gts->ts_ctxlock);
954                         set_current_state(TASK_INTERRUPTIBLE);
955                         schedule_timeout(GRU_ASSIGN_DELAY);  /* true hack ZZZ */
956                         if (gts->ts_steal_jiffies + GRU_STEAL_DELAY < jiffies)
957                                 gru_steal_context(gts);
958                         goto again;
959                 }
960                 gru_load_context(gts);
961                 paddr = gseg_physical_address(gts->ts_gru, gts->ts_ctxnum);
962                 remap_pfn_range(vma, vaddr & ~(GRU_GSEG_PAGESIZE - 1),
963                                 paddr >> PAGE_SHIFT, GRU_GSEG_PAGESIZE,
964                                 vma->vm_page_prot);
965         }
966
967         preempt_enable();
968         mutex_unlock(&gts->ts_ctxlock);
969
970         return VM_FAULT_NOPAGE;
971 }
972