Compile up both the NFS and the TFTP version of the PXE loader and
[dragonfly.git] / sys / boot / i386 / libi386 / pxe.c
1 /*-
2  * Copyright (c) 2000 Alfred Perlstein <alfred@freebsd.org>
3  * Copyright (c) 2000 Paul Saab <ps@freebsd.org>
4  * Copyright (c) 2000 John Baldwin <jhb@freebsd.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD: src/sys/boot/i386/libi386/pxe.c,v 1.20 2003/08/25 23:28:31 obrien Exp $
29  * $DragonFly: src/sys/boot/i386/libi386/Attic/pxe.c,v 1.7 2005/09/03 23:52:47 dillon Exp $
30  */
31
32 #include <sys/param.h>
33 #include <stand.h>
34 #include <string.h>
35 #include <stdarg.h>
36
37 #include <netinet/in_systm.h>
38 #include <netinet/in.h>
39 #include <netinet/udp.h>
40
41 #include <net.h>
42 #include <netif.h>
43 #include <nfsv2.h>
44 #include <iodesc.h>
45
46 #include <bootp.h>
47 #include <bootstrap.h>
48 #include "btxv86.h"
49 #include "pxe.h"
50
51 /*
52  * Allocate the PXE buffers statically instead of sticking grimy fingers into
53  * BTX's private data area.  The scratch buffer is used to send information to
54  * the PXE BIOS, and the data buffer is used to receive data from the PXE BIOS.
55  */
56 #define PXE_BUFFER_SIZE         0x2000
57 #define PXE_TFTP_BUFFER_SIZE    512
58 static char     scratch_buffer[PXE_BUFFER_SIZE];
59 static char     data_buffer[PXE_BUFFER_SIZE];
60
61 static pxenv_t  *pxenv_p = NULL;        /* PXENV+ */
62 static pxe_t    *pxe_p   = NULL;        /* !PXE */
63 static BOOTPLAYER       bootplayer;     /* PXE Cached information. */
64
65 static int      pxe_debug = 0;
66 static int      pxe_sock = -1;
67 static int      pxe_opens = 0;
68
69 void            pxe_enable(void *pxeinfo);
70 static void     (*pxe_call)(int func);
71 static void     pxenv_call(int func);
72 static void     bangpxe_call(int func);
73
74 static int      pxe_init(void);
75 static int      pxe_strategy(void *devdata, int flag, daddr_t dblk,
76                              size_t size, char *buf, size_t *rsize);
77 static int      pxe_open(struct open_file *f, ...);
78 static int      pxe_close(struct open_file *f);
79 static void     pxe_print(int verbose);
80 static void     pxe_cleanup(void);
81 static void     pxe_setnfshandle(char *rootpath);
82
83 static void     pxe_perror(int error);
84 static int      pxe_netif_match(struct netif *nif, void *machdep_hint);
85 static int      pxe_netif_probe(struct netif *nif, void *machdep_hint);
86 static void     pxe_netif_init(struct iodesc *desc, void *machdep_hint);
87 static int      pxe_netif_get(struct iodesc *desc, void *pkt, size_t len,
88                               time_t timeout);
89 static int      pxe_netif_put(struct iodesc *desc, void *pkt, size_t len);
90 static void     pxe_netif_end(struct netif *nif);
91
92 extern struct netif_stats       pxe_st[];
93 extern u_int16_t                __bangpxeseg;
94 extern u_int16_t                __bangpxeoff;
95 extern void                     __bangpxeentry(void);
96 extern u_int16_t                __pxenvseg;
97 extern u_int16_t                __pxenvoff;
98 extern void                     __pxenventry(void);
99
100 struct netif_dif pxe_ifs[] = {
101 /*      dif_unit        dif_nsel        dif_stats       dif_private     */
102         {0,             1,              &pxe_st[0],     0}
103 };
104
105 struct netif_stats pxe_st[NENTS(pxe_ifs)];
106
107 struct netif_driver pxenetif = {
108         "pxenet",
109         pxe_netif_match,
110         pxe_netif_probe,
111         pxe_netif_init,
112         pxe_netif_get,
113         pxe_netif_put,
114         pxe_netif_end,
115         pxe_ifs,
116         NENTS(pxe_ifs)
117 };
118
119 struct netif_driver *netif_drivers[] = {
120         &pxenetif,
121         NULL
122 };
123
124 struct devsw pxedisk = {
125         "pxe", 
126         DEVT_NET,
127         pxe_init,
128         pxe_strategy, 
129         pxe_open, 
130         pxe_close, 
131         noioctl,
132         pxe_print,
133         pxe_cleanup
134 };
135
136 /*
137  * This function is called by the loader to enable PXE support if we
138  * are booted by PXE.  The passed in pointer is a pointer to the
139  * PXENV+ structure.
140  */
141 void
142 pxe_enable(void *pxeinfo)
143 {
144         pxenv_p  = (pxenv_t *)pxeinfo;
145         pxe_p    = (pxe_t *)PTOV(pxenv_p->PXEPtr.segment * 16 +
146                                  pxenv_p->PXEPtr.offset);
147         pxe_call = NULL;
148 }
149
150 /* 
151  * return true if pxe structures are found/initialized,
152  * also figures out our IP information via the pxe cached info struct 
153  */
154 static int
155 pxe_init(void)
156 {
157         t_PXENV_GET_CACHED_INFO *gci_p;
158         int     counter;
159         uint8_t checksum;
160         uint8_t *checkptr;
161         
162         if(pxenv_p == NULL)
163                 return (0);
164
165         /*  look for "PXENV+" */
166         if (bcmp((void *)pxenv_p->Signature, S_SIZE("PXENV+"))) {
167                 pxenv_p = NULL;
168                 return (0);
169         }
170
171         /* make sure the size is something we can handle */
172         if (pxenv_p->Length > sizeof(*pxenv_p)) {
173                 printf("PXENV+ structure too large, ignoring\n");
174                 pxenv_p = NULL;
175                 return (0);
176         }
177             
178         /* 
179          * do byte checksum:
180          * add up each byte in the structure, the total should be 0
181          */
182         checksum = 0;   
183         checkptr = (uint8_t *) pxenv_p;
184         for (counter = 0; counter < pxenv_p->Length; counter++)
185                 checksum += *checkptr++;
186         if (checksum != 0) {
187                 printf("PXENV+ structure failed checksum, ignoring\n");
188                 pxenv_p = NULL;
189                 return (0);
190         }
191
192         
193         /*
194          * PXENV+ passed, so use that if !PXE is not available or
195          * the checksum fails.
196          */
197         pxe_call = pxenv_call;
198         if (pxenv_p->Version >= 0x0200) {
199                 for (;;) {
200                         if (bcmp((void *)pxe_p->Signature, S_SIZE("!PXE"))) {
201                                 pxe_p = NULL;
202                                 break;
203                         }
204                         checksum = 0;
205                         checkptr = (uint8_t *)pxe_p;
206                         for (counter = 0; counter < pxe_p->StructLength;
207                              counter++)
208                                 checksum += *checkptr++;
209                         if (checksum != 0) {
210                                 pxe_p = NULL;
211                                 break;
212                         }
213                         pxe_call = bangpxe_call;
214                         break;
215                 }
216         }
217         
218         printf("\nPXE version %d.%d, real mode entry point ",
219                (uint8_t) (pxenv_p->Version >> 8),
220                (uint8_t) (pxenv_p->Version & 0xFF));
221         if (pxe_call == bangpxe_call)
222                 printf("@%04x:%04x\n",
223                        pxe_p->EntryPointSP.segment,
224                        pxe_p->EntryPointSP.offset);
225         else
226                 printf("@%04x:%04x\n",
227                        pxenv_p->RMEntry.segment, pxenv_p->RMEntry.offset);
228
229         gci_p = (t_PXENV_GET_CACHED_INFO *) scratch_buffer;
230         bzero(gci_p, sizeof(*gci_p));
231         gci_p->PacketType =  PXENV_PACKET_TYPE_BINL_REPLY;
232         pxe_call(PXENV_GET_CACHED_INFO);
233         if (gci_p->Status != 0) {
234                 pxe_perror(gci_p->Status);
235                 pxe_p = NULL;
236                 return (0);
237         }
238         bcopy(PTOV((gci_p->Buffer.segment << 4) + gci_p->Buffer.offset),
239               &bootplayer, gci_p->BufferSize);
240         return (1);
241 }
242
243
244 static int
245 pxe_strategy(void *devdata, int flag, daddr_t dblk, size_t size,
246                 char *buf, size_t *rsize)
247 {
248         return (EIO);
249 }
250
251 static int
252 pxe_open(struct open_file *f, ...)
253 {
254     va_list args;
255     char *devname;              /* Device part of file name (or NULL). */
256     char temp[FNAME_SIZE];
257     int error = 0;
258     int i;
259         
260     va_start(args, f);
261     devname = va_arg(args, char*);
262     va_end(args);
263
264     /* On first open, do netif open, mount, etc. */
265     if (pxe_opens == 0) {
266         /* Find network interface. */
267         if (pxe_sock < 0) {
268             pxe_sock = netif_open(devname);
269             if (pxe_sock < 0) {
270                 printf("pxe_open: netif_open() failed\n");
271                 return (ENXIO);
272             }
273             if (pxe_debug)
274                 printf("pxe_open: netif_open() succeeded\n");
275         }
276         if (rootip.s_addr == 0) {
277                 /*
278                  * Do a bootp/dhcp request to find out where our
279                  * NFS/TFTP server is.  Even if we dont get back
280                  * the proper information, fall back to the server
281                  * which brought us to life and a default rootpath.
282                  */
283                 bootp(pxe_sock, BOOTP_PXE);
284                 if (rootip.s_addr == 0)
285                         rootip.s_addr = bootplayer.sip;
286                 if (!rootpath[1])
287                         strcpy(rootpath, PXENFSROOTPATH);
288
289                 for (i = 0; rootpath[i] != '\0' && i < FNAME_SIZE; i++) {
290                         if (rootpath[i] == ':')
291                                 break;
292                 }
293                 if (i && i != FNAME_SIZE && rootpath[i] == ':') {
294                         rootpath[i++] = '\0';
295                         if (inet_addr(&rootpath[0]) != INADDR_NONE)
296                                 rootip.s_addr = inet_addr(&rootpath[0]);
297                         bcopy(&rootpath[i], &temp[0], strlen(&rootpath[i])+1);
298                         bcopy(&temp[0], &rootpath[0], strlen(&rootpath[i])+1);
299                 }
300                 printf("pxe_open: ip address : %s\n", inet_ntoa(myip));
301                 printf("pxe_open: ip netmask : %s\n", intoa(netmask));
302                 printf("pxe_open: nfs root mount: %s:%s\n", inet_ntoa(rootip), rootpath);
303                 printf("pxe_open: gateway ip:  %s\n", inet_ntoa(gateip));
304
305                 setenv("boot.netif.ip", inet_ntoa(myip), 1);
306                 setenv("boot.netif.netmask", intoa(netmask), 1);
307                 setenv("boot.netif.gateway", inet_ntoa(gateip), 1);
308                 if (bootplayer.Hardware == ETHER_TYPE) {
309                     sprintf(temp, "%6D", bootplayer.CAddr, ":");
310                     setenv("boot.netif.hwaddr", temp, 1);
311                 }
312                 setenv("boot.nfsroot.server", inet_ntoa(rootip), 1);
313                 setenv("boot.nfsroot.path", rootpath, 1);
314         }
315     }
316     pxe_opens++;
317     f->f_devdata = &pxe_sock;
318     return (error);
319 }
320
321 static int
322 pxe_close(struct open_file *f)
323 {
324
325 #ifdef  PXE_DEBUG
326     if (pxe_debug)
327         printf("pxe_close: opens=%d\n", pxe_opens);
328 #endif
329
330     /* On last close, do netif close, etc. */
331     f->f_devdata = NULL;
332     /* Extra close call? */
333     if (pxe_opens <= 0)
334         return (0);
335     pxe_opens--;
336     /* Not last close? */
337     if (pxe_opens > 0)
338         return(0);
339
340     /* get an NFS filehandle for our root filesystem */
341     pxe_setnfshandle(rootpath);
342
343     if (pxe_sock >= 0) {
344
345 #ifdef PXE_DEBUG
346         if (pxe_debug)
347             printf("pxe_close: calling netif_close()\n");
348 #endif
349         netif_close(pxe_sock);
350         pxe_sock = -1;
351     }
352     return (0);
353 }
354
355 static void
356 pxe_print(int verbose)
357 {
358         if (pxe_call != NULL) {
359                 if (*bootplayer.Sname == '\0') {
360                         printf("      "IP_STR":%s\n",
361                                IP_ARGS(htonl(bootplayer.sip)),
362                                bootplayer.bootfile);
363                 } else {
364                         printf("      %s:%s\n", bootplayer.Sname,
365                                bootplayer.bootfile);
366                 }
367         }
368
369         return;
370 }
371
372 static void
373 pxe_cleanup(void)
374 {
375 #ifdef PXE_DEBUG
376         t_PXENV_UNLOAD_STACK *unload_stack_p =
377             (t_PXENV_UNLOAD_STACK *)scratch_buffer;
378         t_PXENV_UNDI_SHUTDOWN *undi_shutdown_p =
379             (t_PXENV_UNDI_SHUTDOWN *)scratch_buffer;
380 #endif
381
382         if (pxe_call == NULL)
383                 return;
384
385         pxe_call(PXENV_UNDI_SHUTDOWN);
386
387 #ifdef PXE_DEBUG
388         if (pxe_debug && undi_shutdown_p->Status != 0)
389                 printf("pxe_cleanup: UNDI_SHUTDOWN failed %x\n",
390                        undi_shutdown_p->Status);
391 #endif
392
393         pxe_call(PXENV_UNLOAD_STACK);
394
395 #ifdef PXE_DEBUG        
396         if (pxe_debug && unload_stack_p->Status != 0)
397                 printf("pxe_cleanup: UNLOAD_STACK failed %x\n",
398                     unload_stack_p->Status);
399 #endif
400 }
401
402 void
403 pxe_perror(int err)
404 {
405         return;
406 }
407
408 /*
409  * Reach inside the libstand NFS code and dig out an NFS handle
410  * for the root filesystem.  If there is no nfs handle but a NFS root
411  * path was dynamically requested (not just as a default), then try
412  * to get the handle.  This occurs if we are compiled for TFTP operation
413  * but still want to pass an NFS root to the kernel.
414  */
415 struct nfs_iodesc {
416         struct  iodesc  *iodesc;
417         off_t   off;
418         u_char  fh[NFS_FHSIZE];
419         /* structure truncated here */
420 };
421 extern struct   nfs_iodesc nfs_root_node;
422
423 static void
424 pxe_setnfshandle(char *rootpath)
425 {
426         int     i;
427         u_char  *fh;
428         char    buf[2 * NFS_FHSIZE + 3], *cp;
429
430         fh = &nfs_root_node.fh[0];
431
432         /*
433          * If no file handle exists but a root path was dynamically
434          * requested, try to get a good handle.
435          */
436         for (i = 0; i < NFS_FHSIZE; ++i) {
437                 if (fh[i])
438                         break;
439         }
440         if (i != NFS_FHSIZE) {
441                 buf[0] = 'X';
442                 cp = &buf[1];
443                 for (i = 0; i < NFS_FHSIZE; i++, cp += 2)
444                         sprintf(cp, "%02x", fh[i]);
445                 sprintf(cp, "X");
446                 setenv("boot.nfsroot.nfshandle", buf, 1);
447         }
448 }
449
450 void
451 pxenv_call(int func)
452 {
453 #ifdef PXE_DEBUG
454         if (pxe_debug)
455                 printf("pxenv_call %x\n", func);
456 #endif
457         
458         bzero(&v86, sizeof(v86));
459         bzero(data_buffer, sizeof(data_buffer));
460
461         __pxenvseg = pxenv_p->RMEntry.segment;
462         __pxenvoff = pxenv_p->RMEntry.offset;
463         
464         v86.ctl  = V86_ADDR | V86_CALLF | V86_FLAGS;
465         v86.es   = VTOPSEG(scratch_buffer);
466         v86.edi  = VTOPOFF(scratch_buffer);
467         v86.addr = (VTOPSEG(__pxenventry) << 16) | VTOPOFF(__pxenventry);
468         v86.ebx  = func;
469         v86int();
470         v86.ctl  = V86_FLAGS;
471 }
472
473 void
474 bangpxe_call(int func)
475 {
476 #ifdef PXE_DEBUG
477         if (pxe_debug)
478                 printf("bangpxe_call %x\n", func);
479 #endif
480         
481         bzero(&v86, sizeof(v86));
482         bzero(data_buffer, sizeof(data_buffer));
483
484         __bangpxeseg = pxe_p->EntryPointSP.segment;
485         __bangpxeoff = pxe_p->EntryPointSP.offset;
486         
487         v86.ctl  = V86_ADDR | V86_CALLF | V86_FLAGS;
488         v86.edx  = VTOPSEG(scratch_buffer);
489         v86.eax  = VTOPOFF(scratch_buffer);
490         v86.addr = (VTOPSEG(__bangpxeentry) << 16) | VTOPOFF(__bangpxeentry);
491         v86.ebx  = func;
492         v86int();
493         v86.ctl  = V86_FLAGS;
494 }
495
496
497 time_t
498 getsecs()
499 {
500         time_t n = 0;
501         time(&n);
502         return n;
503 }
504
505 static int
506 pxe_netif_match(struct netif *nif, void *machdep_hint)
507 {
508         return 1;
509 }
510
511
512 static int
513 pxe_netif_probe(struct netif *nif, void *machdep_hint)
514 {
515         t_PXENV_UDP_OPEN *udpopen_p = (t_PXENV_UDP_OPEN *)scratch_buffer;
516
517         if (pxe_call == NULL)
518                 return -1;
519
520         bzero(udpopen_p, sizeof(*udpopen_p));
521         udpopen_p->src_ip = bootplayer.yip;
522         pxe_call(PXENV_UDP_OPEN);
523
524         if (udpopen_p->status != 0) {
525                 printf("pxe_netif_probe: failed %x\n", udpopen_p->status);
526                 return -1;
527         }
528         return 0;
529 }
530
531 static void
532 pxe_netif_end(struct netif *nif)
533 {
534         t_PXENV_UDP_CLOSE *udpclose_p = (t_PXENV_UDP_CLOSE *)scratch_buffer;
535         bzero(udpclose_p, sizeof(*udpclose_p));
536
537         pxe_call(PXENV_UDP_CLOSE);
538         if (udpclose_p->status != 0)
539                 printf("pxe_end failed %x\n", udpclose_p->status);
540 }
541
542 static void
543 pxe_netif_init(struct iodesc *desc, void *machdep_hint)
544 {
545         int i;
546         for (i = 0; i < 6; ++i)
547                 desc->myea[i] = bootplayer.CAddr[i];
548         desc->xid = bootplayer.ident;
549 }
550
551 static int
552 pxe_netif_get(struct iodesc *desc, void *pkt, size_t len, time_t timeout)
553 {
554         return len;
555 }
556
557 static int
558 pxe_netif_put(struct iodesc *desc, void *pkt, size_t len)
559 {
560         return len;
561 }
562
563 ssize_t
564 sendudp(struct iodesc *h, void *pkt, size_t len)
565 {
566         t_PXENV_UDP_WRITE *udpwrite_p = (t_PXENV_UDP_WRITE *)scratch_buffer;
567         bzero(udpwrite_p, sizeof(*udpwrite_p));
568         
569         udpwrite_p->ip             = h->destip.s_addr;
570         udpwrite_p->dst_port       = h->destport;
571         udpwrite_p->src_port       = h->myport;
572         udpwrite_p->buffer_size    = len;
573         udpwrite_p->buffer.segment = VTOPSEG(pkt);
574         udpwrite_p->buffer.offset  = VTOPOFF(pkt);
575
576         if (netmask == 0 || SAMENET(myip, h->destip, netmask))
577                 udpwrite_p->gw = 0;
578         else
579                 udpwrite_p->gw = gateip.s_addr;
580
581         pxe_call(PXENV_UDP_WRITE);
582
583 #if 0
584         /* XXX - I dont know why we need this. */
585         delay(1000);
586 #endif
587         if (udpwrite_p->status != 0) {
588                 /* XXX: This happens a lot.  It shouldn't. */
589                 if (udpwrite_p->status != 1)
590                         printf("sendudp failed %x\n", udpwrite_p->status);
591                 return -1;
592         }
593         return len;
594 }
595
596 ssize_t
597 readudp(struct iodesc *h, void *pkt, size_t len, time_t timeout)
598 {
599         t_PXENV_UDP_READ *udpread_p = (t_PXENV_UDP_READ *)scratch_buffer;
600         struct udphdr *uh = NULL;
601         
602         uh = (struct udphdr *) pkt - 1;
603         bzero(udpread_p, sizeof(*udpread_p));
604         
605         udpread_p->dest_ip        = h->myip.s_addr;
606         udpread_p->d_port         = h->myport;
607         udpread_p->buffer_size    = len;
608         udpread_p->buffer.segment = VTOPSEG(data_buffer);
609         udpread_p->buffer.offset  = VTOPOFF(data_buffer);
610
611         pxe_call(PXENV_UDP_READ);
612
613 #if 0
614         /* XXX - I dont know why we need this. */
615         delay(1000);
616 #endif
617         if (udpread_p->status != 0) {
618                 /* XXX: This happens a lot.  It shouldn't. */
619                 if (udpread_p->status != 1)
620                         printf("readudp failed %x\n", udpread_p->status);
621                 return -1;
622         }
623         bcopy(data_buffer, pkt, udpread_p->buffer_size);
624         uh->uh_sport = udpread_p->s_port;
625         return udpread_p->buffer_size;
626 }