]> err.no Git - linux-2.6/blob - arch/powerpc/platforms/cell/spufs/sched.c
[POWERPC] spufs: make state_mutex interruptible
[linux-2.6] / arch / powerpc / platforms / cell / spufs / sched.c
1 /* sched.c - SPU scheduler.
2  *
3  * Copyright (C) IBM 2005
4  * Author: Mark Nutter <mnutter@us.ibm.com>
5  *
6  * 2006-03-31   NUMA domains added.
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, or (at your option)
11  * 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., 675 Mass Ave, Cambridge, MA 02139, USA.
21  */
22
23 #undef DEBUG
24
25 #include <linux/module.h>
26 #include <linux/errno.h>
27 #include <linux/sched.h>
28 #include <linux/kernel.h>
29 #include <linux/mm.h>
30 #include <linux/completion.h>
31 #include <linux/vmalloc.h>
32 #include <linux/smp.h>
33 #include <linux/stddef.h>
34 #include <linux/unistd.h>
35 #include <linux/numa.h>
36 #include <linux/mutex.h>
37 #include <linux/notifier.h>
38 #include <linux/kthread.h>
39 #include <linux/pid_namespace.h>
40 #include <linux/proc_fs.h>
41 #include <linux/seq_file.h>
42
43 #include <asm/io.h>
44 #include <asm/mmu_context.h>
45 #include <asm/spu.h>
46 #include <asm/spu_csa.h>
47 #include <asm/spu_priv1.h>
48 #include "spufs.h"
49
50 struct spu_prio_array {
51         DECLARE_BITMAP(bitmap, MAX_PRIO);
52         struct list_head runq[MAX_PRIO];
53         spinlock_t runq_lock;
54         int nr_waiting;
55 };
56
57 static unsigned long spu_avenrun[3];
58 static struct spu_prio_array *spu_prio;
59 static struct task_struct *spusched_task;
60 static struct timer_list spusched_timer;
61
62 /*
63  * Priority of a normal, non-rt, non-niced'd process (aka nice level 0).
64  */
65 #define NORMAL_PRIO             120
66
67 /*
68  * Frequency of the spu scheduler tick.  By default we do one SPU scheduler
69  * tick for every 10 CPU scheduler ticks.
70  */
71 #define SPUSCHED_TICK           (10)
72
73 /*
74  * These are the 'tuning knobs' of the scheduler:
75  *
76  * Minimum timeslice is 5 msecs (or 1 spu scheduler tick, whichever is
77  * larger), default timeslice is 100 msecs, maximum timeslice is 800 msecs.
78  */
79 #define MIN_SPU_TIMESLICE       max(5 * HZ / (1000 * SPUSCHED_TICK), 1)
80 #define DEF_SPU_TIMESLICE       (100 * HZ / (1000 * SPUSCHED_TICK))
81
82 #define MAX_USER_PRIO           (MAX_PRIO - MAX_RT_PRIO)
83 #define SCALE_PRIO(x, prio) \
84         max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO / 2), MIN_SPU_TIMESLICE)
85
86 /*
87  * scale user-nice values [ -20 ... 0 ... 19 ] to time slice values:
88  * [800ms ... 100ms ... 5ms]
89  *
90  * The higher a thread's priority, the bigger timeslices
91  * it gets during one round of execution. But even the lowest
92  * priority thread gets MIN_TIMESLICE worth of execution time.
93  */
94 void spu_set_timeslice(struct spu_context *ctx)
95 {
96         if (ctx->prio < NORMAL_PRIO)
97                 ctx->time_slice = SCALE_PRIO(DEF_SPU_TIMESLICE * 4, ctx->prio);
98         else
99                 ctx->time_slice = SCALE_PRIO(DEF_SPU_TIMESLICE, ctx->prio);
100 }
101
102 /*
103  * Update scheduling information from the owning thread.
104  */
105 void __spu_update_sched_info(struct spu_context *ctx)
106 {
107         /*
108          * assert that the context is not on the runqueue, so it is safe
109          * to change its scheduling parameters.
110          */
111         BUG_ON(!list_empty(&ctx->rq));
112
113         /*
114          * 32-Bit assignments are atomic on powerpc, and we don't care about
115          * memory ordering here because retrieving the controlling thread is
116          * per definition racy.
117          */
118         ctx->tid = current->pid;
119
120         /*
121          * We do our own priority calculations, so we normally want
122          * ->static_prio to start with. Unfortunately this field
123          * contains junk for threads with a realtime scheduling
124          * policy so we have to look at ->prio in this case.
125          */
126         if (rt_prio(current->prio))
127                 ctx->prio = current->prio;
128         else
129                 ctx->prio = current->static_prio;
130         ctx->policy = current->policy;
131
132         /*
133          * TO DO: the context may be loaded, so we may need to activate
134          * it again on a different node. But it shouldn't hurt anything
135          * to update its parameters, because we know that the scheduler
136          * is not actively looking at this field, since it is not on the
137          * runqueue. The context will be rescheduled on the proper node
138          * if it is timesliced or preempted.
139          */
140         ctx->cpus_allowed = current->cpus_allowed;
141 }
142
143 void spu_update_sched_info(struct spu_context *ctx)
144 {
145         int node;
146
147         if (ctx->state == SPU_STATE_RUNNABLE) {
148                 node = ctx->spu->node;
149
150                 /*
151                  * Take list_mutex to sync with find_victim().
152                  */
153                 mutex_lock(&cbe_spu_info[node].list_mutex);
154                 __spu_update_sched_info(ctx);
155                 mutex_unlock(&cbe_spu_info[node].list_mutex);
156         } else {
157                 __spu_update_sched_info(ctx);
158         }
159 }
160
161 static int __node_allowed(struct spu_context *ctx, int node)
162 {
163         if (nr_cpus_node(node)) {
164                 cpumask_t mask = node_to_cpumask(node);
165
166                 if (cpus_intersects(mask, ctx->cpus_allowed))
167                         return 1;
168         }
169
170         return 0;
171 }
172
173 static int node_allowed(struct spu_context *ctx, int node)
174 {
175         int rval;
176
177         spin_lock(&spu_prio->runq_lock);
178         rval = __node_allowed(ctx, node);
179         spin_unlock(&spu_prio->runq_lock);
180
181         return rval;
182 }
183
184 static BLOCKING_NOTIFIER_HEAD(spu_switch_notifier);
185
186 void spu_switch_notify(struct spu *spu, struct spu_context *ctx)
187 {
188         blocking_notifier_call_chain(&spu_switch_notifier,
189                             ctx ? ctx->object_id : 0, spu);
190 }
191
192 static void notify_spus_active(void)
193 {
194         int node;
195
196         /*
197          * Wake up the active spu_contexts.
198          *
199          * When the awakened processes see their "notify_active" flag is set,
200          * they will call spu_switch_notify().
201          */
202         for_each_online_node(node) {
203                 struct spu *spu;
204
205                 mutex_lock(&cbe_spu_info[node].list_mutex);
206                 list_for_each_entry(spu, &cbe_spu_info[node].spus, cbe_list) {
207                         if (spu->alloc_state != SPU_FREE) {
208                                 struct spu_context *ctx = spu->ctx;
209                                 set_bit(SPU_SCHED_NOTIFY_ACTIVE,
210                                         &ctx->sched_flags);
211                                 mb();
212                                 wake_up_all(&ctx->stop_wq);
213                         }
214                 }
215                 mutex_unlock(&cbe_spu_info[node].list_mutex);
216         }
217 }
218
219 int spu_switch_event_register(struct notifier_block * n)
220 {
221         int ret;
222         ret = blocking_notifier_chain_register(&spu_switch_notifier, n);
223         if (!ret)
224                 notify_spus_active();
225         return ret;
226 }
227 EXPORT_SYMBOL_GPL(spu_switch_event_register);
228
229 int spu_switch_event_unregister(struct notifier_block * n)
230 {
231         return blocking_notifier_chain_unregister(&spu_switch_notifier, n);
232 }
233 EXPORT_SYMBOL_GPL(spu_switch_event_unregister);
234
235 /**
236  * spu_bind_context - bind spu context to physical spu
237  * @spu:        physical spu to bind to
238  * @ctx:        context to bind
239  */
240 static void spu_bind_context(struct spu *spu, struct spu_context *ctx)
241 {
242         pr_debug("%s: pid=%d SPU=%d NODE=%d\n", __FUNCTION__, current->pid,
243                  spu->number, spu->node);
244         spuctx_switch_state(ctx, SPU_UTIL_SYSTEM);
245
246         if (ctx->flags & SPU_CREATE_NOSCHED)
247                 atomic_inc(&cbe_spu_info[spu->node].reserved_spus);
248
249         ctx->stats.slb_flt_base = spu->stats.slb_flt;
250         ctx->stats.class2_intr_base = spu->stats.class2_intr;
251
252         spu->ctx = ctx;
253         spu->flags = 0;
254         ctx->spu = spu;
255         ctx->ops = &spu_hw_ops;
256         spu->pid = current->pid;
257         spu->tgid = current->tgid;
258         spu_associate_mm(spu, ctx->owner);
259         spu->ibox_callback = spufs_ibox_callback;
260         spu->wbox_callback = spufs_wbox_callback;
261         spu->stop_callback = spufs_stop_callback;
262         spu->mfc_callback = spufs_mfc_callback;
263         mb();
264         spu_unmap_mappings(ctx);
265         spu_restore(&ctx->csa, spu);
266         spu->timestamp = jiffies;
267         spu_cpu_affinity_set(spu, raw_smp_processor_id());
268         spu_switch_notify(spu, ctx);
269         ctx->state = SPU_STATE_RUNNABLE;
270
271         spuctx_switch_state(ctx, SPU_UTIL_IDLE_LOADED);
272 }
273
274 /*
275  * Must be used with the list_mutex held.
276  */
277 static inline int sched_spu(struct spu *spu)
278 {
279         BUG_ON(!mutex_is_locked(&cbe_spu_info[spu->node].list_mutex));
280
281         return (!spu->ctx || !(spu->ctx->flags & SPU_CREATE_NOSCHED));
282 }
283
284 static void aff_merge_remaining_ctxs(struct spu_gang *gang)
285 {
286         struct spu_context *ctx;
287
288         list_for_each_entry(ctx, &gang->aff_list_head, aff_list) {
289                 if (list_empty(&ctx->aff_list))
290                         list_add(&ctx->aff_list, &gang->aff_list_head);
291         }
292         gang->aff_flags |= AFF_MERGED;
293 }
294
295 static void aff_set_offsets(struct spu_gang *gang)
296 {
297         struct spu_context *ctx;
298         int offset;
299
300         offset = -1;
301         list_for_each_entry_reverse(ctx, &gang->aff_ref_ctx->aff_list,
302                                                                 aff_list) {
303                 if (&ctx->aff_list == &gang->aff_list_head)
304                         break;
305                 ctx->aff_offset = offset--;
306         }
307
308         offset = 0;
309         list_for_each_entry(ctx, gang->aff_ref_ctx->aff_list.prev, aff_list) {
310                 if (&ctx->aff_list == &gang->aff_list_head)
311                         break;
312                 ctx->aff_offset = offset++;
313         }
314
315         gang->aff_flags |= AFF_OFFSETS_SET;
316 }
317
318 static struct spu *aff_ref_location(struct spu_context *ctx, int mem_aff,
319                  int group_size, int lowest_offset)
320 {
321         struct spu *spu;
322         int node, n;
323
324         /*
325          * TODO: A better algorithm could be used to find a good spu to be
326          *       used as reference location for the ctxs chain.
327          */
328         node = cpu_to_node(raw_smp_processor_id());
329         for (n = 0; n < MAX_NUMNODES; n++, node++) {
330                 node = (node < MAX_NUMNODES) ? node : 0;
331                 if (!node_allowed(ctx, node))
332                         continue;
333                 mutex_lock(&cbe_spu_info[node].list_mutex);
334                 list_for_each_entry(spu, &cbe_spu_info[node].spus, cbe_list) {
335                         if ((!mem_aff || spu->has_mem_affinity) &&
336                                                         sched_spu(spu)) {
337                                 mutex_unlock(&cbe_spu_info[node].list_mutex);
338                                 return spu;
339                         }
340                 }
341                 mutex_unlock(&cbe_spu_info[node].list_mutex);
342         }
343         return NULL;
344 }
345
346 static void aff_set_ref_point_location(struct spu_gang *gang)
347 {
348         int mem_aff, gs, lowest_offset;
349         struct spu_context *ctx;
350         struct spu *tmp;
351
352         mem_aff = gang->aff_ref_ctx->flags & SPU_CREATE_AFFINITY_MEM;
353         lowest_offset = 0;
354         gs = 0;
355
356         list_for_each_entry(tmp, &gang->aff_list_head, aff_list)
357                 gs++;
358
359         list_for_each_entry_reverse(ctx, &gang->aff_ref_ctx->aff_list,
360                                                                 aff_list) {
361                 if (&ctx->aff_list == &gang->aff_list_head)
362                         break;
363                 lowest_offset = ctx->aff_offset;
364         }
365
366         gang->aff_ref_spu = aff_ref_location(gang->aff_ref_ctx, mem_aff, gs,
367                                                         lowest_offset);
368 }
369
370 static struct spu *ctx_location(struct spu *ref, int offset, int node)
371 {
372         struct spu *spu;
373
374         spu = NULL;
375         if (offset >= 0) {
376                 list_for_each_entry(spu, ref->aff_list.prev, aff_list) {
377                         BUG_ON(spu->node != node);
378                         if (offset == 0)
379                                 break;
380                         if (sched_spu(spu))
381                                 offset--;
382                 }
383         } else {
384                 list_for_each_entry_reverse(spu, ref->aff_list.next, aff_list) {
385                         BUG_ON(spu->node != node);
386                         if (offset == 0)
387                                 break;
388                         if (sched_spu(spu))
389                                 offset++;
390                 }
391         }
392
393         return spu;
394 }
395
396 /*
397  * affinity_check is called each time a context is going to be scheduled.
398  * It returns the spu ptr on which the context must run.
399  */
400 static int has_affinity(struct spu_context *ctx)
401 {
402         struct spu_gang *gang = ctx->gang;
403
404         if (list_empty(&ctx->aff_list))
405                 return 0;
406
407         if (!gang->aff_ref_spu) {
408                 if (!(gang->aff_flags & AFF_MERGED))
409                         aff_merge_remaining_ctxs(gang);
410                 if (!(gang->aff_flags & AFF_OFFSETS_SET))
411                         aff_set_offsets(gang);
412                 aff_set_ref_point_location(gang);
413         }
414
415         return gang->aff_ref_spu != NULL;
416 }
417
418 /**
419  * spu_unbind_context - unbind spu context from physical spu
420  * @spu:        physical spu to unbind from
421  * @ctx:        context to unbind
422  */
423 static void spu_unbind_context(struct spu *spu, struct spu_context *ctx)
424 {
425         pr_debug("%s: unbind pid=%d SPU=%d NODE=%d\n", __FUNCTION__,
426                  spu->pid, spu->number, spu->node);
427         spuctx_switch_state(ctx, SPU_UTIL_SYSTEM);
428
429         if (spu->ctx->flags & SPU_CREATE_NOSCHED)
430                 atomic_dec(&cbe_spu_info[spu->node].reserved_spus);
431
432         if (ctx->gang){
433                 mutex_lock(&ctx->gang->aff_mutex);
434                 if (has_affinity(ctx)) {
435                         if (atomic_dec_and_test(&ctx->gang->aff_sched_count))
436                                 ctx->gang->aff_ref_spu = NULL;
437                 }
438                 mutex_unlock(&ctx->gang->aff_mutex);
439         }
440
441         spu_switch_notify(spu, NULL);
442         spu_unmap_mappings(ctx);
443         spu_save(&ctx->csa, spu);
444         spu->timestamp = jiffies;
445         ctx->state = SPU_STATE_SAVED;
446         spu->ibox_callback = NULL;
447         spu->wbox_callback = NULL;
448         spu->stop_callback = NULL;
449         spu->mfc_callback = NULL;
450         spu_associate_mm(spu, NULL);
451         spu->pid = 0;
452         spu->tgid = 0;
453         ctx->ops = &spu_backing_ops;
454         spu->flags = 0;
455         spu->ctx = NULL;
456
457         ctx->stats.slb_flt +=
458                 (spu->stats.slb_flt - ctx->stats.slb_flt_base);
459         ctx->stats.class2_intr +=
460                 (spu->stats.class2_intr - ctx->stats.class2_intr_base);
461
462         /* This maps the underlying spu state to idle */
463         spuctx_switch_state(ctx, SPU_UTIL_IDLE_LOADED);
464         ctx->spu = NULL;
465 }
466
467 /**
468  * spu_add_to_rq - add a context to the runqueue
469  * @ctx:       context to add
470  */
471 static void __spu_add_to_rq(struct spu_context *ctx)
472 {
473         /*
474          * Unfortunately this code path can be called from multiple threads
475          * on behalf of a single context due to the way the problem state
476          * mmap support works.
477          *
478          * Fortunately we need to wake up all these threads at the same time
479          * and can simply skip the runqueue addition for every but the first
480          * thread getting into this codepath.
481          *
482          * It's still quite hacky, and long-term we should proxy all other
483          * threads through the owner thread so that spu_run is in control
484          * of all the scheduling activity for a given context.
485          */
486         if (list_empty(&ctx->rq)) {
487                 list_add_tail(&ctx->rq, &spu_prio->runq[ctx->prio]);
488                 set_bit(ctx->prio, spu_prio->bitmap);
489                 if (!spu_prio->nr_waiting++)
490                         __mod_timer(&spusched_timer, jiffies + SPUSCHED_TICK);
491         }
492 }
493
494 static void spu_add_to_rq(struct spu_context *ctx)
495 {
496         spin_lock(&spu_prio->runq_lock);
497         __spu_add_to_rq(ctx);
498         spin_unlock(&spu_prio->runq_lock);
499 }
500
501 static void __spu_del_from_rq(struct spu_context *ctx)
502 {
503         int prio = ctx->prio;
504
505         if (!list_empty(&ctx->rq)) {
506                 if (!--spu_prio->nr_waiting)
507                         del_timer(&spusched_timer);
508                 list_del_init(&ctx->rq);
509
510                 if (list_empty(&spu_prio->runq[prio]))
511                         clear_bit(prio, spu_prio->bitmap);
512         }
513 }
514
515 void spu_del_from_rq(struct spu_context *ctx)
516 {
517         spin_lock(&spu_prio->runq_lock);
518         __spu_del_from_rq(ctx);
519         spin_unlock(&spu_prio->runq_lock);
520 }
521
522 static void spu_prio_wait(struct spu_context *ctx)
523 {
524         DEFINE_WAIT(wait);
525
526         /*
527          * The caller must explicitly wait for a context to be loaded
528          * if the nosched flag is set.  If NOSCHED is not set, the caller
529          * queues the context and waits for an spu event or error.
530          */
531         BUG_ON(!(ctx->flags & SPU_CREATE_NOSCHED));
532
533         spin_lock(&spu_prio->runq_lock);
534         prepare_to_wait_exclusive(&ctx->stop_wq, &wait, TASK_INTERRUPTIBLE);
535         if (!signal_pending(current)) {
536                 __spu_add_to_rq(ctx);
537                 spin_unlock(&spu_prio->runq_lock);
538                 mutex_unlock(&ctx->state_mutex);
539                 schedule();
540                 mutex_lock(&ctx->state_mutex);
541                 spin_lock(&spu_prio->runq_lock);
542                 __spu_del_from_rq(ctx);
543         }
544         spin_unlock(&spu_prio->runq_lock);
545         __set_current_state(TASK_RUNNING);
546         remove_wait_queue(&ctx->stop_wq, &wait);
547 }
548
549 static struct spu *spu_get_idle(struct spu_context *ctx)
550 {
551         struct spu *spu, *aff_ref_spu;
552         int node, n;
553
554         if (ctx->gang) {
555                 mutex_lock(&ctx->gang->aff_mutex);
556                 if (has_affinity(ctx)) {
557                         aff_ref_spu = ctx->gang->aff_ref_spu;
558                         atomic_inc(&ctx->gang->aff_sched_count);
559                         mutex_unlock(&ctx->gang->aff_mutex);
560                         node = aff_ref_spu->node;
561
562                         mutex_lock(&cbe_spu_info[node].list_mutex);
563                         spu = ctx_location(aff_ref_spu, ctx->aff_offset, node);
564                         if (spu && spu->alloc_state == SPU_FREE)
565                                 goto found;
566                         mutex_unlock(&cbe_spu_info[node].list_mutex);
567
568                         mutex_lock(&ctx->gang->aff_mutex);
569                         if (atomic_dec_and_test(&ctx->gang->aff_sched_count))
570                                 ctx->gang->aff_ref_spu = NULL;
571                         mutex_unlock(&ctx->gang->aff_mutex);
572
573                         return NULL;
574                 }
575                 mutex_unlock(&ctx->gang->aff_mutex);
576         }
577         node = cpu_to_node(raw_smp_processor_id());
578         for (n = 0; n < MAX_NUMNODES; n++, node++) {
579                 node = (node < MAX_NUMNODES) ? node : 0;
580                 if (!node_allowed(ctx, node))
581                         continue;
582
583                 mutex_lock(&cbe_spu_info[node].list_mutex);
584                 list_for_each_entry(spu, &cbe_spu_info[node].spus, cbe_list) {
585                         if (spu->alloc_state == SPU_FREE)
586                                 goto found;
587                 }
588                 mutex_unlock(&cbe_spu_info[node].list_mutex);
589         }
590
591         return NULL;
592
593  found:
594         spu->alloc_state = SPU_USED;
595         mutex_unlock(&cbe_spu_info[node].list_mutex);
596         pr_debug("Got SPU %d %d\n", spu->number, spu->node);
597         spu_init_channels(spu);
598         return spu;
599 }
600
601 /**
602  * find_victim - find a lower priority context to preempt
603  * @ctx:        canidate context for running
604  *
605  * Returns the freed physical spu to run the new context on.
606  */
607 static struct spu *find_victim(struct spu_context *ctx)
608 {
609         struct spu_context *victim = NULL;
610         struct spu *spu;
611         int node, n;
612
613         /*
614          * Look for a possible preemption candidate on the local node first.
615          * If there is no candidate look at the other nodes.  This isn't
616          * exactly fair, but so far the whole spu scheduler tries to keep
617          * a strong node affinity.  We might want to fine-tune this in
618          * the future.
619          */
620  restart:
621         node = cpu_to_node(raw_smp_processor_id());
622         for (n = 0; n < MAX_NUMNODES; n++, node++) {
623                 node = (node < MAX_NUMNODES) ? node : 0;
624                 if (!node_allowed(ctx, node))
625                         continue;
626
627                 mutex_lock(&cbe_spu_info[node].list_mutex);
628                 list_for_each_entry(spu, &cbe_spu_info[node].spus, cbe_list) {
629                         struct spu_context *tmp = spu->ctx;
630
631                         if (tmp && tmp->prio > ctx->prio &&
632                             !(tmp->flags & SPU_CREATE_NOSCHED) &&
633                             (!victim || tmp->prio > victim->prio))
634                                 victim = spu->ctx;
635                 }
636                 mutex_unlock(&cbe_spu_info[node].list_mutex);
637
638                 if (victim) {
639                         /*
640                          * This nests ctx->state_mutex, but we always lock
641                          * higher priority contexts before lower priority
642                          * ones, so this is safe until we introduce
643                          * priority inheritance schemes.
644                          *
645                          * XXX if the highest priority context is locked,
646                          * this can loop a long time.  Might be better to
647                          * look at another context or give up after X retries.
648                          */
649                         if (!mutex_trylock(&victim->state_mutex)) {
650                                 victim = NULL;
651                                 goto restart;
652                         }
653
654                         spu = victim->spu;
655                         if (!spu || victim->prio <= ctx->prio) {
656                                 /*
657                                  * This race can happen because we've dropped
658                                  * the active list mutex.  Not a problem, just
659                                  * restart the search.
660                                  */
661                                 mutex_unlock(&victim->state_mutex);
662                                 victim = NULL;
663                                 goto restart;
664                         }
665
666                         mutex_lock(&cbe_spu_info[node].list_mutex);
667                         cbe_spu_info[node].nr_active--;
668                         spu_unbind_context(spu, victim);
669                         mutex_unlock(&cbe_spu_info[node].list_mutex);
670
671                         victim->stats.invol_ctx_switch++;
672                         spu->stats.invol_ctx_switch++;
673                         spu_add_to_rq(victim);
674
675                         mutex_unlock(&victim->state_mutex);
676
677                         return spu;
678                 }
679         }
680
681         return NULL;
682 }
683
684 static void __spu_schedule(struct spu *spu, struct spu_context *ctx)
685 {
686         int node = spu->node;
687         int success = 0;
688
689         spu_set_timeslice(ctx);
690
691         mutex_lock(&cbe_spu_info[node].list_mutex);
692         if (spu->ctx == NULL) {
693                 spu_bind_context(spu, ctx);
694                 cbe_spu_info[node].nr_active++;
695                 spu->alloc_state = SPU_USED;
696                 success = 1;
697         }
698         mutex_unlock(&cbe_spu_info[node].list_mutex);
699
700         if (success)
701                 wake_up_all(&ctx->run_wq);
702         else
703                 spu_add_to_rq(ctx);
704 }
705
706 static void spu_schedule(struct spu *spu, struct spu_context *ctx)
707 {
708         /* not a candidate for interruptible because it's called either
709            from the scheduler thread or from spu_deactivate */
710         mutex_lock(&ctx->state_mutex);
711         __spu_schedule(spu, ctx);
712         spu_release(ctx);
713 }
714
715 static void spu_unschedule(struct spu *spu, struct spu_context *ctx)
716 {
717         int node = spu->node;
718
719         mutex_lock(&cbe_spu_info[node].list_mutex);
720         cbe_spu_info[node].nr_active--;
721         spu->alloc_state = SPU_FREE;
722         spu_unbind_context(spu, ctx);
723         ctx->stats.invol_ctx_switch++;
724         spu->stats.invol_ctx_switch++;
725         mutex_unlock(&cbe_spu_info[node].list_mutex);
726 }
727
728 /**
729  * spu_activate - find a free spu for a context and execute it
730  * @ctx:        spu context to schedule
731  * @flags:      flags (currently ignored)
732  *
733  * Tries to find a free spu to run @ctx.  If no free spu is available
734  * add the context to the runqueue so it gets woken up once an spu
735  * is available.
736  */
737 int spu_activate(struct spu_context *ctx, unsigned long flags)
738 {
739         struct spu *spu;
740
741         /*
742          * If there are multiple threads waiting for a single context
743          * only one actually binds the context while the others will
744          * only be able to acquire the state_mutex once the context
745          * already is in runnable state.
746          */
747         if (ctx->spu)
748                 return 0;
749
750 spu_activate_top:
751         if (signal_pending(current))
752                 return -ERESTARTSYS;
753
754         spu = spu_get_idle(ctx);
755         /*
756          * If this is a realtime thread we try to get it running by
757          * preempting a lower priority thread.
758          */
759         if (!spu && rt_prio(ctx->prio))
760                 spu = find_victim(ctx);
761         if (spu) {
762                 unsigned long runcntl;
763
764                 runcntl = ctx->ops->runcntl_read(ctx);
765                 __spu_schedule(spu, ctx);
766                 if (runcntl & SPU_RUNCNTL_RUNNABLE)
767                         spuctx_switch_state(ctx, SPU_UTIL_USER);
768
769                 return 0;
770         }
771
772         if (ctx->flags & SPU_CREATE_NOSCHED) {
773                 spu_prio_wait(ctx);
774                 goto spu_activate_top;
775         }
776
777         spu_add_to_rq(ctx);
778
779         return 0;
780 }
781
782 /**
783  * grab_runnable_context - try to find a runnable context
784  *
785  * Remove the highest priority context on the runqueue and return it
786  * to the caller.  Returns %NULL if no runnable context was found.
787  */
788 static struct spu_context *grab_runnable_context(int prio, int node)
789 {
790         struct spu_context *ctx;
791         int best;
792
793         spin_lock(&spu_prio->runq_lock);
794         best = find_first_bit(spu_prio->bitmap, prio);
795         while (best < prio) {
796                 struct list_head *rq = &spu_prio->runq[best];
797
798                 list_for_each_entry(ctx, rq, rq) {
799                         /* XXX(hch): check for affinity here aswell */
800                         if (__node_allowed(ctx, node)) {
801                                 __spu_del_from_rq(ctx);
802                                 goto found;
803                         }
804                 }
805                 best++;
806         }
807         ctx = NULL;
808  found:
809         spin_unlock(&spu_prio->runq_lock);
810         return ctx;
811 }
812
813 static int __spu_deactivate(struct spu_context *ctx, int force, int max_prio)
814 {
815         struct spu *spu = ctx->spu;
816         struct spu_context *new = NULL;
817
818         if (spu) {
819                 new = grab_runnable_context(max_prio, spu->node);
820                 if (new || force) {
821                         spu_unschedule(spu, ctx);
822                         if (new) {
823                                 if (new->flags & SPU_CREATE_NOSCHED)
824                                         wake_up(&new->stop_wq);
825                                 else {
826                                         spu_release(ctx);
827                                         spu_schedule(spu, new);
828                                         /* this one can't easily be made
829                                            interruptible */
830                                         mutex_lock(&ctx->state_mutex);
831                                 }
832                         }
833                 }
834         }
835
836         return new != NULL;
837 }
838
839 /**
840  * spu_deactivate - unbind a context from it's physical spu
841  * @ctx:        spu context to unbind
842  *
843  * Unbind @ctx from the physical spu it is running on and schedule
844  * the highest priority context to run on the freed physical spu.
845  */
846 void spu_deactivate(struct spu_context *ctx)
847 {
848         __spu_deactivate(ctx, 1, MAX_PRIO);
849 }
850
851 /**
852  * spu_yield -  yield a physical spu if others are waiting
853  * @ctx:        spu context to yield
854  *
855  * Check if there is a higher priority context waiting and if yes
856  * unbind @ctx from the physical spu and schedule the highest
857  * priority context to run on the freed physical spu instead.
858  */
859 void spu_yield(struct spu_context *ctx)
860 {
861         if (!(ctx->flags & SPU_CREATE_NOSCHED)) {
862                 mutex_lock(&ctx->state_mutex);
863                 __spu_deactivate(ctx, 0, MAX_PRIO);
864                 mutex_unlock(&ctx->state_mutex);
865         }
866 }
867
868 static noinline void spusched_tick(struct spu_context *ctx)
869 {
870         struct spu_context *new = NULL;
871         struct spu *spu = NULL;
872         u32 status;
873
874         if (spu_acquire(ctx))
875                 BUG();  /* a kernel thread never has signals pending */
876
877         if (ctx->state != SPU_STATE_RUNNABLE)
878                 goto out;
879         if (spu_stopped(ctx, &status))
880                 goto out;
881         if (ctx->flags & SPU_CREATE_NOSCHED)
882                 goto out;
883         if (ctx->policy == SCHED_FIFO)
884                 goto out;
885
886         if (--ctx->time_slice)
887                 goto out;
888
889         spu = ctx->spu;
890         new = grab_runnable_context(ctx->prio + 1, spu->node);
891         if (new) {
892                 spu_unschedule(spu, ctx);
893                 spu_add_to_rq(ctx);
894         } else {
895                 ctx->time_slice++;
896         }
897 out:
898         spu_release(ctx);
899
900         if (new)
901                 spu_schedule(spu, new);
902 }
903
904 /**
905  * count_active_contexts - count nr of active tasks
906  *
907  * Return the number of tasks currently running or waiting to run.
908  *
909  * Note that we don't take runq_lock / list_mutex here.  Reading
910  * a single 32bit value is atomic on powerpc, and we don't care
911  * about memory ordering issues here.
912  */
913 static unsigned long count_active_contexts(void)
914 {
915         int nr_active = 0, node;
916
917         for (node = 0; node < MAX_NUMNODES; node++)
918                 nr_active += cbe_spu_info[node].nr_active;
919         nr_active += spu_prio->nr_waiting;
920
921         return nr_active;
922 }
923
924 /**
925  * spu_calc_load - given tick count, update the avenrun load estimates.
926  * @tick:       tick count
927  *
928  * No locking against reading these values from userspace, as for
929  * the CPU loadavg code.
930  */
931 static void spu_calc_load(unsigned long ticks)
932 {
933         unsigned long active_tasks; /* fixed-point */
934         static int count = LOAD_FREQ;
935
936         count -= ticks;
937
938         if (unlikely(count < 0)) {
939                 active_tasks = count_active_contexts() * FIXED_1;
940                 do {
941                         CALC_LOAD(spu_avenrun[0], EXP_1, active_tasks);
942                         CALC_LOAD(spu_avenrun[1], EXP_5, active_tasks);
943                         CALC_LOAD(spu_avenrun[2], EXP_15, active_tasks);
944                         count += LOAD_FREQ;
945                 } while (count < 0);
946         }
947 }
948
949 static void spusched_wake(unsigned long data)
950 {
951         mod_timer(&spusched_timer, jiffies + SPUSCHED_TICK);
952         wake_up_process(spusched_task);
953         spu_calc_load(SPUSCHED_TICK);
954 }
955
956 static int spusched_thread(void *unused)
957 {
958         struct spu *spu;
959         int node;
960
961         while (!kthread_should_stop()) {
962                 set_current_state(TASK_INTERRUPTIBLE);
963                 schedule();
964                 for (node = 0; node < MAX_NUMNODES; node++) {
965                         struct mutex *mtx = &cbe_spu_info[node].list_mutex;
966
967                         mutex_lock(mtx);
968                         list_for_each_entry(spu, &cbe_spu_info[node].spus,
969                                         cbe_list) {
970                                 struct spu_context *ctx = spu->ctx;
971
972                                 if (ctx) {
973                                         mutex_unlock(mtx);
974                                         spusched_tick(ctx);
975                                         mutex_lock(mtx);
976                                 }
977                         }
978                         mutex_unlock(mtx);
979                 }
980         }
981
982         return 0;
983 }
984
985 void spuctx_switch_state(struct spu_context *ctx,
986                 enum spu_utilization_state new_state)
987 {
988         unsigned long long curtime;
989         signed long long delta;
990         struct timespec ts;
991         struct spu *spu;
992         enum spu_utilization_state old_state;
993
994         ktime_get_ts(&ts);
995         curtime = timespec_to_ns(&ts);
996         delta = curtime - ctx->stats.tstamp;
997
998         WARN_ON(!mutex_is_locked(&ctx->state_mutex));
999         WARN_ON(delta < 0);
1000
1001         spu = ctx->spu;
1002         old_state = ctx->stats.util_state;
1003         ctx->stats.util_state = new_state;
1004         ctx->stats.tstamp = curtime;
1005
1006         /*
1007          * Update the physical SPU utilization statistics.
1008          */
1009         if (spu) {
1010                 ctx->stats.times[old_state] += delta;
1011                 spu->stats.times[old_state] += delta;
1012                 spu->stats.util_state = new_state;
1013                 spu->stats.tstamp = curtime;
1014         }
1015 }
1016
1017 #define LOAD_INT(x) ((x) >> FSHIFT)
1018 #define LOAD_FRAC(x) LOAD_INT(((x) & (FIXED_1-1)) * 100)
1019
1020 static int show_spu_loadavg(struct seq_file *s, void *private)
1021 {
1022         int a, b, c;
1023
1024         a = spu_avenrun[0] + (FIXED_1/200);
1025         b = spu_avenrun[1] + (FIXED_1/200);
1026         c = spu_avenrun[2] + (FIXED_1/200);
1027
1028         /*
1029          * Note that last_pid doesn't really make much sense for the
1030          * SPU loadavg (it even seems very odd on the CPU side...),
1031          * but we include it here to have a 100% compatible interface.
1032          */
1033         seq_printf(s, "%d.%02d %d.%02d %d.%02d %ld/%d %d\n",
1034                 LOAD_INT(a), LOAD_FRAC(a),
1035                 LOAD_INT(b), LOAD_FRAC(b),
1036                 LOAD_INT(c), LOAD_FRAC(c),
1037                 count_active_contexts(),
1038                 atomic_read(&nr_spu_contexts),
1039                 current->nsproxy->pid_ns->last_pid);
1040         return 0;
1041 }
1042
1043 static int spu_loadavg_open(struct inode *inode, struct file *file)
1044 {
1045         return single_open(file, show_spu_loadavg, NULL);
1046 }
1047
1048 static const struct file_operations spu_loadavg_fops = {
1049         .open           = spu_loadavg_open,
1050         .read           = seq_read,
1051         .llseek         = seq_lseek,
1052         .release        = single_release,
1053 };
1054
1055 int __init spu_sched_init(void)
1056 {
1057         struct proc_dir_entry *entry;
1058         int err = -ENOMEM, i;
1059
1060         spu_prio = kzalloc(sizeof(struct spu_prio_array), GFP_KERNEL);
1061         if (!spu_prio)
1062                 goto out;
1063
1064         for (i = 0; i < MAX_PRIO; i++) {
1065                 INIT_LIST_HEAD(&spu_prio->runq[i]);
1066                 __clear_bit(i, spu_prio->bitmap);
1067         }
1068         spin_lock_init(&spu_prio->runq_lock);
1069
1070         setup_timer(&spusched_timer, spusched_wake, 0);
1071
1072         spusched_task = kthread_run(spusched_thread, NULL, "spusched");
1073         if (IS_ERR(spusched_task)) {
1074                 err = PTR_ERR(spusched_task);
1075                 goto out_free_spu_prio;
1076         }
1077
1078         entry = create_proc_entry("spu_loadavg", 0, NULL);
1079         if (!entry)
1080                 goto out_stop_kthread;
1081         entry->proc_fops = &spu_loadavg_fops;
1082
1083         pr_debug("spusched: tick: %d, min ticks: %d, default ticks: %d\n",
1084                         SPUSCHED_TICK, MIN_SPU_TIMESLICE, DEF_SPU_TIMESLICE);
1085         return 0;
1086
1087  out_stop_kthread:
1088         kthread_stop(spusched_task);
1089  out_free_spu_prio:
1090         kfree(spu_prio);
1091  out:
1092         return err;
1093 }
1094
1095 void spu_sched_exit(void)
1096 {
1097         struct spu *spu;
1098         int node;
1099
1100         remove_proc_entry("spu_loadavg", NULL);
1101
1102         del_timer_sync(&spusched_timer);
1103         kthread_stop(spusched_task);
1104
1105         for (node = 0; node < MAX_NUMNODES; node++) {
1106                 mutex_lock(&cbe_spu_info[node].list_mutex);
1107                 list_for_each_entry(spu, &cbe_spu_info[node].spus, cbe_list)
1108                         if (spu->alloc_state != SPU_FREE)
1109                                 spu->alloc_state = SPU_FREE;
1110                 mutex_unlock(&cbe_spu_info[node].list_mutex);
1111         }
1112         kfree(spu_prio);
1113 }