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