xref: /minix3/minix/servers/vfs/misc.c (revision 1f945e8080b22572da1cabae9b0f0cfb4718b620)
1 /* This file contains a collection of miscellaneous procedures.  Some of them
2  * perform simple system calls.  Some others do a little part of system calls
3  * that are mostly performed by the Memory Manager.
4  *
5  * The entry points into this file are
6  *   do_fcntl:	  perform the FCNTL system call
7  *   do_sync:	  perform the SYNC system call
8  *   do_fsync:	  perform the FSYNC system call
9  *   pm_setsid:	  perform VFS's side of setsid system call
10  *   pm_reboot:	  sync disks and prepare for shutdown
11  *   pm_fork:	  adjust the tables after PM has performed a FORK system call
12  *   do_exec:	  handle files with FD_CLOEXEC on after PM has done an EXEC
13  *   do_exit:	  a process has exited; note that in the tables
14  *   do_set:	  set uid or gid for some process
15  *   do_revive:	  revive a process that was waiting for something (e.g. TTY)
16  *   do_svrctl:	  file system control
17  *   do_getsysinfo:	request copy of FS data structure
18  *   pm_dumpcore: create a core dump
19  */
20 
21 #include "fs.h"
22 #include <fcntl.h>
23 #include <assert.h>
24 #include <unistd.h>
25 #include <string.h>
26 #include <minix/callnr.h>
27 #include <minix/safecopies.h>
28 #include <minix/endpoint.h>
29 #include <minix/com.h>
30 #include <minix/sysinfo.h>
31 #include <minix/u64.h>
32 #include <sys/ptrace.h>
33 #include <sys/svrctl.h>
34 #include <sys/resource.h>
35 #include "file.h"
36 #include "scratchpad.h"
37 #include <minix/vfsif.h>
38 #include "vnode.h"
39 #include "vmnt.h"
40 
41 #define CORE_NAME	"core"
42 #define CORE_MODE	0777	/* mode to use on core image files */
43 
44 #if ENABLE_SYSCALL_STATS
45 unsigned long calls_stats[NR_VFS_CALLS];
46 #endif
47 
48 static void free_proc(int flags);
49 
50 /*===========================================================================*
51  *				do_getsysinfo				     *
52  *===========================================================================*/
53 int do_getsysinfo(void)
54 {
55   vir_bytes src_addr, dst_addr;
56   size_t len, buf_size;
57   int what;
58 
59   what = job_m_in.m_lsys_getsysinfo.what;
60   dst_addr = job_m_in.m_lsys_getsysinfo.where;
61   buf_size = job_m_in.m_lsys_getsysinfo.size;
62 
63   /* Only su may call do_getsysinfo. This call may leak information (and is not
64    * stable enough to be part of the API/ABI). In the future, requests from
65    * non-system processes should be denied.
66    */
67 
68   if (!super_user) return(EPERM);
69 
70   switch(what) {
71     case SI_PROC_TAB:
72 	src_addr = (vir_bytes) fproc;
73 	len = sizeof(struct fproc) * NR_PROCS;
74 	break;
75     case SI_DMAP_TAB:
76 	src_addr = (vir_bytes) dmap;
77 	len = sizeof(struct dmap) * NR_DEVICES;
78 	break;
79 #if ENABLE_SYSCALL_STATS
80     case SI_CALL_STATS:
81 	src_addr = (vir_bytes) calls_stats;
82 	len = sizeof(calls_stats);
83 	break;
84 #endif
85     default:
86 	return(EINVAL);
87   }
88 
89   if (len != buf_size)
90 	return(EINVAL);
91 
92   return sys_datacopy_wrapper(SELF, src_addr, who_e, dst_addr, len);
93 }
94 
95 /*===========================================================================*
96  *				do_fcntl				     *
97  *===========================================================================*/
98 int do_fcntl(void)
99 {
100 /* Perform the fcntl(fd, cmd, ...) system call. */
101 
102   register struct filp *f;
103   int new_fd, fl, r = OK, fcntl_req, fcntl_argx;
104   tll_access_t locktype;
105 
106   scratch(fp).file.fd_nr = job_m_in.m_lc_vfs_fcntl.fd;
107   scratch(fp).io.io_buffer = job_m_in.m_lc_vfs_fcntl.arg_ptr;
108   scratch(fp).io.io_nbytes = job_m_in.m_lc_vfs_fcntl.cmd;
109   fcntl_req = job_m_in.m_lc_vfs_fcntl.cmd;
110   fcntl_argx = job_m_in.m_lc_vfs_fcntl.arg_int;
111 
112   /* Is the file descriptor valid? */
113   locktype = (fcntl_req == F_FREESP) ? VNODE_WRITE : VNODE_READ;
114   if ((f = get_filp(scratch(fp).file.fd_nr, locktype)) == NULL)
115 	return(err_code);
116 
117   switch (fcntl_req) {
118     case F_DUPFD:
119 	/* This replaces the old dup() system call. */
120 	if (fcntl_argx < 0 || fcntl_argx >= OPEN_MAX) r = EINVAL;
121 	else if ((r = get_fd(fp, fcntl_argx, 0, &new_fd, NULL)) == OK) {
122 		f->filp_count++;
123 		fp->fp_filp[new_fd] = f;
124 		r = new_fd;
125 	}
126 	break;
127 
128     case F_GETFD:
129 	/* Get close-on-exec flag (FD_CLOEXEC in POSIX Table 6-2). */
130 	r = 0;
131 	if (FD_ISSET(scratch(fp).file.fd_nr, &fp->fp_cloexec_set))
132 		r = FD_CLOEXEC;
133 	break;
134 
135     case F_SETFD:
136 	/* Set close-on-exec flag (FD_CLOEXEC in POSIX Table 6-2). */
137 	if (fcntl_argx & FD_CLOEXEC)
138 		FD_SET(scratch(fp).file.fd_nr, &fp->fp_cloexec_set);
139 	else
140 		FD_CLR(scratch(fp).file.fd_nr, &fp->fp_cloexec_set);
141 	break;
142 
143     case F_GETFL:
144 	/* Get file status flags (O_NONBLOCK and O_APPEND). */
145 	fl = f->filp_flags & (O_NONBLOCK | O_APPEND | O_ACCMODE);
146 	r = fl;
147 	break;
148 
149     case F_SETFL:
150 	/* Set file status flags (O_NONBLOCK and O_APPEND). */
151 	fl = O_NONBLOCK | O_APPEND;
152 	f->filp_flags = (f->filp_flags & ~fl) | (fcntl_argx & fl);
153 	break;
154 
155     case F_GETLK:
156     case F_SETLK:
157     case F_SETLKW:
158 	/* Set or clear a file lock. */
159 	r = lock_op(f, fcntl_req);
160 	break;
161 
162     case F_FREESP:
163      {
164 	/* Free a section of a file */
165 	off_t start, end, offset;
166 	struct flock flock_arg;
167 
168 	/* Check if it's a regular file. */
169 	if (!S_ISREG(f->filp_vno->v_mode)) r = EINVAL;
170 	else if (!(f->filp_mode & W_BIT)) r = EBADF;
171 	else {
172 		/* Copy flock data from userspace. */
173 		r = sys_datacopy_wrapper(who_e, scratch(fp).io.io_buffer,
174 			SELF, (vir_bytes) &flock_arg, sizeof(flock_arg));
175 	}
176 
177 	if (r != OK) break;
178 
179 	/* Convert starting offset to signed. */
180 	offset = (off_t) flock_arg.l_start;
181 
182 	/* Figure out starting position base. */
183 	switch(flock_arg.l_whence) {
184 	  case SEEK_SET: start = 0; break;
185 	  case SEEK_CUR: start = f->filp_pos; break;
186 	  case SEEK_END: start = f->filp_vno->v_size; break;
187 	  default: r = EINVAL;
188 	}
189 	if (r != OK) break;
190 
191 	/* Check for overflow or underflow. */
192 	if (offset > 0 && start + offset < start) r = EINVAL;
193 	else if (offset < 0 && start + offset > start) r = EINVAL;
194 	else {
195 		start += offset;
196 		if (start < 0) r = EINVAL;
197 	}
198 	if (r != OK) break;
199 
200 	if (flock_arg.l_len != 0) {
201 		if (start >= f->filp_vno->v_size) r = EINVAL;
202 		else if ((end = start + flock_arg.l_len) <= start) r = EINVAL;
203 		else if (end > f->filp_vno->v_size) end = f->filp_vno->v_size;
204 	} else {
205                 end = 0;
206 	}
207 	if (r != OK) break;
208 
209 	r = req_ftrunc(f->filp_vno->v_fs_e, f->filp_vno->v_inode_nr,start,end);
210 
211 	if (r == OK && flock_arg.l_len == 0)
212 		f->filp_vno->v_size = start;
213 
214 	break;
215      }
216     case F_GETNOSIGPIPE:
217 	r = !!(f->filp_flags & O_NOSIGPIPE);
218 	break;
219     case F_SETNOSIGPIPE:
220 	if (fcntl_argx)
221 		f->filp_flags |= O_NOSIGPIPE;
222 	else
223 		f->filp_flags &= ~O_NOSIGPIPE;
224 	break;
225     case F_FLUSH_FS_CACHE:
226     {
227 	struct vnode *vn = f->filp_vno;
228 	mode_t mode = f->filp_vno->v_mode;
229 	if (!super_user) {
230 		r = EPERM;
231 	} else if (S_ISBLK(mode)) {
232 		/* Block device; flush corresponding device blocks. */
233 		r = req_flush(vn->v_bfs_e, vn->v_sdev);
234 	} else if (S_ISREG(mode) || S_ISDIR(mode)) {
235 		/* Directory or regular file; flush hosting FS blocks. */
236 		r = req_flush(vn->v_fs_e, vn->v_dev);
237 	} else {
238 		/* Remaining cases.. Meaning unclear. */
239 		r = ENODEV;
240 	}
241 	break;
242     }
243     default:
244 	r = EINVAL;
245   }
246 
247   unlock_filp(f);
248   return(r);
249 }
250 
251 /*===========================================================================*
252  *				do_sync					     *
253  *===========================================================================*/
254 int do_sync(void)
255 {
256   struct vmnt *vmp;
257   int r = OK;
258 
259   for (vmp = &vmnt[0]; vmp < &vmnt[NR_MNTS]; ++vmp) {
260 	if ((r = lock_vmnt(vmp, VMNT_READ)) != OK)
261 		break;
262 	if (vmp->m_dev != NO_DEV && vmp->m_fs_e != NONE &&
263 		 vmp->m_root_node != NULL) {
264 		req_sync(vmp->m_fs_e);
265 	}
266 	unlock_vmnt(vmp);
267   }
268 
269   return(r);
270 }
271 
272 /*===========================================================================*
273  *				do_fsync				     *
274  *===========================================================================*/
275 int do_fsync(void)
276 {
277 /* Perform the fsync() system call. */
278   struct filp *rfilp;
279   struct vmnt *vmp;
280   dev_t dev;
281   int r = OK;
282 
283   scratch(fp).file.fd_nr = job_m_in.m_lc_vfs_fsync.fd;
284 
285   if ((rfilp = get_filp(scratch(fp).file.fd_nr, VNODE_READ)) == NULL)
286 	return(err_code);
287 
288   dev = rfilp->filp_vno->v_dev;
289   unlock_filp(rfilp);
290 
291   for (vmp = &vmnt[0]; vmp < &vmnt[NR_MNTS]; ++vmp) {
292 	if (vmp->m_dev != dev) continue;
293 	if ((r = lock_vmnt(vmp, VMNT_READ)) != OK)
294 		break;
295 	if (vmp->m_dev != NO_DEV && vmp->m_dev == dev &&
296 		vmp->m_fs_e != NONE && vmp->m_root_node != NULL) {
297 
298 		req_sync(vmp->m_fs_e);
299 	}
300 	unlock_vmnt(vmp);
301   }
302 
303   return(r);
304 }
305 
306 int dupvm(struct fproc *rfp, int pfd, int *vmfd, struct filp **newfilp)
307 {
308 	int result, procfd;
309 	struct filp *f = NULL;
310 	struct fproc *vmf = fproc_addr(VM_PROC_NR);
311 
312 	*newfilp = NULL;
313 
314 	if ((f = get_filp2(rfp, pfd, VNODE_READ)) == NULL) {
315 		printf("VFS dupvm: get_filp2 failed\n");
316 		return EBADF;
317 	}
318 
319 	if(!(f->filp_vno->v_vmnt->m_fs_flags & RES_HASPEEK)) {
320 		unlock_filp(f);
321 #if 0	/* Noisy diagnostic for mmap() by ld.so */
322 		printf("VFS dupvm: no peek available\n");
323 #endif
324 		return EINVAL;
325 	}
326 
327 	assert(f->filp_vno);
328 	assert(f->filp_vno->v_vmnt);
329 
330 	if (!S_ISREG(f->filp_vno->v_mode) && !S_ISBLK(f->filp_vno->v_mode)) {
331 		printf("VFS: mmap regular/blockdev only; dev 0x%llx ino %llu has mode 0%o\n",
332 			f->filp_vno->v_dev, f->filp_vno->v_inode_nr, f->filp_vno->v_mode);
333 		unlock_filp(f);
334 		return EINVAL;
335 	}
336 
337 	/* get free FD in VM */
338 	if((result=get_fd(vmf, 0, 0, &procfd, NULL)) != OK) {
339 		unlock_filp(f);
340 		printf("VFS dupvm: getfd failed\n");
341 		return result;
342 	}
343 
344 	*vmfd = procfd;
345 
346 	f->filp_count++;
347 	assert(f->filp_count > 0);
348 	vmf->fp_filp[procfd] = f;
349 
350 	*newfilp = f;
351 
352 	return OK;
353 }
354 
355 /*===========================================================================*
356  *				do_vm_call				     *
357  *===========================================================================*/
358 int do_vm_call(void)
359 {
360 /* A call that VM does to VFS.
361  * We must reply with the fixed type VM_VFS_REPLY (and put our result info
362  * in the rest of the message) so VM can tell the difference between a
363  * request from VFS and a reply to this call.
364  */
365 	int req = job_m_in.VFS_VMCALL_REQ;
366 	int req_fd = job_m_in.VFS_VMCALL_FD;
367 	u32_t req_id = job_m_in.VFS_VMCALL_REQID;
368 	endpoint_t ep = job_m_in.VFS_VMCALL_ENDPOINT;
369 	u64_t offset = job_m_in.VFS_VMCALL_OFFSET;
370 	u32_t length = job_m_in.VFS_VMCALL_LENGTH;
371 	int result = OK;
372 	int slot;
373 	struct fproc *rfp, *vmf;
374 	struct filp *f = NULL;
375 	int r;
376 
377 	if(job_m_in.m_source != VM_PROC_NR)
378 		return ENOSYS;
379 
380 	if(isokendpt(ep, &slot) != OK) rfp = NULL;
381 	else rfp = &fproc[slot];
382 
383 	vmf = fproc_addr(VM_PROC_NR);
384 	assert(fp == vmf);
385 	assert(rfp != vmf);
386 
387 	switch(req) {
388 		case VMVFSREQ_FDLOOKUP:
389 		{
390 			int procfd;
391 
392 			/* Lookup fd in referenced process. */
393 
394 			if(!rfp) {
395 				printf("VFS: why isn't ep %d here?!\n", ep);
396 				result = ESRCH;
397 				goto reqdone;
398 			}
399 
400 			if((result = dupvm(rfp, req_fd, &procfd, &f)) != OK) {
401 #if 0   /* Noisy diagnostic for mmap() by ld.so */
402 				printf("vfs: dupvm failed\n");
403 #endif
404 				goto reqdone;
405 			}
406 
407 			if(S_ISBLK(f->filp_vno->v_mode)) {
408 				assert(f->filp_vno->v_sdev != NO_DEV);
409 				job_m_out.VMV_DEV = f->filp_vno->v_sdev;
410 				job_m_out.VMV_INO = VMC_NO_INODE;
411 				job_m_out.VMV_SIZE_PAGES = LONG_MAX;
412 			} else {
413 				job_m_out.VMV_DEV = f->filp_vno->v_dev;
414 				job_m_out.VMV_INO = f->filp_vno->v_inode_nr;
415 				job_m_out.VMV_SIZE_PAGES =
416 					roundup(f->filp_vno->v_size,
417 						PAGE_SIZE)/PAGE_SIZE;
418 			}
419 
420 			job_m_out.VMV_FD = procfd;
421 
422 			result = OK;
423 
424 			break;
425 		}
426 		case VMVFSREQ_FDCLOSE:
427 		{
428 			result = close_fd(fp, req_fd);
429 			if(result != OK) {
430 				printf("VFS: VM fd close for fd %d, %d (%d)\n",
431 					req_fd, fp->fp_endpoint, result);
432 			}
433 			break;
434 		}
435 		case VMVFSREQ_FDIO:
436 		{
437 			result = actual_lseek(fp, req_fd, SEEK_SET, offset,
438 				NULL);
439 
440 			if(result == OK) {
441 				result = actual_read_write_peek(fp, PEEKING,
442 					req_fd, /* vir_bytes */ 0, length);
443 			}
444 
445 			break;
446 		}
447 		default:
448 			panic("VFS: bad request code from VM\n");
449 			break;
450 	}
451 
452 reqdone:
453 	if(f)
454 		unlock_filp(f);
455 
456 	/* fp is VM still. */
457 	assert(fp == vmf);
458 	job_m_out.VMV_ENDPOINT = ep;
459 	job_m_out.VMV_RESULT = result;
460 	job_m_out.VMV_REQID = req_id;
461 
462 	/* Reply asynchronously as VM may not be able to receive
463 	 * an ipc_sendnb() message.
464 	 */
465 	job_m_out.m_type = VM_VFS_REPLY;
466 	r = asynsend3(VM_PROC_NR, &job_m_out, 0);
467 	if(r != OK) printf("VFS: couldn't asynsend3() to VM\n");
468 
469 	/* VFS does not reply any further */
470 	return SUSPEND;
471 }
472 
473 /*===========================================================================*
474  *				pm_reboot				     *
475  *===========================================================================*/
476 void pm_reboot()
477 {
478 /* Perform the VFS side of the reboot call. This call is performed from the PM
479  * process context.
480  */
481   message m_out;
482   int i, r;
483   struct fproc *rfp, *pmfp;
484 
485   pmfp = fp;
486 
487   do_sync();
488 
489   /* Do exit processing for all leftover processes and servers, but don't
490    * actually exit them (if they were really gone, PM will tell us about it).
491    * Skip processes that handle parts of the file system; we first need to give
492    * them the chance to unmount (which should be possible as all normal
493    * processes have no open files anymore).
494    */
495   /* This is the only place where we allow special modification of "fp". The
496    * reboot procedure should really be implemented as a PM message broadcasted
497    * to all processes, so that each process will be shut down cleanly by a
498    * thread operating on its behalf. Doing everything here is simpler, but it
499    * requires an exception to the strict model of having "fp" be the process
500    * that owns the current worker thread.
501    */
502   for (i = 0; i < NR_PROCS; i++) {
503 	rfp = &fproc[i];
504 
505 	/* Don't just free the proc right away, but let it finish what it was
506 	 * doing first */
507 	if (rfp != fp) lock_proc(rfp);
508 	if (rfp->fp_endpoint != NONE && find_vmnt(rfp->fp_endpoint) == NULL) {
509 		worker_set_proc(rfp);	/* temporarily fake process context */
510 		free_proc(0);
511 		worker_set_proc(pmfp);	/* restore original process context */
512 	}
513 	if (rfp != fp) unlock_proc(rfp);
514   }
515 
516   do_sync();
517   unmount_all(0 /* Don't force */);
518 
519   /* Try to exit all processes again including File Servers */
520   for (i = 0; i < NR_PROCS; i++) {
521 	rfp = &fproc[i];
522 
523 	/* Don't just free the proc right away, but let it finish what it was
524 	 * doing first */
525 	if (rfp != fp) lock_proc(rfp);
526 	if (rfp->fp_endpoint != NONE) {
527 		worker_set_proc(rfp);	/* temporarily fake process context */
528 		free_proc(0);
529 		worker_set_proc(pmfp);	/* restore original process context */
530 	}
531 	if (rfp != fp) unlock_proc(rfp);
532   }
533 
534   do_sync();
535   unmount_all(1 /* Force */);
536 
537   /* Reply to PM for synchronization */
538   memset(&m_out, 0, sizeof(m_out));
539 
540   m_out.m_type = VFS_PM_REBOOT_REPLY;
541 
542   if ((r = ipc_send(PM_PROC_NR, &m_out)) != OK)
543 	panic("pm_reboot: ipc_send failed: %d", r);
544 }
545 
546 /*===========================================================================*
547  *				pm_fork					     *
548  *===========================================================================*/
549 void pm_fork(endpoint_t pproc, endpoint_t cproc, pid_t cpid)
550 {
551 /* Perform those aspects of the fork() system call that relate to files.
552  * In particular, let the child inherit its parent's file descriptors.
553  * The parent and child parameters tell who forked off whom. The file
554  * system uses the same slot numbers as the kernel.  Only PM makes this call.
555  */
556 
557   struct fproc *cp, *pp;
558   int i, parentno, childno;
559   mutex_t c_fp_lock;
560 
561   /* Check up-to-dateness of fproc. */
562   okendpt(pproc, &parentno);
563 
564   /* PM gives child endpoint, which implies process slot information.
565    * Don't call isokendpt, because that will verify if the endpoint
566    * number is correct in fproc, which it won't be.
567    */
568   childno = _ENDPOINT_P(cproc);
569   if (childno < 0 || childno >= NR_PROCS)
570 	panic("VFS: bogus child for forking: %d", cproc);
571   if (fproc[childno].fp_pid != PID_FREE)
572 	panic("VFS: forking on top of in-use child: %d", childno);
573 
574   /* Copy the parent's fproc struct to the child. */
575   /* However, the mutex variables belong to a slot and must stay the same. */
576   c_fp_lock = fproc[childno].fp_lock;
577   fproc[childno] = fproc[parentno];
578   fproc[childno].fp_lock = c_fp_lock;
579 
580   /* Increase the counters in the 'filp' table. */
581   cp = &fproc[childno];
582   pp = &fproc[parentno];
583 
584   for (i = 0; i < OPEN_MAX; i++)
585 	if (cp->fp_filp[i] != NULL) cp->fp_filp[i]->filp_count++;
586 
587   /* Fill in new process and endpoint id. */
588   cp->fp_pid = cpid;
589   cp->fp_endpoint = cproc;
590 
591   /* A forking process never has an outstanding grant, as it isn't blocking on
592    * I/O. */
593   if (GRANT_VALID(pp->fp_grant)) {
594 	panic("VFS: fork: pp (endpoint %d) has grant %d\n", pp->fp_endpoint,
595 	       pp->fp_grant);
596   }
597   if (GRANT_VALID(cp->fp_grant)) {
598 	panic("VFS: fork: cp (endpoint %d) has grant %d\n", cp->fp_endpoint,
599 	       cp->fp_grant);
600   }
601 
602   /* A child is not a process leader, not being revived, etc. */
603   cp->fp_flags = FP_NOFLAGS;
604 
605   /* Record the fact that both root and working dir have another user. */
606   if (cp->fp_rd) dup_vnode(cp->fp_rd);
607   if (cp->fp_wd) dup_vnode(cp->fp_wd);
608 }
609 
610 /*===========================================================================*
611  *				free_proc				     *
612  *===========================================================================*/
613 static void free_proc(int flags)
614 {
615   int i;
616   register struct fproc *rfp;
617   register struct filp *rfilp;
618   register struct vnode *vp;
619   dev_t dev;
620 
621   if (fp->fp_endpoint == NONE)
622 	panic("free_proc: already free");
623 
624   if (fp_is_blocked(fp))
625 	unpause();
626 
627   /* Loop on file descriptors, closing any that are open. */
628   for (i = 0; i < OPEN_MAX; i++) {
629 	(void) close_fd(fp, i);
630   }
631 
632   /* Release root and working directories. */
633   if (fp->fp_rd) { put_vnode(fp->fp_rd); fp->fp_rd = NULL; }
634   if (fp->fp_wd) { put_vnode(fp->fp_wd); fp->fp_wd = NULL; }
635 
636   /* The rest of these actions is only done when processes actually exit. */
637   if (!(flags & FP_EXITING)) return;
638 
639   fp->fp_flags |= FP_EXITING;
640 
641   /* Check if any process is SUSPENDed on this driver.
642    * If a driver exits, unmap its entries in the dmap table.
643    * (unmapping has to be done after the first step, because the
644    * dmap table is used in the first step.)
645    */
646   unsuspend_by_endpt(fp->fp_endpoint);
647   dmap_unmap_by_endpt(fp->fp_endpoint);
648 
649   worker_stop_by_endpt(fp->fp_endpoint); /* Unblock waiting threads */
650   vmnt_unmap_by_endpt(fp->fp_endpoint); /* Invalidate open files if this
651 					     * was an active FS */
652 
653   /* If a session leader exits and it has a controlling tty, then revoke
654    * access to its controlling tty from all other processes using it.
655    */
656   if ((fp->fp_flags & FP_SESLDR) && fp->fp_tty != 0) {
657       dev = fp->fp_tty;
658       for (rfp = &fproc[0]; rfp < &fproc[NR_PROCS]; rfp++) {
659 	  if(rfp->fp_pid == PID_FREE) continue;
660           if (rfp->fp_tty == dev) rfp->fp_tty = 0;
661 
662           for (i = 0; i < OPEN_MAX; i++) {
663 		if ((rfilp = rfp->fp_filp[i]) == NULL) continue;
664 		if (rfilp->filp_mode == FILP_CLOSED) continue;
665 		vp = rfilp->filp_vno;
666 		if (!S_ISCHR(vp->v_mode)) continue;
667 		if (vp->v_sdev != dev) continue;
668 		lock_filp(rfilp, VNODE_READ);
669 		(void) cdev_close(dev); /* Ignore any errors. */
670 		/* FIXME: missing select check */
671 		rfilp->filp_mode = FILP_CLOSED;
672 		unlock_filp(rfilp);
673           }
674       }
675   }
676 
677   /* Exit done. Mark slot as free. */
678   fp->fp_endpoint = NONE;
679   fp->fp_pid = PID_FREE;
680   fp->fp_flags = FP_NOFLAGS;
681 }
682 
683 /*===========================================================================*
684  *				pm_exit					     *
685  *===========================================================================*/
686 void pm_exit(void)
687 {
688 /* Perform the file system portion of the exit(status) system call.
689  * This function is called from the context of the exiting process.
690  */
691 
692   free_proc(FP_EXITING);
693 }
694 
695 /*===========================================================================*
696  *				pm_setgid				     *
697  *===========================================================================*/
698 void pm_setgid(proc_e, egid, rgid)
699 endpoint_t proc_e;
700 int egid;
701 int rgid;
702 {
703   register struct fproc *tfp;
704   int slot;
705 
706   okendpt(proc_e, &slot);
707   tfp = &fproc[slot];
708 
709   tfp->fp_effgid =  egid;
710   tfp->fp_realgid = rgid;
711 }
712 
713 
714 /*===========================================================================*
715  *				pm_setgroups				     *
716  *===========================================================================*/
717 void pm_setgroups(proc_e, ngroups, groups)
718 endpoint_t proc_e;
719 int ngroups;
720 gid_t *groups;
721 {
722   struct fproc *rfp;
723   int slot;
724 
725   okendpt(proc_e, &slot);
726   rfp = &fproc[slot];
727   if (ngroups * sizeof(gid_t) > sizeof(rfp->fp_sgroups))
728 	panic("VFS: pm_setgroups: too much data to copy");
729   if (sys_datacopy_wrapper(who_e, (vir_bytes) groups, SELF, (vir_bytes) rfp->fp_sgroups,
730 		   ngroups * sizeof(gid_t)) == OK) {
731 	rfp->fp_ngroups = ngroups;
732   } else
733 	panic("VFS: pm_setgroups: datacopy failed");
734 }
735 
736 
737 /*===========================================================================*
738  *				pm_setuid				     *
739  *===========================================================================*/
740 void pm_setuid(proc_e, euid, ruid)
741 endpoint_t proc_e;
742 int euid;
743 int ruid;
744 {
745   struct fproc *tfp;
746   int slot;
747 
748   okendpt(proc_e, &slot);
749   tfp = &fproc[slot];
750 
751   tfp->fp_effuid =  euid;
752   tfp->fp_realuid = ruid;
753 }
754 
755 /*===========================================================================*
756  *				pm_setsid				     *
757  *===========================================================================*/
758 void pm_setsid(endpoint_t proc_e)
759 {
760 /* Perform the VFS side of the SETSID call, i.e. get rid of the controlling
761  * terminal of a process, and make the process a session leader.
762  */
763   struct fproc *rfp;
764   int slot;
765 
766   /* Make the process a session leader with no controlling tty. */
767   okendpt(proc_e, &slot);
768   rfp = &fproc[slot];
769   rfp->fp_flags |= FP_SESLDR;
770   rfp->fp_tty = 0;
771 }
772 
773 /*===========================================================================*
774  *				do_svrctl				     *
775  *===========================================================================*/
776 int do_svrctl(void)
777 {
778   unsigned long svrctl;
779   vir_bytes ptr;
780 
781   svrctl = job_m_in.m_lc_svrctl.request;
782   ptr = job_m_in.m_lc_svrctl.arg;
783 
784   if (IOCGROUP(svrctl) != 'F') return(EINVAL);
785 
786   switch (svrctl) {
787     case VFSSETPARAM:
788     case VFSGETPARAM:
789 	{
790 		struct sysgetenv sysgetenv;
791 		char search_key[64];
792 		char val[64];
793 		int r, s;
794 
795 		/* Copy sysgetenv structure to VFS */
796 		if (sys_datacopy_wrapper(who_e, ptr, SELF, (vir_bytes) &sysgetenv,
797 				 sizeof(sysgetenv)) != OK)
798 			return(EFAULT);
799 
800 		/* Basic sanity checking */
801 		if (svrctl == VFSSETPARAM) {
802 			if (sysgetenv.keylen <= 0 ||
803 			    sysgetenv.keylen > (sizeof(search_key) - 1) ||
804 			    sysgetenv.vallen <= 0 ||
805 			    sysgetenv.vallen >= sizeof(val)) {
806 				return(EINVAL);
807 			}
808 		}
809 
810 		/* Copy parameter "key" */
811 		if ((s = sys_datacopy_wrapper(who_e, (vir_bytes) sysgetenv.key,
812 				      SELF, (vir_bytes) search_key,
813 				      sysgetenv.keylen)) != OK)
814 			return(s);
815 		search_key[sysgetenv.keylen] = '\0'; /* Limit string */
816 
817 		/* Is it a parameter we know? */
818 		if (svrctl == VFSSETPARAM) {
819 			if (!strcmp(search_key, "verbose")) {
820 				int verbose_val;
821 				if ((s = sys_datacopy_wrapper(who_e,
822 				    (vir_bytes) sysgetenv.val, SELF,
823 				    (vir_bytes) &val, sysgetenv.vallen)) != OK)
824 					return(s);
825 				val[sysgetenv.vallen] = '\0'; /* Limit string */
826 				verbose_val = atoi(val);
827 				if (verbose_val < 0 || verbose_val > 4) {
828 					return(EINVAL);
829 				}
830 				verbose = verbose_val;
831 				r = OK;
832 			} else {
833 				r = ESRCH;
834 			}
835 		} else { /* VFSGETPARAM */
836 			char small_buf[60];
837 
838 			r = ESRCH;
839 			if (!strcmp(search_key, "print_traces")) {
840 				mthread_stacktraces();
841 				sysgetenv.val = 0;
842 				sysgetenv.vallen = 0;
843 				r = OK;
844 			} else if (!strcmp(search_key, "active_threads")) {
845 				int active = NR_WTHREADS - worker_available();
846 				snprintf(small_buf, sizeof(small_buf) - 1,
847 					 "%d", active);
848 				sysgetenv.vallen = strlen(small_buf);
849 				r = OK;
850 			}
851 
852 			if (r == OK) {
853 				if ((s = sys_datacopy_wrapper(SELF,
854 				    (vir_bytes) &sysgetenv, who_e, ptr,
855 				    sizeof(sysgetenv))) != OK)
856 					return(s);
857 				if (sysgetenv.val != 0) {
858 					if ((s = sys_datacopy_wrapper(SELF,
859 					    (vir_bytes) small_buf, who_e,
860 					    (vir_bytes) sysgetenv.val,
861 					    sysgetenv.vallen)) != OK)
862 						return(s);
863 				}
864 			}
865 		}
866 
867 		return(r);
868 	}
869     default:
870 	return(EINVAL);
871   }
872 }
873 
874 /*===========================================================================*
875  *				pm_dumpcore				     *
876  *===========================================================================*/
877 int pm_dumpcore(int csig, vir_bytes exe_name)
878 {
879   int r = OK, core_fd;
880   struct filp *f;
881   char core_path[PATH_MAX];
882   char proc_name[PROC_NAME_LEN];
883 
884   /* if a process is blocked, scratch(fp).file.fd_nr holds the fd it's blocked
885    * on. free it up for use by common_open().
886    */
887   if (fp_is_blocked(fp))
888           unpause();
889 
890   /* open core file */
891   snprintf(core_path, PATH_MAX, "%s.%d", CORE_NAME, fp->fp_pid);
892   core_fd = common_open(core_path, O_WRONLY | O_CREAT | O_TRUNC, CORE_MODE);
893   if (core_fd < 0) { r = core_fd; goto core_exit; }
894 
895   /* get process' name */
896   r = sys_datacopy_wrapper(PM_PROC_NR, exe_name, VFS_PROC_NR, (vir_bytes) proc_name,
897 			PROC_NAME_LEN);
898   if (r != OK) goto core_exit;
899   proc_name[PROC_NAME_LEN - 1] = '\0';
900 
901   if ((f = get_filp(core_fd, VNODE_WRITE)) == NULL) { r=EBADF; goto core_exit; }
902   write_elf_core_file(f, csig, proc_name);
903   unlock_filp(f);
904   (void) close_fd(fp, core_fd);	        /* ignore failure, we're exiting anyway */
905 
906 core_exit:
907   if(csig)
908 	  free_proc(FP_EXITING);
909   return(r);
910 }
911 
912 /*===========================================================================*
913  *				 ds_event				     *
914  *===========================================================================*/
915 void
916 ds_event(void)
917 {
918   char key[DS_MAX_KEYLEN];
919   char *blkdrv_prefix = "drv.blk.";
920   char *chrdrv_prefix = "drv.chr.";
921   u32_t value;
922   int type, r, is_blk;
923   endpoint_t owner_endpoint;
924 
925   /* Get the event and the owner from DS. */
926   while ((r = ds_check(key, &type, &owner_endpoint)) == OK) {
927 	/* Only check for block and character driver up events. */
928 	if (!strncmp(key, blkdrv_prefix, strlen(blkdrv_prefix))) {
929 		is_blk = TRUE;
930 	} else if (!strncmp(key, chrdrv_prefix, strlen(chrdrv_prefix))) {
931 		is_blk = FALSE;
932 	} else {
933 		continue;
934 	}
935 
936 	if ((r = ds_retrieve_u32(key, &value)) != OK) {
937 		printf("VFS: ds_event: ds_retrieve_u32 failed\n");
938 		break;
939 	}
940 	if (value != DS_DRIVER_UP) continue;
941 
942 	/* Perform up. */
943 	dmap_endpt_up(owner_endpoint, is_blk);
944   }
945 
946   if (r != ENOENT) printf("VFS: ds_event: ds_check failed: %d\n", r);
947 }
948 
949 /* A function to be called on panic(). */
950 void panic_hook(void)
951 {
952   printf("VFS mthread stacktraces:\n");
953   mthread_stacktraces();
954 }
955 
956 /*===========================================================================*
957  *				do_getrusage				     *
958  *===========================================================================*/
959 int do_getrusage(void)
960 {
961 	int res;
962 	struct rusage r_usage;
963 
964 	if ((res = sys_datacopy_wrapper(who_e, m_in.m_lc_vfs_rusage.addr, SELF,
965 		(vir_bytes) &r_usage, (vir_bytes) sizeof(r_usage))) < 0)
966 		return res;
967 
968 	r_usage.ru_inblock = 0;
969 	r_usage.ru_oublock = 0;
970 	r_usage.ru_ixrss = fp->text_size;
971 	r_usage.ru_idrss = fp->data_size;
972 	r_usage.ru_isrss = DEFAULT_STACK_LIMIT;
973 
974 	return sys_datacopy_wrapper(SELF, (vir_bytes) &r_usage, who_e,
975 		m_in.m_lc_vfs_rusage.addr, (phys_bytes) sizeof(r_usage));
976 }
977