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