kernel - Attempt to make procfs MPSAFE (3)
[dragonfly.git] / sys / vfs / procfs / procfs_vnops.c
1 /*
2  * Copyright (c) 1993, 1995 Jan-Simon Pendry
3  * Copyright (c) 1993, 1995
4  *      The Regents of the University of California.  All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * Jan-Simon Pendry.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *      This product includes software developed by the University of
20  *      California, Berkeley and its contributors.
21  * 4. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *      @(#)procfs_vnops.c      8.18 (Berkeley) 5/21/95
38  *
39  * $FreeBSD: src/sys/miscfs/procfs/procfs_vnops.c,v 1.76.2.7 2002/01/22 17:22:59 nectar Exp $
40  */
41
42 /*
43  * procfs vnode interface
44  */
45
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/time.h>
49 #include <sys/kernel.h>
50 #include <sys/lock.h>
51 #include <sys/fcntl.h>
52 #include <sys/proc.h>
53 #include <sys/priv.h>
54 #include <sys/signalvar.h>
55 #include <sys/vnode.h>
56 #include <sys/uio.h>
57 #include <sys/mount.h>
58 #include <sys/namei.h>
59 #include <sys/dirent.h>
60 #include <sys/malloc.h>
61 #include <sys/reg.h>
62 #include <vm/vm_zone.h>
63 #include <vfs/procfs/procfs.h>
64 #include <sys/pioctl.h>
65
66 #include <sys/spinlock2.h>
67
68 #include <machine/limits.h>
69
70 static int      procfs_access (struct vop_access_args *);
71 static int      procfs_badop (struct vop_generic_args *);
72 static int      procfs_bmap (struct vop_bmap_args *);
73 static int      procfs_close (struct vop_close_args *);
74 static int      procfs_getattr (struct vop_getattr_args *);
75 static int      procfs_inactive (struct vop_inactive_args *);
76 static int      procfs_ioctl (struct vop_ioctl_args *);
77 static int      procfs_lookup (struct vop_old_lookup_args *);
78 static int      procfs_open (struct vop_open_args *);
79 static int      procfs_print (struct vop_print_args *);
80 static int      procfs_readdir (struct vop_readdir_args *);
81 static int      procfs_readlink (struct vop_readlink_args *);
82 static int      procfs_reclaim (struct vop_reclaim_args *);
83 static int      procfs_setattr (struct vop_setattr_args *);
84
85 static int      procfs_readdir_proc(struct vop_readdir_args *);
86 static int      procfs_readdir_root(struct vop_readdir_args *);
87
88 /*
89  * procfs vnode operations.
90  */
91 struct vop_ops procfs_vnode_vops = {
92         .vop_default =          vop_defaultop,
93         .vop_access =           procfs_access,
94         .vop_advlock =          (void *)procfs_badop,
95         .vop_bmap =             procfs_bmap,
96         .vop_close =            procfs_close,
97         .vop_old_create =       (void *)procfs_badop,
98         .vop_getattr =          procfs_getattr,
99         .vop_inactive =         procfs_inactive,
100         .vop_old_link =         (void *)procfs_badop,
101         .vop_old_lookup =       procfs_lookup,
102         .vop_old_mkdir =        (void *)procfs_badop,
103         .vop_old_mknod =        (void *)procfs_badop,
104         .vop_open =             procfs_open,
105         .vop_pathconf =         vop_stdpathconf,
106         .vop_print =            procfs_print,
107         .vop_read =             procfs_rw,
108         .vop_readdir =          procfs_readdir,
109         .vop_readlink =         procfs_readlink,
110         .vop_reclaim =          procfs_reclaim,
111         .vop_old_remove =       (void *)procfs_badop,
112         .vop_old_rename =       (void *)procfs_badop,
113         .vop_old_rmdir =        (void *)procfs_badop,
114         .vop_setattr =          procfs_setattr,
115         .vop_old_symlink =      (void *)procfs_badop,
116         .vop_write =            (void *)procfs_rw,
117         .vop_ioctl =            procfs_ioctl
118 };
119
120
121 /*
122  * This is a list of the valid names in the
123  * process-specific sub-directories.  It is
124  * used in procfs_lookup and procfs_readdir
125  */
126 static struct proc_target {
127         u_char  pt_type;
128         u_char  pt_namlen;
129         char    *pt_name;
130         pfstype pt_pfstype;
131         int     (*pt_valid) (struct lwp *p);
132 } proc_targets[] = {
133 #define N(s) sizeof(s)-1, s
134         /*        name          type            validp */
135         { DT_DIR, N("."),       Pproc,          NULL },
136         { DT_DIR, N(".."),      Proot,          NULL },
137         { DT_REG, N("mem"),     Pmem,           NULL },
138         { DT_REG, N("regs"),    Pregs,          procfs_validregs },
139         { DT_REG, N("fpregs"),  Pfpregs,        procfs_validfpregs },
140         { DT_REG, N("dbregs"),  Pdbregs,        procfs_validdbregs },
141         { DT_REG, N("ctl"),     Pctl,           NULL },
142         { DT_REG, N("status"),  Pstatus,        NULL },
143         { DT_REG, N("note"),    Pnote,          NULL },
144         { DT_REG, N("notepg"),  Pnotepg,        NULL },
145         { DT_REG, N("map"),     Pmap,           procfs_validmap },
146         { DT_REG, N("etype"),   Ptype,          procfs_validtype },
147         { DT_REG, N("cmdline"), Pcmdline,       NULL },
148         { DT_REG, N("rlimit"),  Prlimit,        NULL },
149         { DT_LNK, N("file"),    Pfile,          NULL },
150 #undef N
151 };
152 static const int nproc_targets = NELEM(proc_targets);
153
154 static pid_t atopid (const char *, u_int);
155
156 /*
157  * set things up for doing i/o on
158  * the pfsnode (vp).  (vp) is locked
159  * on entry, and should be left locked
160  * on exit.
161  *
162  * for procfs we don't need to do anything
163  * in particular for i/o.  all that is done
164  * is to support exclusive open on process
165  * memory images.
166  *
167  * procfs_open(struct vnode *a_vp, int a_mode, struct ucred *a_cred,
168  *             struct file *a_fp)
169  */
170 static int
171 procfs_open(struct vop_open_args *ap)
172 {
173         struct pfsnode *pfs = VTOPFS(ap->a_vp);
174         struct proc *p1, *p2;
175         int error;
176
177         p2 = pfs_pfind(pfs->pfs_pid);
178         if (p2 == NULL)
179                 return (ENOENT);
180         if (pfs->pfs_pid && !PRISON_CHECK(ap->a_cred, p2->p_ucred)) {
181                 error = ENOENT;
182                 goto done;
183         }
184
185         switch (pfs->pfs_type) {
186         case Pmem:
187                 if (((pfs->pfs_flags & FWRITE) && (ap->a_mode & O_EXCL)) ||
188                     ((pfs->pfs_flags & O_EXCL) && (ap->a_mode & FWRITE))) {
189                         error = EBUSY;
190                         goto done;
191                 }
192
193                 p1 = curproc;
194                 KKASSERT(p1);
195                 /* Can't trace a process that's currently exec'ing. */ 
196                 if ((p2->p_flags & P_INEXEC) != 0) {
197                         error = EAGAIN;
198                         goto done;
199                 }
200                 if (!CHECKIO(p1, p2) || p_trespass(ap->a_cred, p2->p_ucred)) {
201                         error = EPERM;
202                         goto done;
203                 }
204
205                 if (ap->a_mode & FWRITE)
206                         pfs->pfs_flags = ap->a_mode & (FWRITE|O_EXCL);
207
208                 break;
209
210         default:
211                 break;
212         }
213         error = vop_stdopen(ap);
214 done:
215         pfs_pdone(p2);
216         return error;
217 }
218
219 /*
220  * close the pfsnode (vp) after doing i/o.
221  * (vp) is not locked on entry or exit.
222  *
223  * nothing to do for procfs other than undo
224  * any exclusive open flag (see _open above).
225  *
226  * procfs_close(struct vnode *a_vp, int a_fflag, struct ucred *a_cred)
227  */
228 static int
229 procfs_close(struct vop_close_args *ap)
230 {
231         struct pfsnode *pfs = VTOPFS(ap->a_vp);
232         struct proc *p;
233
234         switch (pfs->pfs_type) {
235         case Pmem:
236                 if ((ap->a_fflag & FWRITE) && (pfs->pfs_flags & O_EXCL))
237                         pfs->pfs_flags &= ~(FWRITE|O_EXCL);
238                 /*
239                  * v_opencount determines the last real close on the vnode.
240                  *
241                  * If this is the last close, then it checks to see if
242                  * the target process has PF_LINGER set in p_pfsflags,
243                  * if this is *not* the case, then the process' stop flags
244                  * are cleared, and the process is woken up.  This is
245                  * to help prevent the case where a process has been
246                  * told to stop on an event, but then the requesting process
247                  * has gone away or forgotten about it.
248                  */
249                 p = NULL;
250                 if ((ap->a_vp->v_opencount < 2)
251                     && (p = pfs_pfind(pfs->pfs_pid))
252                     && !(p->p_pfsflags & PF_LINGER)) {
253                         spin_lock(&p->p_spin);
254                         p->p_stops = 0;
255                         p->p_step = 0;
256                         spin_unlock(&p->p_spin);
257                         wakeup(&p->p_step);
258                 }
259                 pfs_pdone(p);
260                 break;
261         default:
262                 break;
263         }
264
265         return (vop_stdclose(ap));
266 }
267
268 /*
269  * do an ioctl operation on a pfsnode (vp).
270  * (vp) is not locked on entry or exit.
271  */
272 static int
273 procfs_ioctl(struct vop_ioctl_args *ap)
274 {
275         struct pfsnode *pfs = VTOPFS(ap->a_vp);
276         struct proc *procp;
277         struct proc *p;
278         int error;
279         int signo;
280         struct procfs_status *psp;
281         unsigned char flags;
282
283         procp = pfind(pfs->pfs_pid);
284         if (procp == NULL)
285                 return ENOTTY;
286         p = curproc;
287         if (p == NULL) {
288                 error = EINVAL;
289                 goto done;
290         }
291
292         /* Can't trace a process that's currently exec'ing. */ 
293         if ((procp->p_flags & P_INEXEC) != 0) {
294                 error = EAGAIN;
295                 goto done;
296         }
297         if (!CHECKIO(p, procp) || p_trespass(ap->a_cred, procp->p_ucred)) {
298                 error = EPERM;
299                 goto done;
300         }
301
302         switch (ap->a_command) {
303         case PIOCBIS:
304           procp->p_stops |= *(unsigned int*)ap->a_data;
305           break;
306         case PIOCBIC:
307           procp->p_stops &= ~*(unsigned int*)ap->a_data;
308           break;
309         case PIOCSFL:
310           /*
311            * NFLAGS is "non-suser_xxx flags" -- currently, only
312            * PFS_ISUGID ("ignore set u/g id");
313            */
314 #define NFLAGS  (PF_ISUGID)
315           flags = (unsigned char)*(unsigned int*)ap->a_data;
316           if (flags & NFLAGS && (error = priv_check_cred(ap->a_cred, PRIV_ROOT, 0)))
317             goto done;
318           procp->p_pfsflags = flags;
319           break;
320         case PIOCGFL:
321           *(unsigned int*)ap->a_data = (unsigned int)procp->p_pfsflags;
322           break;
323         case PIOCSTATUS:
324           /*
325            * NOTE: syscall entry deals with stopevents and may run without
326            *       the MP lock.
327            */
328           psp = (struct procfs_status *)ap->a_data;
329           psp->flags = procp->p_pfsflags;
330           psp->events = procp->p_stops;
331           spin_lock(&procp->p_spin);
332           if (procp->p_step) {
333             psp->state = 0;
334             psp->why = procp->p_stype;
335             psp->val = procp->p_xstat;
336             spin_unlock(&procp->p_spin);
337           } else {
338             psp->state = 1;
339             spin_unlock(&procp->p_spin);
340             psp->why = 0;       /* Not defined values */
341             psp->val = 0;       /* Not defined values */
342           }
343           break;
344         case PIOCWAIT:
345           /*
346            * NOTE: syscall entry deals with stopevents and may run without
347            *       the MP lock.
348            */
349           psp = (struct procfs_status *)ap->a_data;
350           spin_lock(&procp->p_spin);
351           while (procp->p_step == 0) {
352             tsleep_interlock(&procp->p_stype, PCATCH);
353             spin_unlock(&procp->p_spin);
354             error = tsleep(&procp->p_stype, PCATCH | PINTERLOCKED, "piocwait", 0);
355             if (error)
356               goto done;
357             spin_lock(&procp->p_spin);
358           }
359           spin_unlock(&procp->p_spin);
360           psp->state = 1;       /* It stopped */
361           psp->flags = procp->p_pfsflags;
362           psp->events = procp->p_stops;
363           psp->why = procp->p_stype;    /* why it stopped */
364           psp->val = procp->p_xstat;    /* any extra info */
365           break;
366         case PIOCCONT:  /* Restart a proc */
367           /*
368            * NOTE: syscall entry deals with stopevents and may run without
369            *       the MP lock.  However, the caller is presumably interlocked
370            *       by having waited.
371            */
372           if (procp->p_step == 0) {
373             error = EINVAL;     /* Can only start a stopped process */
374             goto done;
375           }
376           if ((signo = *(int*)ap->a_data) != 0) {
377             if (signo >= NSIG || signo <= 0) {
378               error = EINVAL;
379               goto done;
380             }
381             ksignal(procp, signo);
382           }
383           procp->p_step = 0;
384           wakeup(&procp->p_step);
385           break;
386         default:
387           error = ENOTTY;
388           goto done;
389         }
390         error = 0;
391 done:
392         pfs_pdone(procp);
393         return 0;
394 }
395
396 /*
397  * do block mapping for pfsnode (vp).
398  * since we don't use the buffer cache
399  * for procfs this function should never
400  * be called.  in any case, it's not clear
401  * what part of the kernel ever makes use
402  * of this function.  for sanity, this is the
403  * usual no-op bmap, although returning
404  * (EIO) would be a reasonable alternative.
405  *
406  * XXX mmap assumes buffer cache operation
407  *
408  * procfs_bmap(struct vnode *a_vp, off_t a_loffset,
409  *              off_t *a_doffsetp, int *a_runp, int *a_runb)
410  */
411 static int
412 procfs_bmap(struct vop_bmap_args *ap)
413 {
414         if (ap->a_doffsetp != NULL)
415                 *ap->a_doffsetp = ap->a_loffset;
416         if (ap->a_runp != NULL)
417                 *ap->a_runp = 0;
418         if (ap->a_runb != NULL)
419                 *ap->a_runb = 0;
420         return (0);
421 }
422
423 /*
424  * procfs_inactive is called when the pfsnode
425  * is vrele'd and the reference count goes
426  * to zero.  (vp) will be on the vnode free
427  * list, so to get it back vget() must be
428  * used.
429  *
430  * (vp) is locked on entry, but must be unlocked on exit.
431  *
432  * procfs_inactive(struct vnode *a_vp)
433  */
434 static int
435 procfs_inactive(struct vop_inactive_args *ap)
436 {
437         struct pfsnode *pfs = VTOPFS(ap->a_vp);
438
439         if (pfs->pfs_pid & PFS_DEAD)
440                 vrecycle(ap->a_vp);
441         return (0);
442 }
443
444 /*
445  * _reclaim is called when getnewvnode()
446  * wants to make use of an entry on the vnode
447  * free list.  at this time the filesystem needs
448  * to free any private data and remove the node
449  * from any private lists.
450  *
451  * procfs_reclaim(struct vnode *a_vp)
452  */
453 static int
454 procfs_reclaim(struct vop_reclaim_args *ap)
455 {
456         return (procfs_freevp(ap->a_vp));
457 }
458
459 /*
460  * _print is used for debugging.
461  * just print a readable description
462  * of (vp).
463  *
464  * procfs_print(struct vnode *a_vp)
465  */
466 static int
467 procfs_print(struct vop_print_args *ap)
468 {
469         struct pfsnode *pfs = VTOPFS(ap->a_vp);
470
471         kprintf("tag VT_PROCFS, type %d, pid %ld, mode %x, flags %lx\n",
472             pfs->pfs_type, (long)pfs->pfs_pid, pfs->pfs_mode, pfs->pfs_flags);
473         return (0);
474 }
475
476 /*
477  * generic entry point for unsupported operations
478  */
479 static int
480 procfs_badop(struct vop_generic_args *ap)
481 {
482         return (EIO);
483 }
484
485 /*
486  * Invent attributes for pfsnode (vp) and store
487  * them in (vap).
488  * Directories lengths are returned as zero since
489  * any real length would require the genuine size
490  * to be computed, and nothing cares anyway.
491  *
492  * this is relatively minimal for procfs.
493  *
494  * procfs_getattr(struct vnode *a_vp, struct vattr *a_vap)
495  */
496 static int
497 procfs_getattr(struct vop_getattr_args *ap)
498 {
499         struct pfsnode *pfs = VTOPFS(ap->a_vp);
500         struct vattr *vap = ap->a_vap;
501         struct proc *procp;
502         int error;
503
504         /*
505          * First make sure that the process and its credentials 
506          * still exist.
507          */
508         switch (pfs->pfs_type) {
509         case Proot:
510         case Pcurproc:
511                 procp = NULL;
512                 break;
513         default:
514                 procp = pfs_pfind(pfs->pfs_pid);
515                 if (procp == NULL || procp->p_ucred == NULL) {
516                         error = ENOENT;
517                         goto done;
518                 }
519                 break;
520         }
521
522         error = 0;
523
524         /* start by zeroing out the attributes */
525         VATTR_NULL(vap);
526
527         /* next do all the common fields */
528         vap->va_type = ap->a_vp->v_type;
529         vap->va_mode = pfs->pfs_mode;
530         vap->va_fileid = pfs->pfs_fileno;
531         vap->va_flags = 0;
532         vap->va_blocksize = PAGE_SIZE;
533         vap->va_bytes = vap->va_size = 0;
534         vap->va_fsid = ap->a_vp->v_mount->mnt_stat.f_fsid.val[0];
535
536         /*
537          * Make all times be current TOD.
538          * It would be possible to get the process start
539          * time from the p_stat structure, but there's
540          * no "file creation" time stamp anyway, and the
541          * p_stat structure is not addressible if u. gets
542          * swapped out for that process.
543          */
544         nanotime(&vap->va_ctime);
545         vap->va_atime = vap->va_mtime = vap->va_ctime;
546
547         /*
548          * If the process has exercised some setuid or setgid
549          * privilege, then rip away read/write permission so
550          * that only root can gain access.
551          */
552         switch (pfs->pfs_type) {
553         case Pctl:
554         case Pregs:
555         case Pfpregs:
556         case Pdbregs:
557         case Pmem:
558                 if (procp->p_flags & P_SUGID) {
559                         vap->va_mode &= ~((VREAD|VWRITE)|
560                                           ((VREAD|VWRITE)>>3)|
561                                           ((VREAD|VWRITE)>>6));
562                 }
563                 break;
564         default:
565                 break;
566         }
567
568         /*
569          * now do the object specific fields
570          *
571          * The size could be set from struct reg, but it's hardly
572          * worth the trouble, and it puts some (potentially) machine
573          * dependent data into this machine-independent code.  If it
574          * becomes important then this function should break out into
575          * a per-file stat function in the corresponding .c file.
576          */
577
578         vap->va_nlink = 1;
579         if (procp) {
580                 if (procp->p_ucred) {
581                         vap->va_uid = procp->p_ucred->cr_uid;
582                         vap->va_gid = procp->p_ucred->cr_gid;
583                 } else {
584                         vap->va_uid = -1;
585                         vap->va_gid = -1;
586                 }
587         }
588
589         switch (pfs->pfs_type) {
590         case Proot:
591                 /*
592                  * Set nlink to 1 to tell fts(3) we don't actually know.
593                  */
594                 vap->va_nlink = 1;
595                 vap->va_uid = 0;
596                 vap->va_gid = 0;
597                 vap->va_size = vap->va_bytes = DEV_BSIZE;
598                 break;
599
600         case Pcurproc: {
601                 char buf[16];           /* should be enough */
602
603                 vap->va_uid = 0;
604                 vap->va_gid = 0;
605                 vap->va_size = ksnprintf(buf, sizeof(buf),
606                                          "%ld", (long)curproc->p_pid);
607                 vap->va_bytes = vap->va_size;
608                 break;
609         }
610
611         case Pproc:
612                 vap->va_nlink = nproc_targets;
613                 vap->va_size = vap->va_bytes = DEV_BSIZE;
614                 break;
615
616         case Pfile: {
617                 char *fullpath, *freepath;
618
619                 if (procp->p_textnch.ncp == NULL)
620                         error = EINVAL;
621                 else
622                         error = cache_fullpath(procp, &procp->p_textnch,
623                                                 &fullpath, &freepath, 0);
624
625                 if (error == 0) {
626                         vap->va_size = strlen(fullpath);
627                         kfree(freepath, M_TEMP);
628                 } else {
629                         vap->va_size = sizeof("unknown") - 1;
630                         error = 0;
631                 }
632                 vap->va_bytes = vap->va_size;
633                 break;
634         }
635
636         case Pmem:
637                 /*
638                  * If we denied owner access earlier, then we have to
639                  * change the owner to root - otherwise 'ps' and friends
640                  * will break even though they are setgid kmem. *SIGH*
641                  */
642                 if (procp->p_flags & P_SUGID)
643                         vap->va_uid = 0;
644                 else if (procp->p_ucred)
645                         vap->va_uid = procp->p_ucred->cr_uid;
646                 else
647                         vap->va_uid = -1;
648                 break;
649
650         case Pregs:
651                 vap->va_bytes = vap->va_size = sizeof(struct reg);
652                 break;
653
654         case Pfpregs:
655                 vap->va_bytes = vap->va_size = sizeof(struct fpreg);
656                 break;
657
658         case Pdbregs:
659                 vap->va_bytes = vap->va_size = sizeof(struct dbreg);
660                 break;
661
662         case Ptype:
663         case Pmap:
664         case Pctl:
665         case Pstatus:
666         case Pnote:
667         case Pnotepg:
668         case Pcmdline:
669         case Prlimit:
670                 break;
671
672         default:
673                 panic("procfs_getattr");
674         }
675 done:
676         pfs_pdone(procp);
677         return (error);
678 }
679
680 /*
681  * procfs_setattr(struct vnode *a_vp, struct vattr *a_vap,
682  *                struct ucred *a_cred)
683  */
684 static int
685 procfs_setattr(struct vop_setattr_args *ap)
686 {
687         if (ap->a_vap->va_flags != VNOVAL)
688                 return (EOPNOTSUPP);
689
690         /*
691          * just fake out attribute setting
692          * it's not good to generate an error
693          * return, otherwise things like creat()
694          * will fail when they try to set the
695          * file length to 0.  worse, this means
696          * that echo $note > /proc/$pid/note will fail.
697          */
698
699         return (0);
700 }
701
702 /*
703  * implement access checking.
704  *
705  * procfs_access(struct vnode *a_vp, int a_mode, struct ucred *a_cred)
706  */
707 static int
708 procfs_access(struct vop_access_args *ap)
709 {
710         struct vattr vattr;
711         int error;
712
713         error = VOP_GETATTR(ap->a_vp, &vattr);
714         if (!error)
715                 error = vop_helper_access(ap, vattr.va_uid, vattr.va_gid, 
716                                 vattr.va_mode, 0);
717         return (error);
718 }
719
720 /*
721  * lookup.  this is incredibly complicated in the general case, however
722  * for most pseudo-filesystems very little needs to be done.
723  *
724  * procfs_lookup(struct vnode *a_dvp, struct vnode **a_vpp,
725  *               struct componentname *a_cnp)
726  */
727 static int
728 procfs_lookup(struct vop_old_lookup_args *ap)
729 {
730         struct componentname *cnp = ap->a_cnp;
731         struct vnode **vpp = ap->a_vpp;
732         struct vnode *dvp = ap->a_dvp;
733         char *pname = cnp->cn_nameptr;
734         /* struct proc *curp = cnp->cn_proc; */
735         struct proc_target *pt;
736         pid_t pid;
737         struct pfsnode *pfs;
738         struct proc *p;
739         struct lwp *lp;
740         int i;
741         int error;
742
743         *vpp = NULL;
744
745         if (cnp->cn_nameiop == NAMEI_DELETE || cnp->cn_nameiop == NAMEI_RENAME)
746                 return (EROFS);
747
748         p = NULL;
749         error = 0;
750         if (cnp->cn_namelen == 1 && *pname == '.') {
751                 *vpp = dvp;
752                 vref(*vpp);
753                 goto out;
754         }
755
756         pfs = VTOPFS(dvp);
757         switch (pfs->pfs_type) {
758         case Proot:
759                 if (cnp->cn_flags & CNP_ISDOTDOT)
760                         return (EIO);
761
762                 if (CNEQ(cnp, "curproc", 7)) {
763                         error = procfs_allocvp(dvp->v_mount, vpp, 0, Pcurproc);
764                         goto out;
765                 }
766
767                 pid = atopid(pname, cnp->cn_namelen);
768                 if (pid == NO_PID)
769                         break;
770
771                 p = pfs_pfind(pid);
772                 if (p == NULL)
773                         break;
774
775                 if (!PRISON_CHECK(ap->a_cnp->cn_cred, p->p_ucred))
776                         break;
777
778                 if (ps_showallprocs == 0 && ap->a_cnp->cn_cred->cr_uid != 0 &&
779                     ap->a_cnp->cn_cred->cr_uid != p->p_ucred->cr_uid)
780                         break;
781
782                 error = procfs_allocvp(dvp->v_mount, vpp, pid, Pproc);
783                 goto out;
784
785         case Pproc:
786                 if (cnp->cn_flags & CNP_ISDOTDOT) {
787                         error = procfs_root(dvp->v_mount, vpp);
788                         goto out;
789                 }
790
791                 p = pfs_pfind(pfs->pfs_pid);
792                 if (p == NULL)
793                         break;
794                 /* XXX lwp */
795                 lp = FIRST_LWP_IN_PROC(p);
796
797                 if (!PRISON_CHECK(ap->a_cnp->cn_cred, p->p_ucred))
798                         break;
799
800                 if (ps_showallprocs == 0 && ap->a_cnp->cn_cred->cr_uid != 0 &&
801                     ap->a_cnp->cn_cred->cr_uid != p->p_ucred->cr_uid)
802                         break;
803
804                 for (pt = proc_targets, i = 0; i < nproc_targets; pt++, i++) {
805                         if (cnp->cn_namelen == pt->pt_namlen &&
806                             bcmp(pt->pt_name, pname, cnp->cn_namelen) == 0 &&
807                             (pt->pt_valid == NULL || (*pt->pt_valid)(lp)))
808                                 goto found;
809                 }
810                 break;
811         found:
812                 error = procfs_allocvp(dvp->v_mount, vpp, pfs->pfs_pid,
813                                         pt->pt_pfstype);
814                 goto out;
815
816         default:
817                 error = ENOTDIR;
818                 goto out;
819         }
820         if (cnp->cn_nameiop == NAMEI_LOOKUP)
821                 error = ENOENT;
822         else
823                 error = EROFS;
824         /*
825          * If no error occured *vpp will hold a referenced locked vnode.
826          * dvp was passed to us locked and *vpp must be returned locked.
827          * If *vpp != dvp then we should unlock dvp if (1) this is not the
828          * last component or (2) CNP_LOCKPARENT is not set.
829          */
830 out:
831         if (error == 0 && *vpp != dvp) {
832                 if ((cnp->cn_flags & CNP_LOCKPARENT) == 0) {
833                         cnp->cn_flags |= CNP_PDIRUNLOCK;
834                         vn_unlock(dvp);
835                 }
836         }
837         pfs_pdone(p);
838         return (error);
839 }
840
841 /*
842  * Does this process have a text file?
843  */
844 int
845 procfs_validfile(struct lwp *lp)
846 {
847         return (procfs_findtextvp(lp->lwp_proc) != NULLVP);
848 }
849
850 /*
851  * readdir() returns directory entries from pfsnode (vp).
852  *
853  * We generate just one directory entry at a time, as it would probably
854  * not pay off to buffer several entries locally to save uiomove calls.
855  *
856  * procfs_readdir(struct vnode *a_vp, struct uio *a_uio, struct ucred *a_cred,
857  *                int *a_eofflag, int *a_ncookies, off_t **a_cookies)
858  */
859 static int
860 procfs_readdir(struct vop_readdir_args *ap)
861 {
862         struct pfsnode *pfs;
863         int error;
864
865         if (ap->a_uio->uio_offset < 0 || ap->a_uio->uio_offset > INT_MAX)
866                 return (EINVAL);
867         if ((error = vn_lock(ap->a_vp, LK_EXCLUSIVE | LK_RETRY)) != 0)
868                 return (error);
869         pfs = VTOPFS(ap->a_vp);
870
871         switch (pfs->pfs_type) {
872         case Pproc:
873                 /*
874                  * this is for the process-specific sub-directories.
875                  * all that is needed to is copy out all the entries
876                  * from the procent[] table (top of this file).
877                  */
878                 error = procfs_readdir_proc(ap);
879                 break;
880         case Proot:
881                 /*
882                  * this is for the root of the procfs filesystem
883                  * what is needed is a special entry for "curproc"
884                  * followed by an entry for each process on allproc
885                  */
886                 error = procfs_readdir_root(ap);
887                 break;
888         default:
889                 error = ENOTDIR;
890                 break;
891         }
892
893         vn_unlock(ap->a_vp);
894         return (error);
895 }
896
897 static int
898 procfs_readdir_proc(struct vop_readdir_args *ap)
899 {
900         struct pfsnode *pfs;
901         int error, i, retval;
902         struct proc *p;
903         struct lwp *lp;
904         struct proc_target *pt;
905         struct uio *uio = ap->a_uio;
906
907         pfs = VTOPFS(ap->a_vp);
908         p = pfs_pfind(pfs->pfs_pid);
909         if (p == NULL)
910                 return(0);
911         if (!PRISON_CHECK(ap->a_cred, p->p_ucred)) {
912                 error = 0;
913                 goto done;
914         }
915         /* XXX lwp, not MPSAFE */
916         lp = FIRST_LWP_IN_PROC(p);
917
918         error = 0;
919         i = (int)uio->uio_offset;
920         if (i < 0) {
921                 error = EINVAL;
922                 goto done;
923         }
924
925         for (pt = &proc_targets[i];
926              !error && uio->uio_resid > 0 && i < nproc_targets; pt++, i++) {
927                 if (pt->pt_valid && (*pt->pt_valid)(lp) == 0)
928                         continue;
929
930                 retval = vop_write_dirent(&error, uio,
931                     PROCFS_FILENO(pfs->pfs_pid, pt->pt_pfstype), pt->pt_type,
932                     pt->pt_namlen, pt->pt_name);
933                 if (retval)
934                         break;
935         }
936
937         uio->uio_offset = (off_t)i;
938         error = 0;
939 done:
940         pfs_pdone(p);
941         return error;
942 }
943
944 struct procfs_readdir_root_info {
945         int error;
946         int i;
947         int pcnt;
948         struct uio *uio;
949         struct ucred *cred;
950 };
951
952 static int procfs_readdir_root_callback(struct proc *p, void *data);
953
954 static int
955 procfs_readdir_root(struct vop_readdir_args *ap)
956 {
957         struct procfs_readdir_root_info info;
958         struct uio *uio = ap->a_uio;
959         int res;
960
961         info.error = 0;
962         info.i = (int)uio->uio_offset;
963
964         if (info.i < 0)
965                 return (EINVAL);
966
967         info.pcnt = 0;
968         info.uio = uio;
969         info.cred = ap->a_cred;
970         while (info.pcnt < 3) {
971                 res = procfs_readdir_root_callback(NULL, &info);
972                 if (res < 0)
973                         break;
974         }
975         if (res >= 0)
976                 allproc_scan(procfs_readdir_root_callback, &info);
977         uio->uio_offset = (off_t)info.i;
978
979         return (info.error);
980 }
981
982 static int
983 procfs_readdir_root_callback(struct proc *p, void *data)
984 {
985         struct procfs_readdir_root_info *info = data;
986         struct uio *uio;
987         int retval;
988         ino_t d_ino;
989         const char *d_name;
990         char d_name_pid[20];
991         size_t d_namlen;
992         uint8_t d_type;
993
994         uio = info->uio;
995
996         if (uio->uio_resid <= 0 || info->error)
997                 return(-1);
998
999         switch (info->pcnt) {
1000         case 0:         /* `.' */
1001                 d_ino = PROCFS_FILENO(0, Proot);
1002                 d_name = ".";
1003                 d_namlen = 1;
1004                 d_type = DT_DIR;
1005                 break;
1006         case 1:         /* `..' */
1007                 d_ino = PROCFS_FILENO(0, Proot);
1008                 d_name = "..";
1009                 d_namlen = 2;
1010                 d_type = DT_DIR;
1011                 break;
1012
1013         case 2:
1014                 d_ino = PROCFS_FILENO(0, Pcurproc);
1015                 d_namlen = 7;
1016                 d_name = "curproc";
1017                 d_type = DT_LNK;
1018                 break;
1019
1020
1021         default:
1022                 if (!PRISON_CHECK(info->cred, p->p_ucred))
1023                         return(0);
1024                 if (ps_showallprocs == 0 && 
1025                     info->cred->cr_uid != 0 &&
1026                     info->cred->cr_uid != p->p_ucred->cr_uid) {
1027                         return(0);
1028                 }
1029
1030                 /*
1031                  * Skip entries we have already returned (optimization)
1032                  */
1033                 if (info->pcnt < info->i) {
1034                         ++info->pcnt;
1035                         return(0);
1036                 }
1037
1038                 d_ino = PROCFS_FILENO(p->p_pid, Pproc);
1039                 d_namlen = ksnprintf(d_name_pid, sizeof(d_name_pid),
1040                     "%ld", (long)p->p_pid);
1041                 d_name = d_name_pid;
1042                 d_type = DT_DIR;
1043                 break;
1044         }
1045
1046         /*
1047          * Skip entries we have already returned (optimization)
1048          */
1049         if (info->pcnt < info->i) {
1050                 ++info->pcnt;
1051                 return(0);
1052         }
1053
1054         retval = vop_write_dirent(&info->error, uio,
1055                                   d_ino, d_type, d_namlen, d_name);
1056         if (retval)
1057                 return(-1);
1058         ++info->pcnt;
1059         ++info->i;
1060         return(0);
1061 }
1062
1063 /*
1064  * readlink reads the link of `curproc' or `file'
1065  */
1066 static int
1067 procfs_readlink(struct vop_readlink_args *ap)
1068 {
1069         char buf[16];           /* should be enough */
1070         struct proc *procp;
1071         struct vnode *vp = ap->a_vp;
1072         struct pfsnode *pfs = VTOPFS(vp);
1073         char *fullpath, *freepath;
1074         int error, len;
1075
1076         switch (pfs->pfs_type) {
1077         case Pcurproc:
1078                 if (pfs->pfs_fileno != PROCFS_FILENO(0, Pcurproc))
1079                         return (EINVAL);
1080
1081                 len = ksnprintf(buf, sizeof(buf), "%ld", (long)curproc->p_pid);
1082
1083                 return (uiomove(buf, len, ap->a_uio));
1084         /*
1085          * There _should_ be no way for an entire process to disappear
1086          * from under us...
1087          */
1088         case Pfile:
1089                 procp = pfs_pfind(pfs->pfs_pid);
1090                 if (procp == NULL || procp->p_ucred == NULL) {
1091                         kprintf("procfs_readlink: pid %d disappeared\n",
1092                             pfs->pfs_pid);
1093                         pfs_pdone(procp);
1094                         return (uiomove("unknown", sizeof("unknown") - 1,
1095                                         ap->a_uio));
1096                 }
1097                 if (procp->p_textnch.ncp)
1098                         error = cache_fullpath(procp, &procp->p_textnch,
1099                                                &fullpath, &freepath, 0);
1100                 else
1101                         error = EINVAL;
1102
1103                 if (error != 0) {
1104                         pfs_pdone(procp);
1105                         return (uiomove("unknown", sizeof("unknown") - 1,
1106                                         ap->a_uio));
1107                 }
1108                 error = uiomove(fullpath, strlen(fullpath), ap->a_uio);
1109                 kfree(freepath, M_TEMP);
1110                 pfs_pdone(procp);
1111                 return (error);
1112         default:
1113                 return (EINVAL);
1114         }
1115 }
1116
1117 /*
1118  * convert decimal ascii to pid_t
1119  */
1120 static pid_t
1121 atopid(const char *b, u_int len)
1122 {
1123         pid_t p = 0;
1124
1125         while (len--) {
1126                 char c = *b++;
1127                 if (c < '0' || c > '9')
1128                         return (NO_PID);
1129                 p = 10 * p + (c - '0');
1130                 if (p > PID_MAX)
1131                         return (NO_PID);
1132         }
1133
1134         return (p);
1135 }
1136