]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/libpcap/pcap-dos.c
This commit was generated by cvs2svn to compensate for changes in r147824,
[FreeBSD/FreeBSD.git] / contrib / libpcap / pcap-dos.c
1 /*
2  *  This file is part of DOS-libpcap
3  *  Ported to DOS/DOSX by G. Vanem <giva@bgnett.no>
4  *
5  *  pcap-dos.c: Interface to PKTDRVR, NDIS2 and 32-bit pmode
6  *              network drivers.
7  *
8  * @(#) $Header: /tcpdump/master/libpcap/pcap-dos.c,v 1.1 2004/12/18 08:52:10 guy Exp $ (LBL)
9  */
10
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <signal.h>
15 #include <float.h>
16 #include <fcntl.h>
17 #include <io.h>
18
19 #if defined(USE_32BIT_DRIVERS)
20   #include "msdos/pm_drvr/pmdrvr.h"
21   #include "msdos/pm_drvr/pci.h"
22   #include "msdos/pm_drvr/bios32.h"
23   #include "msdos/pm_drvr/module.h"
24   #include "msdos/pm_drvr/3c501.h"
25   #include "msdos/pm_drvr/3c503.h"
26   #include "msdos/pm_drvr/3c509.h"
27   #include "msdos/pm_drvr/3c59x.h"
28   #include "msdos/pm_drvr/3c515.h"
29   #include "msdos/pm_drvr/3c90x.h"
30   #include "msdos/pm_drvr/3c575_cb.h"
31   #include "msdos/pm_drvr/ne.h"
32   #include "msdos/pm_drvr/wd.h"
33   #include "msdos/pm_drvr/accton.h"
34   #include "msdos/pm_drvr/cs89x0.h"
35   #include "msdos/pm_drvr/rtl8139.h"
36   #include "msdos/pm_drvr/ne2k-pci.h"
37 #endif
38
39 #include "pcap.h"
40 #include "pcap-dos.h"
41 #include "pcap-int.h"
42 #include "msdos/pktdrvr.h"
43
44 #ifdef USE_NDIS2
45 #include "msdos/ndis2.h"
46 #endif
47
48 #include <arpa/inet.h>
49 #include <net/if.h>
50 #include <net/if_arp.h>
51 #include <net/if_ether.h>
52 #include <net/if_packe.h>
53 #include <tcp.h>
54
55 #if defined(USE_32BIT_DRIVERS)
56   #define FLUSHK()       do { _printk_safe = 1; _printk_flush(); } while (0)
57   #define NDIS_NEXT_DEV  &rtl8139_dev
58
59   static char *rx_pool = NULL;
60   static void init_32bit (void);
61
62   static int  pktq_init     (struct rx_ringbuf *q, int size, int num, char *pool);
63   static int  pktq_check    (struct rx_ringbuf *q);
64   static int  pktq_inc_out  (struct rx_ringbuf *q);
65   static int  pktq_in_index (struct rx_ringbuf *q) LOCKED_FUNC;
66   static void pktq_clear    (struct rx_ringbuf *q) LOCKED_FUNC;
67
68   static struct rx_elem *pktq_in_elem  (struct rx_ringbuf *q) LOCKED_FUNC;
69   static struct rx_elem *pktq_out_elem (struct rx_ringbuf *q);
70
71 #else
72   #define FLUSHK()      ((void)0)
73   #define NDIS_NEXT_DEV  NULL
74 #endif
75
76 /*
77  * Internal variables/functions in Watt-32
78  */
79 extern WORD  _pktdevclass;
80 extern BOOL  _eth_is_init;
81 extern int   _w32_dynamic_host;
82 extern int   _watt_do_exit;
83 extern int   _watt_is_init;
84 extern int   _w32__bootp_on, _w32__dhcp_on, _w32__rarp_on, _w32__do_mask_req;
85 extern void (*_w32_usr_post_init) (void);
86 extern void (*_w32_print_hook)();
87
88 extern void dbug_write (const char *);  /* Watt-32 lib, pcdbug.c */
89 extern int  pkt_get_mtu (void);
90
91 static int ref_count = 0;
92
93 static u_long mac_count    = 0;
94 static u_long filter_count = 0;
95
96 static volatile BOOL exc_occured = 0;
97
98 static struct device *handle_to_device [20];
99
100 static int  pcap_read_dos (pcap_t *p, int cnt, pcap_handler callback,
101                            u_char *data);
102 static void pcap_close_dos (pcap_t *p);
103 static int  pcap_stats_dos (pcap_t *p, struct pcap_stat *ps);
104 static int  pcap_sendpacket_dos (pcap_t *p, const void *buf, size_t len);
105 static int  pcap_setfilter_dos (pcap_t *p, struct bpf_program *fp);
106
107 static int  ndis_probe (struct device *dev);
108 static int  pkt_probe  (struct device *dev);
109
110 static void close_driver (void);
111 static int  init_watt32 (struct pcap *pcap, const char *dev_name, char *err_buf);
112 static int  first_init (const char *name, char *ebuf, int promisc);
113
114 static void watt32_recv_hook (u_char *dummy, const struct pcap_pkthdr *pcap,
115                               const u_char *buf);
116
117 /*
118  * These are the device we always support
119  */
120 static struct device ndis_dev = {
121               "ndis",
122               "NDIS2 LanManager",
123               0,
124               0,0,0,0,0,0,
125               NDIS_NEXT_DEV,  /* NULL or a 32-bit device */
126               ndis_probe
127             };
128
129 static struct device pkt_dev = {
130               "pkt",
131               "Packet-Driver",
132               0,
133               0,0,0,0,0,0,
134               &ndis_dev,
135               pkt_probe
136             };
137
138 static struct device *get_device (int fd)
139 {
140   if (fd <= 0 || fd >= sizeof(handle_to_device)/sizeof(handle_to_device[0]))
141      return (NULL);
142   return handle_to_device [fd-1];
143 }
144
145 /*
146  * Open MAC-driver with name 'device_name' for live capture of
147  * network packets.
148  */
149 pcap_t *pcap_open_live (const char *device_name, int snaplen, int promisc,
150                         int timeout_ms, char *errbuf)
151
152   struct pcap *pcap;
153
154   if (snaplen < ETH_MIN)
155       snaplen = ETH_MIN;
156
157   if (snaplen > ETH_MAX)   /* silently accept and truncate large MTUs */
158       snaplen = ETH_MAX;
159
160   pcap = calloc (sizeof(*pcap), 1);
161   if (!pcap)
162   {
163     strcpy (errbuf, "Not enough memory (pcap)");
164     return (NULL);
165   }
166
167   pcap->snapshot          = max (ETH_MIN+8, snaplen);
168   pcap->linktype          = DLT_EN10MB;  /* !! */
169   pcap->inter_packet_wait = timeout_ms;
170   pcap->close_op          = pcap_close_dos;
171   pcap->read_op           = pcap_read_dos;
172   pcap->stats_op          = pcap_stats_dos;
173   pcap->inject_op         = pcap_sendpacket_dos;
174   pcap->setfilter_op      = pcap_setfilter_dos;
175   pcap->fd                = ++ref_count;
176
177   if (pcap->fd == 1)  /* first time we're called */
178   {
179     if (!init_watt32(pcap, device_name, errbuf) ||
180         !first_init(device_name, errbuf, promisc))
181     {
182       free (pcap);
183       return (NULL);
184     } 
185     atexit (close_driver);
186   }
187   else if (stricmp(active_dev->name,device_name))
188   {
189     snprintf (errbuf, PCAP_ERRBUF_SIZE,
190               "Cannot use different devices simultaneously "
191               "(`%s' vs. `%s')", active_dev->name, device_name);
192     free (pcap);
193     pcap = NULL;
194   }
195   handle_to_device [pcap->fd-1] = active_dev;
196   return (pcap);
197 }
198
199 /*
200  * Poll the receiver queue and call the pcap callback-handler
201  * with the packet.
202  */
203 static int
204 pcap_read_one (pcap_t *p, pcap_handler callback, u_char *data)
205 {
206   struct pcap_pkthdr pcap;
207   struct bpf_insn   *fcode = p->fcode.bf_insns;
208   struct timeval     now, expiry;
209   BYTE  *rx_buf;
210   int    rx_len = 0;
211
212   if (p->inter_packet_wait > 0)
213   {
214     gettimeofday2 (&now, NULL);
215     expiry.tv_usec = now.tv_usec + 1000UL * p->inter_packet_wait;
216     expiry.tv_sec  = now.tv_sec;
217     while (expiry.tv_usec >= 1000000L)
218     {
219       expiry.tv_usec -= 1000000L;
220       expiry.tv_sec++;
221     }
222   }
223
224   while (!exc_occured)
225   {
226     volatile struct device *dev; /* might be reset by sig_handler */
227
228     dev = get_device (p->fd);
229     if (!dev)
230        break;
231
232     PCAP_ASSERT (dev->copy_rx_buf || dev->peek_rx_buf);
233     FLUSHK();
234
235     /* If driver has a zero-copy receive facility, peek at the queue,
236      * filter it, do the callback and release the buffer.
237      */
238     if (dev->peek_rx_buf)
239     {
240       PCAP_ASSERT (dev->release_rx_buf);
241       rx_len = (*dev->peek_rx_buf) (&rx_buf);
242     }
243     else
244     {
245       BYTE buf [ETH_MAX+100]; /* add some margin */
246       rx_len = (*dev->copy_rx_buf) (buf, p->snapshot);
247       rx_buf = buf;
248     }
249
250     if (rx_len > 0)  /* got a packet */
251     {
252       mac_count++;
253
254       FLUSHK();
255
256       pcap.caplen = min (rx_len, p->snapshot);
257       pcap.len    = rx_len;
258
259       if (callback &&
260           (!fcode || bpf_filter(fcode, rx_buf, pcap.len, pcap.caplen)))
261       {
262         filter_count++;
263
264         /* Fix-me!! Should be time of arrival. Not time of
265          * capture.
266          */
267         gettimeofday2 (&pcap.ts, NULL);
268         (*callback) (data, &pcap, rx_buf);
269       }
270
271       if (dev->release_rx_buf)
272         (*dev->release_rx_buf) (rx_buf);
273
274       if (pcap_pkt_debug > 0)
275       {
276         if (callback == watt32_recv_hook)
277              dbug_write ("pcap_recv_hook\n");
278         else dbug_write ("pcap_read_op\n");
279       }
280       FLUSHK();
281       return (1);
282     }
283
284     /* If not to wait for a packet or pcap_close() called from
285      * e.g. SIGINT handler, exit loop now.
286      */
287     if (p->inter_packet_wait <= 0 || (volatile int)p->fd <= 0)
288        break;
289
290     gettimeofday2 (&now, NULL);
291
292     if (timercmp(&now, &expiry, >))
293        break;
294
295 #ifndef DJGPP
296     kbhit();    /* a real CPU hog */
297 #endif
298
299     if (p->wait_proc)
300       (*p->wait_proc)();     /* call yield func */
301   }
302
303   if (rx_len < 0)            /* receive error */
304   {
305     p->md.stat.ps_drop++;
306 #ifdef USE_32BIT_DRIVERS
307     if (pcap_pkt_debug > 1)
308        printk ("pkt-err %s\n", pktInfo.error);
309 #endif
310     return (-1);
311   }
312   return (0);
313 }
314
315 static int
316 pcap_read_dos (pcap_t *p, int cnt, pcap_handler callback, u_char *data)
317 {
318   int rc, num = 0;
319
320   while (num <= cnt || (cnt < 0))
321   {
322     if (p->fd <= 0)
323        return (-1);
324     rc = pcap_read_one (p, callback, data);
325     if (rc > 0)
326        num++;
327     if (rc < 0)
328        break;
329     _w32_os_yield();  /* allow SIGINT generation, yield to Win95/NT */
330   }
331   return (num);
332 }
333
334 /*
335  * Return network statistics
336  */
337 static int pcap_stats_dos (pcap_t *p, struct pcap_stat *ps)
338 {
339   struct net_device_stats *stats;
340   struct device           *dev = p ? get_device(p->fd) : NULL;
341
342   if (!dev)
343   {
344     strcpy (p->errbuf, "illegal pcap handle");
345     return (-1);
346   }
347
348   if (!dev->get_stats || (stats = (*dev->get_stats)(dev)) == NULL)
349   {
350     strcpy (p->errbuf, "device statistics not available");
351     return (-1);
352   }
353
354   FLUSHK();
355
356   p->md.stat.ps_recv   = stats->rx_packets;
357   p->md.stat.ps_drop  += stats->rx_missed_errors;
358   p->md.stat.ps_ifdrop = stats->rx_dropped +  /* queue full */
359                          stats->rx_errors;    /* HW errors */
360   if (ps)
361      *ps = p->md.stat;
362
363   return (0);
364 }
365
366 /*
367  * Return detailed network/device statistics.
368  * May be called after 'dev->close' is called.
369  */
370 int pcap_stats_ex (pcap_t *p, struct pcap_stat_ex *se)
371 {
372   struct device *dev = p ? get_device (p->fd) : NULL;
373
374   if (!dev || !dev->get_stats)
375   {
376     strlcpy (p->errbuf, "detailed device statistics not available",
377              PCAP_ERRBUF_SIZE);
378     return (-1);
379   }
380
381   if (!strnicmp(dev->name,"pkt",3))
382   {
383     strlcpy (p->errbuf, "pktdrvr doesn't have detailed statistics",
384              PCAP_ERRBUF_SIZE);
385     return (-1);
386   }             
387   memcpy (se, (*dev->get_stats)(dev), sizeof(*se));
388   return (0);
389 }
390
391 /*
392  * Simply store the filter-code for the pcap_read_dos() callback
393  * Some day the filter-code could be handed down to the active
394  * device (pkt_rx1.s or 32-bit device interrupt handler).
395  */
396 static int pcap_setfilter_dos (pcap_t *p, struct bpf_program *fp)
397 {
398   if (!p)
399      return (-1);
400   p->fcode = *fp;
401   return (0);
402 }
403
404 /*
405  * Return # of packets received in pcap_read_dos()
406  */
407 u_long pcap_mac_packets (void)
408 {
409   return (mac_count);
410 }
411
412 /*
413  * Return # of packets passed through filter in pcap_read_dos()
414  */
415 u_long pcap_filter_packets (void)
416 {
417   return (filter_count);
418 }
419
420 /*
421  * Close pcap device. Not called for offline captures.
422  */
423 static void pcap_close_dos (pcap_t *p)
424 {
425   if (p && !exc_occured)
426   {
427     if (pcap_stats(p,NULL) < 0)
428        p->md.stat.ps_drop = 0;
429     if (!get_device(p->fd))
430        return;
431
432     handle_to_device [p->fd-1] = NULL;
433     p->fd = 0;
434     if (ref_count > 0)
435         ref_count--;
436     if (ref_count > 0)
437        return;
438   }
439   close_driver();
440 }
441
442 /*
443  * Return the name of the 1st network interface,
444  * or NULL if none can be found.
445  */
446 char *pcap_lookupdev (char *ebuf)
447 {
448   struct device *dev;
449
450 #ifdef USE_32BIT_DRIVERS
451   init_32bit();
452 #endif
453
454   for (dev = (struct device*)dev_base; dev; dev = dev->next)
455   {
456     PCAP_ASSERT (dev->probe);
457
458     if ((*dev->probe)(dev))
459     {
460       FLUSHK();
461       probed_dev = (struct device*) dev; /* remember last probed device */
462       return (char*) dev->name;
463     }
464   }
465
466   if (ebuf)
467      strcpy (ebuf, "No driver found");
468   return (NULL);
469 }
470
471 /*
472  * Gets localnet & netmask from Watt-32.
473  */
474 int pcap_lookupnet (const char *device, bpf_u_int32 *localnet,
475                     bpf_u_int32 *netmask, char *errbuf)
476 {
477   if (!_watt_is_init)
478   {
479     strcpy (errbuf, "pcap_open_offline() or pcap_open_live() must be "
480                     "called first");
481     return (-1);
482   }
483
484   *netmask  = _w32_sin_mask;
485   *localnet = my_ip_addr & *netmask;
486   if (*localnet == 0)
487   {
488     if (IN_CLASSA(*netmask))
489        *localnet = IN_CLASSA_NET;
490     else if (IN_CLASSB(*netmask))
491        *localnet = IN_CLASSB_NET;
492     else if (IN_CLASSC(*netmask))
493        *localnet = IN_CLASSC_NET;
494     else
495     {
496       sprintf (errbuf, "inet class for 0x%lx unknown", *netmask);
497       return (-1);
498     }
499   }
500   ARGSUSED (device);
501   return (0);
502 }      
503
504 /*
505  * Get a list of all interfaces that are present and that we probe okay.
506  * Returns -1 on error, 0 otherwise.
507  * The list, as returned through "alldevsp", may be null if no interfaces
508  * were up and could be opened.
509  */
510 int pcap_findalldevs (pcap_if_t **alldevsp, char *errbuf)
511 {
512   struct device     *dev;
513   struct sockaddr_ll sa_ll_1, sa_ll_2;
514   struct sockaddr   *addr, *netmask, *broadaddr, *dstaddr;
515   pcap_if_t *devlist = NULL;
516   int       ret = 0;
517   size_t    addr_size = sizeof(struct sockaddr_ll);
518
519   for (dev = (struct device*)dev_base; dev; dev = dev->next)
520   {
521     PCAP_ASSERT (dev->probe);
522
523     if (!(*dev->probe)(dev))
524        continue;
525
526     PCAP_ASSERT (dev->close);  /* set by probe routine */
527     FLUSHK();
528     (*dev->close) (dev);
529
530     memset (&sa_ll_1, 0, sizeof(sa_ll_1));
531     memset (&sa_ll_2, 0, sizeof(sa_ll_2));
532     sa_ll_1.sll_family = AF_PACKET;
533     sa_ll_2.sll_family = AF_PACKET;
534
535     addr      = (struct sockaddr*) &sa_ll_1;
536     netmask   = (struct sockaddr*) &sa_ll_1;
537     dstaddr   = (struct sockaddr*) &sa_ll_1;
538     broadaddr = (struct sockaddr*) &sa_ll_2;
539     memset (&sa_ll_2.sll_addr, 0xFF, sizeof(sa_ll_2.sll_addr));
540
541     if (pcap_add_if(&devlist, dev->name, dev->flags,
542                     dev->long_name, errbuf) < 0)
543     {
544       ret = -1;
545       break;
546     }
547     if (add_addr_to_iflist(&devlist,dev->name, dev->flags, addr, addr_size,
548                            netmask, addr_size, broadaddr, addr_size,
549                            dstaddr, addr_size, errbuf) < 0)
550     {
551       ret = -1;
552       break;
553     }
554   }
555
556   if (devlist && ret < 0)
557   {
558     pcap_freealldevs (devlist);
559     devlist = NULL;
560   }
561   else
562   if (!devlist)
563      strcpy (errbuf, "No drivers found");
564
565   *alldevsp = devlist;
566   return (ret);
567 }
568
569 /*
570  * pcap_assert() is mainly used for debugging
571  */
572 void pcap_assert (const char *what, const char *file, unsigned line)
573 {
574   FLUSHK();
575   fprintf (stderr, "%s (%u): Assertion \"%s\" failed\n",
576            file, line, what);
577   close_driver();
578   _exit (-1);
579 }
580
581 /*
582  * For pcap_offline_read(): wait and yield between printing packets
583  * to simulate the pace packets where actually recorded.
584  */
585 void pcap_set_wait (pcap_t *p, void (*yield)(void), int wait)
586 {
587   if (p)
588   {
589     p->wait_proc         = yield;
590     p->inter_packet_wait = wait;
591   }
592 }
593
594 /*
595  * Initialise a named network device.
596  */
597 static struct device *
598 open_driver (const char *dev_name, char *ebuf, int promisc)
599 {
600   struct device *dev;
601
602   for (dev = (struct device*)dev_base; dev; dev = dev->next)
603   {
604     PCAP_ASSERT (dev->name);
605
606     if (strcmp (dev_name,dev->name))
607        continue;
608
609     if (!probed_dev)   /* user didn't call pcap_lookupdev() first */
610     {
611       PCAP_ASSERT (dev->probe);
612
613       if (!(*dev->probe)(dev))    /* call the xx_probe() function */
614       {
615         sprintf (ebuf, "failed to detect device `%s'", dev_name);
616         return (NULL);
617       }
618       probed_dev = dev;  /* device is probed okay and may be used */
619     }
620     else if (dev != probed_dev)
621     {
622       goto not_probed;
623     }
624
625     FLUSHK();
626
627     /* Select what traffic to receive
628      */
629     if (promisc)
630          dev->flags |=  (IFF_ALLMULTI | IFF_PROMISC);
631     else dev->flags &= ~(IFF_ALLMULTI | IFF_PROMISC);
632
633     PCAP_ASSERT (dev->open);
634
635     if (!(*dev->open)(dev))
636     {
637       sprintf (ebuf, "failed to activate device `%s'", dev_name);
638       if (pktInfo.error && !strncmp(dev->name,"pkt",3))
639       {
640         strcat (ebuf, ": ");
641         strcat (ebuf, pktInfo.error);
642       }
643       return (NULL);
644     }
645
646     /* Some devices need this to operate in promiscous mode
647      */
648     if (promisc && dev->set_multicast_list)
649        (*dev->set_multicast_list) (dev);
650
651     active_dev = dev;   /* remember our active device */
652     break;
653   }
654
655   /* 'dev_name' not matched in 'dev_base' list.
656    */
657   if (!dev)
658   {
659     sprintf (ebuf, "device `%s' not supported", dev_name);
660     return (NULL);
661   }
662
663 not_probed:
664   if (!probed_dev)
665   {
666     sprintf (ebuf, "device `%s' not probed", dev_name);
667     return (NULL);
668   }
669   return (dev);
670 }
671
672 /*
673  * Deinitialise MAC driver.
674  * Set receive mode back to default mode.
675  */
676 static void close_driver (void)
677 {
678   /* !!todo: loop over all 'handle_to_device[]' ? */
679   struct device *dev = active_dev;
680
681   if (dev && dev->close)
682   {
683     (*dev->close) (dev);
684     FLUSHK();
685   }
686
687   active_dev = NULL;
688
689 #ifdef USE_32BIT_DRIVERS
690   if (rx_pool)
691   {
692     k_free (rx_pool);
693     rx_pool = NULL;
694   }
695   if (dev)
696      pcibios_exit();
697 #endif
698 }
699
700
701 #ifdef __DJGPP__
702 static void setup_signals (void (*handler)(int))
703 {
704   signal (SIGSEGV,handler);
705   signal (SIGILL, handler);
706   signal (SIGFPE, handler);
707 }
708
709 static void exc_handler (int sig)
710 {
711 #ifdef USE_32BIT_DRIVERS
712   if (active_dev->irq > 0)    /* excludes IRQ 0 */
713   {
714     disable_irq (active_dev->irq);
715     irq_eoi_cmd (active_dev->irq);
716     _printk_safe = 1;
717   }
718 #endif
719
720   switch (sig)
721   {
722     case SIGSEGV:
723          fputs ("Catching SIGSEGV.\n", stderr);
724          break;
725     case SIGILL:
726          fputs ("Catching SIGILL.\n", stderr);
727          break;
728     case SIGFPE:
729          _fpreset();
730          fputs ("Catching SIGFPE.\n", stderr);
731          break;
732     default:
733          fprintf (stderr, "Catching signal %d.\n", sig);
734   }
735   exc_occured = 1;
736   pcap_close_dos (NULL);
737 }
738 #endif  /* __DJGPP__ */
739
740
741 /*
742  * Open the pcap device for the first client calling pcap_open_live()
743  */
744 static int first_init (const char *name, char *ebuf, int promisc)
745 {
746   struct device *dev;
747
748 #ifdef USE_32BIT_DRIVERS
749   rx_pool = k_calloc (RECEIVE_BUF_SIZE, RECEIVE_QUEUE_SIZE);
750   if (!rx_pool)
751   {
752     strcpy (ebuf, "Not enough memory (Rx pool)");
753     return (0);
754   }
755 #endif
756
757 #ifdef __DJGPP__
758   setup_signals (exc_handler);
759 #endif
760
761 #ifdef USE_32BIT_DRIVERS
762   init_32bit();
763 #endif
764
765   dev = open_driver (name, ebuf, promisc);
766   if (!dev)
767   {
768 #ifdef USE_32BIT_DRIVERS
769     k_free (rx_pool);
770     rx_pool = NULL;
771 #endif
772
773 #ifdef __DJGPP__
774     setup_signals (SIG_DFL);
775 #endif
776     return (0);
777   }
778
779 #ifdef USE_32BIT_DRIVERS
780   /*
781    * If driver is NOT a 16-bit "pkt/ndis" driver (having a 'copy_rx_buf'
782    * set in it's probe handler), initialise near-memory ring-buffer for
783    * the 32-bit device.
784    */
785   if (dev->copy_rx_buf == NULL)
786   {
787     dev->get_rx_buf     = get_rxbuf;
788     dev->peek_rx_buf    = peek_rxbuf;
789     dev->release_rx_buf = release_rxbuf;
790     pktq_init (&dev->queue, RECEIVE_BUF_SIZE, RECEIVE_QUEUE_SIZE, rx_pool);
791   }
792 #endif
793   return (1);
794 }
795
796 #ifdef USE_32BIT_DRIVERS
797 static void init_32bit (void)
798 {
799   static int init_pci = 0;
800
801   if (!_printk_file)
802      _printk_init (64*1024, NULL); /* calls atexit(printk_exit) */
803
804   if (!init_pci)
805      (void)pci_init();             /* init BIOS32+PCI interface */
806   init_pci = 1;
807 }
808 #endif
809
810
811 /*
812  * Hook functions for using Watt-32 together with pcap
813  */
814 static char rxbuf [ETH_MAX+100]; /* rx-buffer with some margin */
815 static WORD etype;
816 static pcap_t pcap_save;
817
818 static void watt32_recv_hook (u_char *dummy, const struct pcap_pkthdr *pcap,
819                               const u_char *buf)
820 {
821   /* Fix me: assumes Ethernet II only */
822   struct ether_header *ep = (struct ether_header*) buf;
823
824   memcpy (rxbuf, buf, pcap->caplen);
825   etype = ep->ether_type;
826   ARGSUSED (dummy);
827 }
828
829 #if (WATTCP_VER >= 0x0224)
830 /*
831  * This function is used by Watt-32 to poll for a packet.
832  * i.e. it's set to bypass _eth_arrived()
833  */
834 static void *pcap_recv_hook (WORD *type)
835 {
836   int len = pcap_read_dos (&pcap_save, 1, watt32_recv_hook, NULL);
837
838   if (len < 0)
839      return (NULL);
840
841   *type = etype;
842   return (void*) &rxbuf;
843 }
844
845 /*
846  * This function is called by Watt-32 (via _eth_xmit_hook).
847  * If dbug_init() was called, we should trace packets sent.
848  */
849 static int pcap_xmit_hook (const void *buf, unsigned len)
850 {
851   int rc = 0;
852
853   if (pcap_pkt_debug > 0)
854      dbug_write ("pcap_xmit_hook: ");
855
856   if (active_dev && active_dev->xmit)
857      if ((*active_dev->xmit) (active_dev, buf, len) > 0)
858         rc = len;
859
860   if (pcap_pkt_debug > 0)
861      dbug_write (rc ? "ok\n" : "fail\n");
862   return (rc);
863 }
864 #endif
865
866 static int pcap_sendpacket_dos (pcap_t *p, const void *buf, size_t len)
867 {
868   struct device *dev = p ? get_device(p->fd) : NULL;
869
870   if (!dev || !dev->xmit)
871      return (-1);
872   return (*dev->xmit) (dev, buf, len);
873 }
874
875 /*
876  * This function is called by Watt-32 in tcp_post_init().
877  * We should prevent Watt-32 from using BOOTP/DHCP/RARP etc.
878  */
879 static void (*prev_post_hook) (void);
880
881 static void pcap_init_hook (void)
882 {
883   _w32__bootp_on = _w32__dhcp_on = _w32__rarp_on = 0;
884   _w32__do_mask_req = 0;
885   _w32_dynamic_host = 0;
886   if (prev_post_hook)
887     (*prev_post_hook)();
888 }
889
890 /*
891  * Supress PRINT message from Watt-32's sock_init()
892  */
893 static void null_print (void) {}
894
895 /*
896  * To use features of Watt-32 (netdb functions and socket etc.)
897  * we must call sock_init(). But we set various hooks to prevent
898  * using normal PKTDRVR functions in pcpkt.c. This should hopefully
899  * make Watt-32 and pcap co-operate.
900  */
901 static int init_watt32 (struct pcap *pcap, const char *dev_name, char *err_buf)
902 {
903   char *env;
904   int   rc, MTU, has_ip_addr;
905   int   using_pktdrv = 1;
906
907   /* If user called sock_init() first, we need to reinit in
908    * order to open debug/trace-file properly
909    */
910   if (_watt_is_init)
911      sock_exit();
912
913   env = getenv ("PCAP_DEBUG");
914   if (env && atoi(env) > 0 &&
915       pcap_pkt_debug < 0)   /* if not already set */
916   {
917     dbug_init();
918     pcap_pkt_debug = atoi (env);
919   }
920
921   _watt_do_exit      = 0;    /* prevent sock_init() calling exit() */
922   prev_post_hook     = _w32_usr_post_init;
923   _w32_usr_post_init = pcap_init_hook;
924   _w32_print_hook    = null_print;
925
926   if (dev_name && strncmp(dev_name,"pkt",3))
927      using_pktdrv = FALSE;
928
929   rc = sock_init();
930   has_ip_addr = (rc != 8);  /* IP-address assignment failed */
931
932   /* if pcap is using a 32-bit driver w/o a pktdrvr loaded, we
933    * just pretend Watt-32 is initialised okay.
934    *
935    * !! fix-me: The Watt-32 config isn't done if no pktdrvr
936    *            was found. In that case my_ip_addr + sin_mask
937    *            have default values. Should be taken from another
938    *            ini-file/environment in any case (ref. tcpdump.ini)
939    */
940   _watt_is_init = 1;  
941
942   if (!using_pktdrv || !has_ip_addr)  /* for now .... */
943   {
944     static const char myip[] = "192.168.0.1";
945     static const char mask[] = "255.255.255.0";
946
947     printf ("Just guessing, using IP %s and netmask %s\n", myip, mask);
948     my_ip_addr    = aton (myip);
949     _w32_sin_mask = aton (mask);
950   }
951   else if (rc && using_pktdrv)
952   {
953     sprintf (err_buf, "sock_init() failed, code %d", rc);
954     return (0);
955   }
956
957   /* Set recv-hook for peeking in _eth_arrived().
958    */
959 #if (WATTCP_VER >= 0x0224)
960   _eth_recv_hook = pcap_recv_hook;
961   _eth_xmit_hook = pcap_xmit_hook;
962 #endif
963
964   /* Free the pkt-drvr handle allocated in pkt_init().
965    * The above hooks should thus use the handle reopened in open_driver()
966    */
967   if (using_pktdrv)
968   {
969     _eth_release();
970 /*  _eth_is_init = 1; */  /* hack to get Rx/Tx-hooks in Watt-32 working */
971   }
972
973   memcpy (&pcap_save, pcap, sizeof(pcap_save));
974   MTU = pkt_get_mtu();
975   pcap_save.fcode.bf_insns = NULL;
976   pcap_save.linktype       = _eth_get_hwtype (NULL, NULL);
977   pcap_save.snapshot       = MTU > 0 ? MTU : ETH_MAX; /* assume 1514 */
978
979 #if 1
980   /* prevent use of resolve() and resolve_ip()
981    */
982   last_nameserver = 0;
983 #endif
984   return (1);
985 }
986
987 int EISA_bus = 0;  /* Where is natural place for this? */
988
989 /*
990  * Application config hooks to set various driver parameters.
991  */
992
993 static struct config_table debug_tab[] = {
994             { "PKT.DEBUG",       ARG_ATOI,   &pcap_pkt_debug    },
995             { "PKT.VECTOR",      ARG_ATOX_W, NULL               },
996             { "NDIS.DEBUG",      ARG_ATOI,   NULL               },
997 #ifdef USE_32BIT_DRIVERS
998             { "3C503.DEBUG",     ARG_ATOI,   &ei_debug          },
999             { "3C503.IO_BASE",   ARG_ATOX_W, &el2_dev.base_addr },
1000             { "3C503.MEMORY",    ARG_ATOX_W, &el2_dev.mem_start },
1001             { "3C503.IRQ",       ARG_ATOI,   &el2_dev.irq       },
1002             { "3C505.DEBUG",     ARG_ATOI,   NULL               },
1003             { "3C505.BASE",      ARG_ATOX_W, NULL               },
1004             { "3C507.DEBUG",     ARG_ATOI,   NULL               },
1005             { "3C509.DEBUG",     ARG_ATOI,   &el3_debug         },
1006             { "3C509.ILOOP",     ARG_ATOI,   &el3_max_loop      },
1007             { "3C529.DEBUG",     ARG_ATOI,   NULL               },
1008             { "3C575.DEBUG",     ARG_ATOI,   &debug_3c575       },
1009             { "3C59X.DEBUG",     ARG_ATOI,   &vortex_debug      },
1010             { "3C59X.IFACE0",    ARG_ATOI,   &vortex_options[0] },
1011             { "3C59X.IFACE1",    ARG_ATOI,   &vortex_options[1] },
1012             { "3C59X.IFACE2",    ARG_ATOI,   &vortex_options[2] },
1013             { "3C59X.IFACE3",    ARG_ATOI,   &vortex_options[3] },
1014             { "3C90X.DEBUG",     ARG_ATOX_W, &tc90xbc_debug     },
1015             { "ACCT.DEBUG",      ARG_ATOI,   &ethpk_debug       },
1016             { "CS89.DEBUG",      ARG_ATOI,   &cs89_debug        },
1017             { "RTL8139.DEBUG",   ARG_ATOI,   &rtl8139_debug     },
1018         /*  { "RTL8139.FDUPLEX", ARG_ATOI,   &rtl8139_options   }, */
1019             { "SMC.DEBUG",       ARG_ATOI,   &ei_debug          },
1020         /*  { "E100.DEBUG",      ARG_ATOI,   &e100_debug        }, */
1021             { "PCI.DEBUG",       ARG_ATOI,   &pci_debug         },
1022             { "BIOS32.DEBUG",    ARG_ATOI,   &bios32_debug      },
1023             { "IRQ.DEBUG",       ARG_ATOI,   &irq_debug         },
1024             { "TIMER.IRQ",       ARG_ATOI,   &timer_irq         },
1025 #endif
1026             { NULL }
1027           };
1028
1029 /*
1030  * pcap_config_hook() is an extension to application's config
1031  * handling. Uses Watt-32's config-table function.
1032  */
1033 int pcap_config_hook (const char *name, const char *value)
1034 {
1035   return parse_config_table (debug_tab, NULL, name, value);
1036 }
1037
1038 /*
1039  * Linked list of supported devices
1040  */
1041 struct device       *active_dev = NULL;      /* the device we have opened */
1042 struct device       *probed_dev = NULL;      /* the device we have probed */
1043 const struct device *dev_base   = &pkt_dev;  /* list of network devices */
1044
1045 /*
1046  * PKTDRVR device functions
1047  */
1048 int pcap_pkt_debug = -1;
1049
1050 static void pkt_close (struct device *dev)
1051 {
1052   BOOL okay = PktExitDriver();
1053
1054   if (pcap_pkt_debug > 1)
1055      fprintf (stderr, "pkt_close(): %d\n", okay);
1056
1057   if (dev->priv)
1058      free (dev->priv);
1059   dev->priv = NULL;
1060 }
1061
1062 static int pkt_open (struct device *dev)
1063 {
1064   PKT_RX_MODE mode;
1065
1066   if (dev->flags & IFF_PROMISC)
1067        mode = PDRX_ALL_PACKETS;
1068   else mode = PDRX_BROADCAST;
1069
1070   if (!PktInitDriver(mode))
1071      return (0);
1072  
1073   PktResetStatistics (pktInfo.handle);
1074   PktQueueBusy (FALSE);
1075   return (1);
1076 }
1077
1078 static int pkt_xmit (struct device *dev, const void *buf, int len)
1079 {
1080   struct net_device_stats *stats = (struct net_device_stats*) dev->priv;
1081
1082   if (pcap_pkt_debug > 0)
1083      dbug_write ("pcap_xmit\n");
1084
1085   if (!PktTransmit(buf,len))
1086   {
1087     stats->tx_errors++;
1088     return (0);
1089   }
1090   return (len);
1091 }
1092
1093 static void *pkt_stats (struct device *dev)
1094 {
1095   struct net_device_stats *stats = (struct net_device_stats*) dev->priv;
1096
1097   if (!stats || !PktSessStatistics(pktInfo.handle))
1098      return (NULL);
1099
1100   stats->rx_packets       = pktStat.inPackets;
1101   stats->rx_errors        = pktStat.lost;
1102   stats->rx_missed_errors = PktRxDropped();
1103   return (stats);
1104 }
1105
1106 static int pkt_probe (struct device *dev)
1107 {
1108   if (!PktSearchDriver())
1109      return (0);
1110
1111   dev->open           = pkt_open;
1112   dev->xmit           = pkt_xmit;
1113   dev->close          = pkt_close;
1114   dev->get_stats      = pkt_stats;
1115   dev->copy_rx_buf    = PktReceive;  /* farmem peek and copy routine */
1116   dev->get_rx_buf     = NULL;
1117   dev->peek_rx_buf    = NULL;
1118   dev->release_rx_buf = NULL;
1119   dev->priv           = calloc (sizeof(struct net_device_stats), 1);
1120   if (!dev->priv)
1121      return (0);
1122   return (1);
1123 }
1124
1125 /*
1126  * NDIS device functions
1127  */
1128 static void ndis_close (struct device *dev)
1129 {
1130 #ifdef USE_NDIS2
1131   NdisShutdown();
1132 #endif
1133   ARGSUSED (dev);
1134 }
1135
1136 static int ndis_open (struct device *dev)
1137 {
1138   int promis = (dev->flags & IFF_PROMISC);
1139
1140 #ifdef USE_NDIS2
1141   if (!NdisInit(promis))
1142      return (0);
1143   return (1);
1144 #else
1145   ARGSUSED (promis);
1146   return (0);
1147 #endif
1148 }
1149
1150 static void *ndis_stats (struct device *dev)
1151 {
1152   static struct net_device_stats stats;
1153
1154   /* to-do */
1155   ARGSUSED (dev);
1156   return (&stats);
1157 }
1158
1159 static int ndis_probe (struct device *dev)
1160 {
1161 #ifdef USE_NDIS2
1162   if (!NdisOpen())
1163      return (0);
1164 #endif
1165
1166   dev->open           = ndis_open;
1167   dev->xmit           = NULL;
1168   dev->close          = ndis_close;
1169   dev->get_stats      = ndis_stats;
1170   dev->copy_rx_buf    = NULL;       /* to-do */
1171   dev->get_rx_buf     = NULL;       /* upcall is from rmode driver */
1172   dev->peek_rx_buf    = NULL;
1173   dev->release_rx_buf = NULL;
1174   return (0);
1175 }
1176
1177 /*
1178  * Search & probe for supported 32-bit (pmode) pcap devices
1179  */
1180 #if defined(USE_32BIT_DRIVERS)
1181
1182 struct device el2_dev LOCKED_VAR = {
1183               "3c503",
1184               "EtherLink II",
1185               0,
1186               0,0,0,0,0,0,
1187               NULL,
1188               el2_probe
1189             };
1190
1191 struct device el3_dev LOCKED_VAR = {
1192               "3c509",
1193               "EtherLink III",
1194               0,
1195               0,0,0,0,0,0,
1196               &el2_dev,
1197               el3_probe
1198             };
1199
1200 struct device tc515_dev LOCKED_VAR = {
1201               "3c515",
1202               "EtherLink PCI",
1203               0,
1204               0,0,0,0,0,0,
1205               &el3_dev,
1206               tc515_probe
1207             };
1208
1209 struct device tc59_dev LOCKED_VAR = {
1210               "3c59x",
1211               "EtherLink PCI",
1212               0,
1213               0,0,0,0,0,0,
1214               &tc515_dev,
1215               tc59x_probe
1216             };
1217
1218 struct device tc90xbc_dev LOCKED_VAR = {
1219               "3c90x",
1220               "EtherLink 90X",
1221               0,
1222               0,0,0,0,0,0,
1223               &tc59_dev,
1224               tc90xbc_probe
1225             };
1226
1227 struct device wd_dev LOCKED_VAR = {
1228               "wd",
1229               "Westen Digital",
1230               0,
1231               0,0,0,0,0,0,
1232               &tc90xbc_dev,
1233               wd_probe
1234             };
1235
1236 struct device ne_dev LOCKED_VAR = {
1237               "ne",
1238               "NEx000",
1239               0,
1240               0,0,0,0,0,0,
1241               &wd_dev,
1242               ne_probe
1243             };
1244
1245 struct device acct_dev LOCKED_VAR = {
1246               "acct",
1247               "Accton EtherPocket",
1248               0,
1249               0,0,0,0,0,0,
1250               &ne_dev,
1251               ethpk_probe
1252             };
1253
1254 struct device cs89_dev LOCKED_VAR = {
1255               "cs89",
1256               "Crystal Semiconductor",
1257               0,
1258               0,0,0,0,0,0,
1259               &acct_dev,
1260               cs89x0_probe
1261             };
1262
1263 struct device rtl8139_dev LOCKED_VAR = {
1264               "rtl8139",
1265               "RealTek PCI",
1266               0,
1267               0,0,0,0,0,0,
1268               &cs89_dev,
1269               rtl8139_probe     /* dev->probe routine */
1270             };            
1271
1272 /*
1273  * Dequeue routine is called by polling.
1274  * NOTE: the queue-element is not copied, only a pointer is
1275  * returned at '*buf'
1276  */
1277 int peek_rxbuf (BYTE **buf)
1278 {
1279   struct rx_elem *tail, *head;
1280
1281   PCAP_ASSERT (pktq_check (&active_dev->queue));
1282
1283   DISABLE();
1284   tail = pktq_out_elem (&active_dev->queue);
1285   head = pktq_in_elem (&active_dev->queue);
1286   ENABLE();
1287
1288   if (head != tail)
1289   {
1290     PCAP_ASSERT (tail->size < active_dev->queue.elem_size-4-2);
1291
1292     *buf = &tail->data[0];
1293     return (tail->size);
1294   }
1295   *buf = NULL;
1296   return (0);
1297 }
1298
1299 /*
1300  * Release buffer we peeked at above.
1301  */
1302 int release_rxbuf (BYTE *buf)
1303 {
1304 #ifndef NDEBUG
1305   struct rx_elem *tail = pktq_out_elem (&active_dev->queue);
1306
1307   PCAP_ASSERT (&tail->data[0] == buf);
1308 #else
1309   ARGSUSED (buf);
1310 #endif
1311   pktq_inc_out (&active_dev->queue);
1312   return (1);
1313 }
1314
1315 /*
1316  * get_rxbuf() routine (in locked code) is called from IRQ handler
1317  * to request a buffer. Interrupts are disabled and we have a 32kB stack.
1318  */
1319 BYTE *get_rxbuf (int len)
1320 {
1321   int idx;
1322
1323   if (len < ETH_MIN || len > ETH_MAX)
1324      return (NULL);
1325
1326   idx = pktq_in_index (&active_dev->queue);
1327
1328 #ifdef DEBUG
1329   {
1330     static int fan_idx LOCKED_VAR = 0;
1331     writew ("-\\|/"[fan_idx++] | (15 << 8),      /* white on black colour */
1332             0xB8000 + 2*79);  /* upper-right corner, 80-col colour screen */
1333     fan_idx &= 3;
1334   }
1335 /* writew (idx + '0' + 0x0F00, 0xB8000 + 2*78); */
1336 #endif
1337
1338   if (idx != active_dev->queue.out_index)
1339   {
1340     struct rx_elem *head = pktq_in_elem (&active_dev->queue);
1341
1342     head->size = len;
1343     active_dev->queue.in_index = idx;
1344     return (&head->data[0]);
1345   }
1346
1347   /* !!to-do: drop 25% of the oldest element
1348    */
1349   pktq_clear (&active_dev->queue);
1350   return (NULL);
1351 }
1352
1353 /*
1354  *  Simple ring-buffer queue handler for reception of packets
1355  *  from network driver.
1356  */
1357 #define PKTQ_MARKER  0xDEADBEEF
1358
1359 static int pktq_check (struct rx_ringbuf *q)
1360 {
1361 #ifndef NDEBUG
1362   int   i;
1363   char *buf;
1364 #endif
1365
1366   if (!q || !q->num_elem || !q->buf_start)
1367      return (0);
1368
1369 #ifndef NDEBUG
1370   buf = q->buf_start;
1371
1372   for (i = 0; i < q->num_elem; i++)
1373   {
1374     buf += q->elem_size;
1375     if (*(DWORD*)(buf - sizeof(DWORD)) != PKTQ_MARKER)
1376        return (0);
1377   }
1378 #endif
1379   return (1);
1380 }
1381
1382 static int pktq_init (struct rx_ringbuf *q, int size, int num, char *pool)
1383 {
1384   int i;
1385
1386   q->elem_size = size;
1387   q->num_elem  = num;
1388   q->buf_start = pool;
1389   q->in_index  = 0;
1390   q->out_index = 0;
1391
1392   PCAP_ASSERT (size >= sizeof(struct rx_elem) + sizeof(DWORD));
1393   PCAP_ASSERT (num);
1394   PCAP_ASSERT (pool);
1395
1396   for (i = 0; i < num; i++)
1397   {
1398 #if 0
1399     struct rx_elem *elem = (struct rx_elem*) pool;
1400
1401     /* assert dword aligned elements
1402      */
1403     PCAP_ASSERT (((unsigned)(&elem->data[0]) & 3) == 0);
1404 #endif
1405     pool += size;
1406     *(DWORD*) (pool - sizeof(DWORD)) = PKTQ_MARKER;
1407   }
1408   return (1);
1409 }
1410
1411 /*
1412  * Increment the queue 'out_index' (tail).
1413  * Check for wraps.
1414  */
1415 static int pktq_inc_out (struct rx_ringbuf *q)
1416 {
1417   q->out_index++;
1418   if (q->out_index >= q->num_elem)
1419       q->out_index = 0;
1420   return (q->out_index);
1421 }
1422
1423 /*
1424  * Return the queue's next 'in_index' (head).
1425  * Check for wraps.
1426  */
1427 static int pktq_in_index (struct rx_ringbuf *q)
1428 {
1429   volatile int index = q->in_index + 1;
1430
1431   if (index >= q->num_elem)
1432       index = 0;
1433   return (index);
1434 }
1435
1436 /*
1437  * Return the queue's head-buffer.
1438  */
1439 static struct rx_elem *pktq_in_elem (struct rx_ringbuf *q)
1440 {
1441   return (struct rx_elem*) (q->buf_start + (q->elem_size * q->in_index));
1442 }
1443
1444 /*
1445  * Return the queue's tail-buffer.
1446  */
1447 static struct rx_elem *pktq_out_elem (struct rx_ringbuf *q)
1448 {
1449   return (struct rx_elem*) (q->buf_start + (q->elem_size * q->out_index));
1450 }
1451
1452 /*
1453  * Clear the queue ring-buffer by setting head=tail.
1454  */
1455 static void pktq_clear (struct rx_ringbuf *q)
1456 {
1457   q->in_index = q->out_index;
1458 }
1459
1460 /*
1461  * Symbols that must be linkable for "gcc -O0"
1462  */
1463 #undef __IOPORT_H
1464 #undef __DMA_H
1465
1466 #define extern
1467 #define __inline__
1468
1469 #include "msdos/pm_drvr/ioport.h"
1470 #include "msdos/pm_drvr/dma.h"
1471
1472 #endif /* USE_32BIT_DRIVERS */
1473