3.1.7 branch.
[minix.git] / kernel / system.c
blob4cb223852acc068195476fb1294d1b57b7707e4d
1 /* This task handles the interface between the kernel and user-level servers.
2 * System services can be accessed by doing a system call. System calls are
3 * transformed into request messages, which are handled by this task. By
4 * convention, a sys_call() is transformed in a SYS_CALL request message that
5 * is handled in a function named do_call().
7 * A private call vector is used to map all system calls to the functions that
8 * handle them. The actual handler functions are contained in separate files
9 * to keep this file clean. The call vector is used in the system task's main
10 * loop to handle all incoming requests.
12 * In addition to the main sys_task() entry point, which starts the main loop,
13 * there are several other minor entry points:
14 * get_priv: assign privilege structure to user or system process
15 * set_sendto_bit: allow a process to send messages to a new target
16 * unset_sendto_bit: disallow a process from sending messages to a target
17 * send_sig: send a signal directly to a system process
18 * cause_sig: take action to cause a signal to occur via a signal mgr
19 * sig_delay_done: tell PM that a process is not sending
20 * umap_bios: map virtual address in BIOS_SEG to physical
21 * get_randomness: accumulate randomness in a buffer
22 * clear_endpoint: remove a process' ability to send and receive messages
24 * Changes:
25 * Nov 22, 2009 get_priv supports static priv ids (Cristiano Giuffrida)
26 * Aug 04, 2005 check if system call is allowed (Jorrit N. Herder)
27 * Jul 20, 2005 send signal to services with message (Jorrit N. Herder)
28 * Jan 15, 2005 new, generalized virtual copy function (Jorrit N. Herder)
29 * Oct 10, 2004 dispatch system calls from call vector (Jorrit N. Herder)
30 * Sep 30, 2004 source code documentation updated (Jorrit N. Herder)
33 #include "debug.h"
34 #include "kernel.h"
35 #include "system.h"
36 #include "proc.h"
37 #include "vm.h"
38 #include <stdlib.h>
39 #include <assert.h>
40 #include <signal.h>
41 #include <unistd.h>
42 #include <sys/sigcontext.h>
43 #include <minix/endpoint.h>
44 #include <minix/safecopies.h>
46 /* Declaration of the call vector that defines the mapping of system calls
47 * to handler functions. The vector is initialized in sys_init() with map(),
48 * which makes sure the system call numbers are ok. No space is allocated,
49 * because the dummy is declared extern. If an illegal call is given, the
50 * array size will be negative and this won't compile.
52 PRIVATE int (*call_vec[NR_SYS_CALLS])(struct proc * caller, message *m_ptr);
53 PRIVATE char *callnames[NR_SYS_CALLS];
55 #define map(call_nr, handler) \
56 {extern int dummy[NR_SYS_CALLS>(unsigned)(call_nr-KERNEL_CALL) ? 1:-1];} \
57 callnames[(call_nr-KERNEL_CALL)] = #call_nr; \
58 call_vec[(call_nr-KERNEL_CALL)] = (handler)
60 PRIVATE void kernel_call_finish(struct proc * caller, message *msg, int result)
62 if(result == VMSUSPEND) {
63 /* Special case: message has to be saved for handling
64 * until VM tells us it's allowed. VM has been notified
65 * and we must wait for its reply to restart the call.
67 assert(RTS_ISSET(caller, RTS_VMREQUEST));
68 assert(caller->p_vmrequest.type == VMSTYPE_KERNELCALL);
69 caller->p_vmrequest.saved.reqmsg = *msg;
70 caller->p_misc_flags |= MF_KCALL_RESUME;
71 } else {
73 * call is finished, we could have been suspended because of VM,
74 * remove the request message
76 caller->p_vmrequest.saved.reqmsg.m_source = NONE;
77 if (result != EDONTREPLY) {
78 /* copy the result as a message to the original user buffer */
79 msg->m_source = SYSTEM;
80 msg->m_type = result; /* report status of call */
81 if (copy_msg_to_user(caller, msg,
82 (message *)caller->p_delivermsg_vir)) {
83 printf("WARNING wrong user pointer 0x%08x from "
84 "process %s / %d\n",
85 caller->p_delivermsg_vir,
86 caller->p_name,
87 caller->p_endpoint);
93 PRIVATE int kernel_call_dispatch(struct proc * caller, message *msg)
95 int result = OK;
96 int call_nr;
98 call_nr = msg->m_type - KERNEL_CALL;
100 /* See if the caller made a valid request and try to handle it. */
101 if (call_nr < 0 || call_nr >= NR_SYS_CALLS) { /* check call number */
102 printf("SYSTEM: illegal request %d from %d.\n",
103 call_nr,msg->m_source);
104 result = EBADREQUEST; /* illegal message type */
106 else if (!GET_BIT(priv(caller)->s_k_call_mask, call_nr)) {
107 printf("SYSTEM: denied request %d from %d.\n",
108 call_nr,msg->m_source);
109 result = ECALLDENIED; /* illegal message type */
110 } else {
111 /* handle the system call */
112 if (call_vec[call_nr])
113 result = (*call_vec[call_nr])(caller, msg);
114 else {
115 printf("Unused kernel call %d from %d\n",
116 call_nr, caller->p_endpoint);
117 result = EBADREQUEST;
121 return result;
124 /*===========================================================================*
125 * kernel_call *
126 *===========================================================================*/
128 * this function checks the basic syscall parameters and if accepted it
129 * dispatches its handling to the right handler
131 PUBLIC void kernel_call(message *m_user, struct proc * caller)
133 int result = OK;
134 message msg;
136 caller->p_delivermsg_vir = (vir_bytes) m_user;
138 * the ldt and cr3 of the caller process is loaded because it just've trapped
139 * into the kernel or was already set in switch_to_user() before we resume
140 * execution of an interrupted kernel call
142 if (copy_msg_from_user(caller, m_user, &msg) == 0) {
143 msg.m_source = caller->p_endpoint;
144 result = kernel_call_dispatch(caller, &msg);
146 else {
147 printf("WARNING wrong user pointer 0x%08x from process %s / %d\n",
148 m_user, caller->p_name, caller->p_endpoint);
149 result = EBADREQUEST;
152 kernel_call_finish(caller, &msg, result);
155 /*===========================================================================*
156 * initialize *
157 *===========================================================================*/
158 PUBLIC void system_init(void)
160 register struct priv *sp;
161 int i;
163 /* Initialize IRQ handler hooks. Mark all hooks available. */
164 for (i=0; i<NR_IRQ_HOOKS; i++) {
165 irq_hooks[i].proc_nr_e = NONE;
168 /* Initialize all alarm timers for all processes. */
169 for (sp=BEG_PRIV_ADDR; sp < END_PRIV_ADDR; sp++) {
170 tmr_inittimer(&(sp->s_alarm_timer));
173 /* Initialize the call vector to a safe default handler. Some system calls
174 * may be disabled or nonexistant. Then explicitely map known calls to their
175 * handler functions. This is done with a macro that gives a compile error
176 * if an illegal call number is used. The ordering is not important here.
178 for (i=0; i<NR_SYS_CALLS; i++) {
179 call_vec[i] = NULL;
180 callnames[i] = "unused";
183 /* Process management. */
184 map(SYS_FORK, do_fork); /* a process forked a new process */
185 map(SYS_EXEC, do_exec); /* update process after execute */
186 map(SYS_CLEAR, do_clear); /* clean up after process exit */
187 map(SYS_EXIT, do_exit); /* a system process wants to exit */
188 map(SYS_PRIVCTL, do_privctl); /* system privileges control */
189 map(SYS_TRACE, do_trace); /* request a trace operation */
190 map(SYS_SETGRANT, do_setgrant); /* get/set own parameters */
191 map(SYS_RUNCTL, do_runctl); /* set/clear stop flag of a process */
192 map(SYS_UPDATE, do_update); /* update a process into another */
193 map(SYS_STATECTL, do_statectl); /* let a process control its state */
195 /* Signal handling. */
196 map(SYS_KILL, do_kill); /* cause a process to be signaled */
197 map(SYS_GETKSIG, do_getksig); /* signal manager checks for signals */
198 map(SYS_ENDKSIG, do_endksig); /* signal manager finished signal */
199 map(SYS_SIGSEND, do_sigsend); /* start POSIX-style signal */
200 map(SYS_SIGRETURN, do_sigreturn); /* return from POSIX-style signal */
202 /* Device I/O. */
203 map(SYS_IRQCTL, do_irqctl); /* interrupt control operations */
204 map(SYS_DEVIO, do_devio); /* inb, inw, inl, outb, outw, outl */
205 map(SYS_VDEVIO, do_vdevio); /* vector with devio requests */
207 /* Memory management. */
208 map(SYS_NEWMAP, do_newmap); /* set up a process memory map */
209 map(SYS_SEGCTL, do_segctl); /* add segment and get selector */
210 map(SYS_MEMSET, do_memset); /* write char to memory area */
211 map(SYS_VMCTL, do_vmctl); /* various VM process settings */
213 /* Copying. */
214 map(SYS_UMAP, do_umap); /* map virtual to physical address */
215 map(SYS_VIRCOPY, do_vircopy); /* use pure virtual addressing */
216 map(SYS_PHYSCOPY, do_copy); /* use physical addressing */
217 map(SYS_SAFECOPYFROM, do_safecopy_from);/* copy with pre-granted permission */
218 map(SYS_SAFECOPYTO, do_safecopy_to); /* copy with pre-granted permission */
219 map(SYS_VSAFECOPY, do_vsafecopy); /* vectored safecopy */
221 /* Mapping. */
222 map(SYS_SAFEMAP, do_safemap); /* map pages from other process */
223 map(SYS_SAFEREVMAP, do_saferevmap); /* grantor revokes the map grant */
224 map(SYS_SAFEUNMAP, do_safeunmap); /* requestor unmaps the mapped pages */
226 /* Clock functionality. */
227 map(SYS_TIMES, do_times); /* get uptime and process times */
228 map(SYS_SETALARM, do_setalarm); /* schedule a synchronous alarm */
229 map(SYS_STIME, do_stime); /* set the boottime */
230 map(SYS_VTIMER, do_vtimer); /* set or retrieve a virtual timer */
232 /* System control. */
233 map(SYS_ABORT, do_abort); /* abort MINIX */
234 map(SYS_GETINFO, do_getinfo); /* request system information */
235 map(SYS_SYSCTL, do_sysctl); /* misc system manipulation */
237 /* Profiling. */
238 map(SYS_SPROF, do_sprofile); /* start/stop statistical profiling */
239 map(SYS_CPROF, do_cprofile); /* get/reset call profiling data */
240 map(SYS_PROFBUF, do_profbuf); /* announce locations to kernel */
242 /* i386-specific. */
243 #if _MINIX_CHIP == _CHIP_INTEL
244 map(SYS_INT86, do_int86); /* real-mode BIOS calls */
245 map(SYS_READBIOS, do_readbios); /* read from BIOS locations */
246 map(SYS_IOPENABLE, do_iopenable); /* Enable I/O */
247 map(SYS_SDEVIO, do_sdevio); /* phys_insb, _insw, _outsb, _outsw */
249 /* Machine state switching. */
250 map(SYS_SETMCONTEXT, do_setmcontext); /* set machine context */
251 map(SYS_GETMCONTEXT, do_getmcontext); /* get machine context */
252 #endif
254 /* Scheduling */
255 map(SYS_SCHEDULE, do_schedule); /* reschedule a process */
256 map(SYS_SCHEDCTL, do_schedctl); /* change process scheduler */
259 /*===========================================================================*
260 * get_priv *
261 *===========================================================================*/
262 PUBLIC int get_priv(rc, priv_id)
263 register struct proc *rc; /* new (child) process pointer */
264 int priv_id; /* privilege id */
266 /* Allocate a new privilege structure for a system process. Privilege ids
267 * can be assigned either statically or dynamically.
269 register struct priv *sp; /* privilege structure */
271 if(priv_id == NULL_PRIV_ID) { /* allocate slot dynamically */
272 for (sp = BEG_DYN_PRIV_ADDR; sp < END_DYN_PRIV_ADDR; ++sp)
273 if (sp->s_proc_nr == NONE) break;
274 if (sp >= END_DYN_PRIV_ADDR) return(ENOSPC);
276 else { /* allocate slot from id */
277 if(!is_static_priv_id(priv_id)) {
278 return EINVAL; /* invalid static priv id */
280 if(priv[priv_id].s_proc_nr != NONE) {
281 return EBUSY; /* slot already in use */
283 sp = &priv[priv_id];
285 rc->p_priv = sp; /* assign new slot */
286 rc->p_priv->s_proc_nr = proc_nr(rc); /* set association */
288 return(OK);
291 /*===========================================================================*
292 * set_sendto_bit *
293 *===========================================================================*/
294 PUBLIC void set_sendto_bit(const struct proc *rp, int id)
296 /* Allow a process to send messages to the process(es) associated with the
297 * system privilege structure with the given ID.
300 /* Disallow the process from sending to a process privilege structure with no
301 * associated process, and disallow the process from sending to itself.
303 if (id_to_nr(id) == NONE || priv_id(rp) == id) {
304 unset_sys_bit(priv(rp)->s_ipc_to, id);
305 return;
308 set_sys_bit(priv(rp)->s_ipc_to, id);
310 /* The process that this process can now send to, must be able to reply (or
311 * vice versa). Therefore, its send mask should be updated as well. Ignore
312 * receivers that don't support traps other than RECEIVE, they can't reply
313 * or send messages anyway.
315 if (priv_addr(id)->s_trap_mask & ~((1 << RECEIVE)))
316 set_sys_bit(priv_addr(id)->s_ipc_to, priv_id(rp));
319 /*===========================================================================*
320 * unset_sendto_bit *
321 *===========================================================================*/
322 PUBLIC void unset_sendto_bit(const struct proc *rp, int id)
324 /* Prevent a process from sending to another process. Retain the send mask
325 * symmetry by also unsetting the bit for the other direction.
328 unset_sys_bit(priv(rp)->s_ipc_to, id);
330 unset_sys_bit(priv_addr(id)->s_ipc_to, priv_id(rp));
333 /*===========================================================================*
334 * send_sig *
335 *===========================================================================*/
336 PUBLIC void send_sig(endpoint_t proc_nr, int sig_nr)
338 /* Notify a system process about a signal. This is straightforward. Simply
339 * set the signal that is to be delivered in the pending signals map and
340 * send a notification with source SYSTEM.
342 register struct proc *rp;
344 if(!isokprocn(proc_nr) || isemptyn(proc_nr))
345 panic("send_sig to empty process: %d", proc_nr);
347 rp = proc_addr(proc_nr);
348 sigaddset(&priv(rp)->s_sig_pending, sig_nr);
349 mini_notify(proc_addr(SYSTEM), rp->p_endpoint);
352 /*===========================================================================*
353 * cause_sig *
354 *===========================================================================*/
355 PUBLIC void cause_sig(proc_nr, sig_nr)
356 proc_nr_t proc_nr; /* process to be signalled */
357 int sig_nr; /* signal to be sent */
359 /* A system process wants to send a signal to a process. Examples are:
360 * - HARDWARE wanting to cause a SIGSEGV after a CPU exception
361 * - TTY wanting to cause SIGINT upon getting a DEL
362 * - FS wanting to cause SIGPIPE for a broken pipe
363 * Signals are handled by sending a message to the signal manager assigned to
364 * the process. This function handles the signals and makes sure the signal
365 * manager gets them by sending a notification. The process being signaled
366 * is blocked while the signal manager has not finished all signals for it.
367 * Race conditions between calls to this function and the system calls that
368 * process pending kernel signals cannot exist. Signal related functions are
369 * only called when a user process causes a CPU exception and from the kernel
370 * process level, which runs to completion.
372 register struct proc *rp;
373 endpoint_t sig_mgr;
375 /* Lookup signal manager. */
376 rp = proc_addr(proc_nr);
377 sig_mgr = priv(rp)->s_sig_mgr;
379 /* If the target is the signal manager of itself, send the signal directly. */
380 if(rp->p_endpoint == sig_mgr) {
381 if(SIGS_IS_LETHAL(sig_nr)) {
382 proc_stacktrace(rp);
383 panic("cause_sig: signal manager gets lethal signal %d for itself",
384 sig_nr);
386 sigaddset(&priv(rp)->s_sig_pending, sig_nr);
387 send_sig(rp->p_endpoint, SIGKSIGSM);
388 return;
391 /* Check if the signal is already pending. Process it otherwise. */
392 if (! sigismember(&rp->p_pending, sig_nr)) {
393 sigaddset(&rp->p_pending, sig_nr);
394 if (! (RTS_ISSET(rp, RTS_SIGNALED))) { /* other pending */
395 RTS_SET(rp, RTS_SIGNALED | RTS_SIG_PENDING);
396 send_sig(sig_mgr, SIGKSIG);
401 /*===========================================================================*
402 * sig_delay_done *
403 *===========================================================================*/
404 PUBLIC void sig_delay_done(struct proc *rp)
406 /* A process is now known not to send any direct messages.
407 * Tell PM that the stop delay has ended, by sending a signal to the process.
408 * Used for actual signal delivery.
411 rp->p_misc_flags &= ~MF_SIG_DELAY;
413 cause_sig(proc_nr(rp), SIGSNDELAY);
416 #if _MINIX_CHIP == _CHIP_INTEL
418 /*===========================================================================*
419 * umap_bios *
420 *===========================================================================*/
421 PUBLIC phys_bytes umap_bios(vir_addr, bytes)
422 vir_bytes vir_addr; /* virtual address in BIOS segment */
423 vir_bytes bytes; /* # of bytes to be copied */
425 /* Calculate the physical memory address at the BIOS. Note: currently, BIOS
426 * address zero (the first BIOS interrupt vector) is not considered as an
427 * error here, but since the physical address will be zero as well, the
428 * calling function will think an error occurred. This is not a problem,
429 * since no one uses the first BIOS interrupt vector.
432 /* Check all acceptable ranges. */
433 if (vir_addr >= BIOS_MEM_BEGIN && vir_addr + bytes <= BIOS_MEM_END)
434 return (phys_bytes) vir_addr;
435 else if (vir_addr >= BASE_MEM_TOP && vir_addr + bytes <= UPPER_MEM_END)
436 return (phys_bytes) vir_addr;
438 printf("Warning, error in umap_bios, virtual address 0x%x\n", vir_addr);
439 return 0;
441 #endif
443 /*===========================================================================*
444 * umap_grant *
445 *===========================================================================*/
446 PUBLIC phys_bytes umap_grant(rp, grant, bytes)
447 struct proc *rp; /* pointer to proc table entry for process */
448 cp_grant_id_t grant; /* grant no. */
449 vir_bytes bytes; /* size */
451 int proc_nr;
452 vir_bytes offset, ret;
453 endpoint_t granter;
455 /* See if the grant in that process is sensible, and
456 * find out the virtual address and (optionally) new
457 * process for that address.
459 * Then convert that process to a slot number.
461 if(verify_grant(rp->p_endpoint, ANY, grant, bytes, 0, 0,
462 &offset, &granter) != OK) {
463 printf("SYSTEM: umap_grant: verify_grant failed\n");
464 return 0;
467 if(!isokendpt(granter, &proc_nr)) {
468 printf("SYSTEM: umap_grant: isokendpt failed\n");
469 return 0;
472 /* Do the mapping from virtual to physical. */
473 ret = umap_virtual(proc_addr(proc_nr), D, offset, bytes);
474 if(!ret) {
475 printf("SYSTEM:umap_grant:umap_virtual failed; grant %s:%d -> %s: vir 0x%lx\n",
476 rp->p_name, grant,
477 proc_addr(proc_nr)->p_name, offset);
479 return ret;
482 /*===========================================================================*
483 * clear_ipc *
484 *===========================================================================*/
485 PRIVATE void clear_ipc(
486 register struct proc *rc /* slot of process to clean up */
489 /* Clear IPC data for a given process slot. */
490 struct proc **xpp; /* iterate over caller queue */
492 if (RTS_ISSET(rc, RTS_SENDING)) {
493 int target_proc;
495 okendpt(rc->p_sendto_e, &target_proc);
496 xpp = &proc_addr(target_proc)->p_caller_q; /* destination's queue */
497 while (*xpp) { /* check entire queue */
498 if (*xpp == rc) { /* process is on the queue */
499 *xpp = (*xpp)->p_q_link; /* replace by next process */
500 #if DEBUG_ENABLE_IPC_WARNINGS
501 printf("endpoint %d / %s removed from queue at %d\n",
502 rc->p_endpoint, rc->p_name, rc->p_sendto_e);
503 #endif
504 break; /* can only be queued once */
506 xpp = &(*xpp)->p_q_link; /* proceed to next queued */
508 rc->p_rts_flags &= ~RTS_SENDING;
510 rc->p_rts_flags &= ~RTS_RECEIVING;
513 /*===========================================================================*
514 * clear_endpoint *
515 *===========================================================================*/
516 PUBLIC void clear_endpoint(rc)
517 register struct proc *rc; /* slot of process to clean up */
519 if(isemptyp(rc)) panic("clear_proc: empty process: %d", rc->p_endpoint);
521 /* Make sure that the exiting process is no longer scheduled. */
522 RTS_SET(rc, RTS_NO_ENDPOINT);
523 if (priv(rc)->s_flags & SYS_PROC)
525 priv(rc)->s_asynsize= 0;
528 /* If the process happens to be queued trying to send a
529 * message, then it must be removed from the message queues.
531 clear_ipc(rc);
533 /* Likewise, if another process was sending or receive a message to or from
534 * the exiting process, it must be alerted that process no longer is alive.
535 * Check all processes.
537 clear_ipc_refs(rc, EDEADSRCDST);
541 /*===========================================================================*
542 * clear_ipc_refs *
543 *===========================================================================*/
544 PUBLIC void clear_ipc_refs(rc, caller_ret)
545 register struct proc *rc; /* slot of process to clean up */
546 int caller_ret; /* code to return on callers */
548 /* Clear IPC references for a given process slot. */
549 struct proc *rp; /* iterate over process table */
551 for (rp = BEG_PROC_ADDR; rp < END_PROC_ADDR; rp++) {
552 if(isemptyp(rp))
553 continue;
555 /* Unset pending notification bits. */
556 unset_sys_bit(priv(rp)->s_notify_pending, priv(rc)->s_id);
558 /* XXX FIXME: Cleanup should be done for senda() as well. For this to be
559 * done in a realistic way, we need a better implementation of senda
560 * with a bitmap similar to s_notify_pending for notify() rather than
561 * a single global MF_ASYNMSG flag. The current arrangement exposes
562 * several performance issues.
565 /* Check if process depends on given process. */
566 if (P_BLOCKEDON(rp) == rc->p_endpoint) {
567 rp->p_reg.retreg = caller_ret; /* return requested code */
568 RTS_UNSET(rp, (RTS_RECEIVING|RTS_SENDING)); /* no longer blocking */
573 /*===========================================================================*
574 * kernel_call_resume *
575 *===========================================================================*/
576 PUBLIC void kernel_call_resume(struct proc *caller)
578 int result;
580 assert(!RTS_ISSET(caller, RTS_SLOT_FREE));
581 assert(!RTS_ISSET(caller, RTS_VMREQUEST));
583 assert(caller->p_vmrequest.saved.reqmsg.m_source == caller->p_endpoint);
586 printf("KERNEL_CALL restart from %s / %d rts 0x%08x misc 0x%08x\n",
587 caller->p_name, caller->p_endpoint,
588 caller->p_rts_flags, caller->p_misc_flags);
592 * we are resuming the kernel call so we have to remove this flag so it
593 * can be set again
595 caller->p_misc_flags &= ~MF_KCALL_RESUME;
596 result = kernel_call_dispatch(caller, &caller->p_vmrequest.saved.reqmsg);
597 kernel_call_finish(caller, &caller->p_vmrequest.saved.reqmsg, result);