xref: /openbmc/qemu/pc-bios/s390-ccw/netmain.c (revision e6e03dcf)
1 /*
2  * S390 virtio-ccw network boot loading program
3  *
4  * Copyright 2017 Thomas Huth, Red Hat Inc.
5  *
6  * Based on the S390 virtio-ccw loading program (main.c)
7  * Copyright (c) 2013 Alexander Graf <agraf@suse.de>
8  *
9  * And based on the network loading code from SLOF (netload.c)
10  * Copyright (c) 2004, 2008 IBM Corporation
11  *
12  * This code is free software; you can redistribute it and/or modify it
13  * under the terms of the GNU General Public License as published by the
14  * Free Software Foundation; either version 2 of the License, or (at your
15  * option) any later version.
16  */
17 
18 #include <stdint.h>
19 #include <stdbool.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <unistd.h>
24 
25 #include <tftp.h>
26 #include <ethernet.h>
27 #include <dhcp.h>
28 #include <dhcpv6.h>
29 #include <ipv4.h>
30 #include <ipv6.h>
31 #include <dns.h>
32 #include <time.h>
33 #include <pxelinux.h>
34 
35 #include "s390-ccw.h"
36 #include "cio.h"
37 #include "virtio.h"
38 
39 #define DEFAULT_BOOT_RETRIES 10
40 #define DEFAULT_TFTP_RETRIES 20
41 
42 extern char _start[];
43 
44 #define KERNEL_ADDR             ((void *)0L)
45 #define KERNEL_MAX_SIZE         ((long)_start)
46 #define ARCH_COMMAND_LINE_SIZE  896              /* Taken from Linux kernel */
47 
48 /* STSI 3.2.2 offset of first vmdb + offset of uuid inside vmdb */
49 #define STSI322_VMDB_UUID_OFFSET ((8 + 12) * 4)
50 
51 char stack[PAGE_SIZE * 8] __attribute__((aligned(PAGE_SIZE)));
52 IplParameterBlock iplb __attribute__((aligned(PAGE_SIZE)));
53 static char cfgbuf[2048];
54 
55 static SubChannelId net_schid = { .one = 1 };
56 static uint8_t mac[6];
57 static uint64_t dest_timer;
58 
59 static uint64_t get_timer_ms(void)
60 {
61     uint64_t clk;
62 
63     asm volatile(" stck %0 " : : "Q"(clk) : "memory");
64 
65     /* Bit 51 is incremented each microsecond */
66     return (clk >> (63 - 51)) / 1000;
67 }
68 
69 void set_timer(int val)
70 {
71     dest_timer = get_timer_ms() + val;
72 }
73 
74 int get_timer(void)
75 {
76     return dest_timer - get_timer_ms();
77 }
78 
79 int get_sec_ticks(void)
80 {
81     return 1000;    /* number of ticks in 1 second */
82 }
83 
84 /**
85  * Obtain IP and configuration info from DHCP server (either IPv4 or IPv6).
86  * @param  fn_ip     contains the following configuration information:
87  *                   client MAC, client IP, TFTP-server MAC, TFTP-server IP,
88  *                   boot file name
89  * @param  retries   Number of DHCP attempts
90  * @return           0 : IP and configuration info obtained;
91  *                   non-0 : error condition occurred.
92  */
93 static int dhcp(struct filename_ip *fn_ip, int retries)
94 {
95     int i = retries + 1;
96     int rc = -1;
97 
98     printf("  Requesting information via DHCP:     ");
99 
100     dhcpv4_generate_transaction_id();
101     dhcpv6_generate_transaction_id();
102 
103     do {
104         printf("\b\b\b%03d", i - 1);
105         if (!--i) {
106             printf("\nGiving up after %d DHCP requests\n", retries);
107             return -1;
108         }
109         fn_ip->ip_version = 4;
110         rc = dhcpv4(NULL, fn_ip);
111         if (rc == -1) {
112             fn_ip->ip_version = 6;
113             set_ipv6_address(fn_ip->fd, 0);
114             rc = dhcpv6(NULL, fn_ip);
115             if (rc == 0) {
116                 memcpy(&fn_ip->own_ip6, get_ipv6_address(), 16);
117                 break;
118             }
119         }
120         if (rc != -1) {    /* either success or non-dhcp failure */
121             break;
122         }
123     } while (1);
124     printf("\b\b\b\bdone\n");
125 
126     return rc;
127 }
128 
129 /**
130  * Seed the random number generator with our mac and current timestamp
131  */
132 static void seed_rng(uint8_t mac[])
133 {
134     uint64_t seed;
135 
136     asm volatile(" stck %0 " : : "Q"(seed) : "memory");
137     seed ^= (mac[2] << 24) | (mac[3] << 16) | (mac[4] << 8) | mac[5];
138     srand(seed);
139 }
140 
141 static int tftp_load(filename_ip_t *fnip, void *buffer, int len)
142 {
143     tftp_err_t tftp_err;
144     int rc;
145 
146     rc = tftp(fnip, buffer, len, DEFAULT_TFTP_RETRIES, &tftp_err);
147 
148     if (rc < 0) {
149         /* Make sure that error messages are put into a new line */
150         printf("\n  ");
151     }
152 
153     if (rc > 1024) {
154         printf("  TFTP: Received %s (%d KBytes)\n", fnip->filename, rc / 1024);
155     } else if (rc > 0) {
156         printf("  TFTP: Received %s (%d Bytes)\n", fnip->filename, rc);
157     } else {
158         const char *errstr = NULL;
159         int ecode;
160         tftp_get_error_info(fnip, &tftp_err, rc, &errstr, &ecode);
161         printf("TFTP error: %s\n", errstr ? errstr : "unknown error");
162     }
163 
164     return rc;
165 }
166 
167 static int net_init(filename_ip_t *fn_ip)
168 {
169     int rc;
170 
171     memset(fn_ip, 0, sizeof(filename_ip_t));
172 
173     rc = virtio_net_init(mac);
174     if (rc < 0) {
175         puts("Could not initialize network device");
176         return -101;
177     }
178     fn_ip->fd = rc;
179 
180     printf("  Using MAC address: %02x:%02x:%02x:%02x:%02x:%02x\n",
181            mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
182 
183     set_mac_address(mac);    /* init ethernet layer */
184     seed_rng(mac);
185 
186     rc = dhcp(fn_ip, DEFAULT_BOOT_RETRIES);
187     if (rc >= 0) {
188         if (fn_ip->ip_version == 4) {
189             set_ipv4_address(fn_ip->own_ip);
190         }
191     } else {
192         puts("Could not get IP address");
193         return -101;
194     }
195 
196     if (fn_ip->ip_version == 4) {
197         printf("  Using IPv4 address: %d.%d.%d.%d\n",
198               (fn_ip->own_ip >> 24) & 0xFF, (fn_ip->own_ip >> 16) & 0xFF,
199               (fn_ip->own_ip >>  8) & 0xFF, fn_ip->own_ip & 0xFF);
200     } else if (fn_ip->ip_version == 6) {
201         char ip6_str[40];
202         ipv6_to_str(fn_ip->own_ip6.addr, ip6_str);
203         printf("  Using IPv6 address: %s\n", ip6_str);
204     }
205 
206     if (rc == -2) {
207         printf("ARP request to TFTP server (%d.%d.%d.%d) failed\n",
208                (fn_ip->server_ip >> 24) & 0xFF, (fn_ip->server_ip >> 16) & 0xFF,
209                (fn_ip->server_ip >>  8) & 0xFF, fn_ip->server_ip & 0xFF);
210         return -102;
211     }
212     if (rc == -4 || rc == -3) {
213         puts("Can't obtain TFTP server IP address");
214         return -107;
215     }
216 
217     printf("  Using TFTP server: ");
218     if (fn_ip->ip_version == 4) {
219         printf("%d.%d.%d.%d\n",
220                (fn_ip->server_ip >> 24) & 0xFF, (fn_ip->server_ip >> 16) & 0xFF,
221                (fn_ip->server_ip >>  8) & 0xFF, fn_ip->server_ip & 0xFF);
222     } else if (fn_ip->ip_version == 6) {
223         char ip6_str[40];
224         ipv6_to_str(fn_ip->server_ip6.addr, ip6_str);
225         printf("%s\n", ip6_str);
226     }
227 
228     if (strlen(fn_ip->filename) > 0) {
229         printf("  Bootfile name: '%s'\n", fn_ip->filename);
230     }
231 
232     return rc;
233 }
234 
235 static void net_release(filename_ip_t *fn_ip)
236 {
237     if (fn_ip->ip_version == 4) {
238         dhcp_send_release(fn_ip->fd);
239     }
240 }
241 
242 /**
243  * Retrieve the Universally Unique Identifier of the VM.
244  * @return UUID string, or NULL in case of errors
245  */
246 static const char *get_uuid(void)
247 {
248     register int r0 asm("0");
249     register int r1 asm("1");
250     uint8_t *mem, *buf, uuid[16];
251     int i, cc, chk = 0;
252     static char uuid_str[37];
253 
254     mem = malloc(2 * PAGE_SIZE);
255     if (!mem) {
256         puts("Out of memory ... can not get UUID.");
257         return NULL;
258     }
259     buf = (uint8_t *)(((uint64_t)mem + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1));
260     memset(buf, 0, PAGE_SIZE);
261 
262     /* Get SYSIB 3.2.2 */
263     r0 = (3 << 28) | 2;
264     r1 = 2;
265     asm volatile(" stsi 0(%[addr])\n"
266                  " ipm  %[cc]\n"
267                  " srl  %[cc],28\n"
268                  : [cc] "=d" (cc)
269                  : "d" (r0), "d" (r1), [addr] "a" (buf)
270                  : "cc", "memory");
271     if (cc) {
272         free(mem);
273         return NULL;
274     }
275 
276     for (i = 0; i < 16; i++) {
277         uuid[i] = buf[STSI322_VMDB_UUID_OFFSET + i];
278         chk |= uuid[i];
279     }
280     free(mem);
281     if (!chk) {
282         return NULL;
283     }
284 
285     sprintf(uuid_str, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
286             "%02x%02x%02x%02x%02x%02x", uuid[0], uuid[1], uuid[2], uuid[3],
287             uuid[4], uuid[5], uuid[6], uuid[7], uuid[8], uuid[9], uuid[10],
288             uuid[11], uuid[12], uuid[13], uuid[14], uuid[15]);
289 
290     return uuid_str;
291 }
292 
293 /**
294  * Load a kernel with initrd (i.e. with the information that we've got from
295  * a pxelinux.cfg config file)
296  */
297 static int load_kernel_with_initrd(filename_ip_t *fn_ip,
298                                    struct pl_cfg_entry *entry)
299 {
300     int rc;
301 
302     printf("Loading pxelinux.cfg entry '%s'\n", entry->label);
303 
304     if (!entry->kernel) {
305         printf("Kernel entry is missing!\n");
306         return -1;
307     }
308 
309     strncpy(fn_ip->filename, entry->kernel, sizeof(fn_ip->filename));
310     rc = tftp_load(fn_ip, KERNEL_ADDR, KERNEL_MAX_SIZE);
311     if (rc < 0) {
312         return rc;
313     }
314 
315     if (entry->initrd) {
316         uint64_t iaddr = (rc + 0xfff) & ~0xfffUL;
317 
318         strncpy(fn_ip->filename, entry->initrd, sizeof(fn_ip->filename));
319         rc = tftp_load(fn_ip, (void *)iaddr, KERNEL_MAX_SIZE - iaddr);
320         if (rc < 0) {
321             return rc;
322         }
323         /* Patch location and size: */
324         *(uint64_t *)0x10408 = iaddr;
325         *(uint64_t *)0x10410 = rc;
326         rc += iaddr;
327     }
328 
329     if (entry->append) {
330         strncpy((char *)0x10480, entry->append, ARCH_COMMAND_LINE_SIZE);
331     }
332 
333     return rc;
334 }
335 
336 #define MAX_PXELINUX_ENTRIES 16
337 
338 static int net_try_pxelinux_cfg(filename_ip_t *fn_ip)
339 {
340     struct pl_cfg_entry entries[MAX_PXELINUX_ENTRIES];
341     int num_ent, def_ent = 0;
342 
343     num_ent = pxelinux_load_parse_cfg(fn_ip, mac, get_uuid(),
344                                       DEFAULT_TFTP_RETRIES,
345                                       cfgbuf, sizeof(cfgbuf),
346                                       entries, MAX_PXELINUX_ENTRIES, &def_ent);
347     if (num_ent > 0) {
348         return load_kernel_with_initrd(fn_ip, &entries[def_ent]);
349     }
350 
351     return -1;
352 }
353 
354 /**
355  * Load via information from a .INS file (which can be found on CD-ROMs
356  * for example)
357  */
358 static int handle_ins_cfg(filename_ip_t *fn_ip, char *cfg, int cfgsize)
359 {
360     char *ptr;
361     int rc = -1, llen;
362     void *destaddr;
363     char *insbuf = cfg;
364 
365     ptr = strchr(insbuf, '\n');
366     if (!ptr) {
367         puts("Does not seem to be a valid .INS file");
368         return -1;
369     }
370 
371     *ptr = 0;
372     printf("\nParsing .INS file:\n %s\n", &insbuf[2]);
373 
374     insbuf = ptr + 1;
375     while (*insbuf && insbuf < cfg + cfgsize) {
376         ptr = strchr(insbuf, '\n');
377         if (ptr) {
378             *ptr = 0;
379         }
380         llen = strlen(insbuf);
381         if (!llen) {
382             insbuf = ptr + 1;
383             continue;
384         }
385         ptr = strchr(insbuf, ' ');
386         if (!ptr) {
387             puts("Missing space separator in .INS file");
388             return -1;
389         }
390         *ptr = 0;
391         strncpy(fn_ip->filename, insbuf, sizeof(fn_ip->filename));
392         destaddr = (char *)atol(ptr + 1);
393         rc = tftp_load(fn_ip, destaddr, (long)_start - (long)destaddr);
394         if (rc <= 0) {
395             break;
396         }
397         insbuf += llen + 1;
398     }
399 
400     return rc;
401 }
402 
403 static int net_try_direct_tftp_load(filename_ip_t *fn_ip)
404 {
405     int rc;
406     void *loadaddr = (void *)0x2000;  /* Load right after the low-core */
407 
408     rc = tftp_load(fn_ip, loadaddr, KERNEL_MAX_SIZE - (long)loadaddr);
409     if (rc < 0) {
410         return rc;
411     } else if (rc < 8) {
412         printf("'%s' is too small (%i bytes only).\n", fn_ip->filename, rc);
413         return -1;
414     }
415 
416     /* Check whether it is a configuration file instead of a kernel */
417     if (rc < sizeof(cfgbuf) - 1) {
418         memcpy(cfgbuf, loadaddr, rc);
419         cfgbuf[rc] = 0;    /* Make sure that it is NUL-terminated */
420         if (!strncmp("* ", cfgbuf, 2)) {
421             return handle_ins_cfg(fn_ip, cfgbuf, rc);
422         }
423         /*
424          * pxelinux.cfg support via bootfile name is just here for developers'
425          * convenience (it eases testing with the built-in DHCP server of QEMU
426          * that does not support RFC 5071). The official way to configure a
427          * pxelinux.cfg file name is to use DHCP options 209 and 210 instead.
428          * So only use the pxelinux.cfg parser here for files that start with
429          * a magic comment string.
430          */
431         if (!strncasecmp("# pxelinux", cfgbuf, 10)) {
432             struct pl_cfg_entry entries[MAX_PXELINUX_ENTRIES];
433             int num_ent, def_ent = 0;
434 
435             num_ent = pxelinux_parse_cfg(cfgbuf, sizeof(cfgbuf), entries,
436                                          MAX_PXELINUX_ENTRIES, &def_ent);
437             if (num_ent <= 0) {
438                 return -1;
439             }
440             return load_kernel_with_initrd(fn_ip, &entries[def_ent]);
441         }
442     }
443 
444     /* Move kernel to right location */
445     memmove(KERNEL_ADDR, loadaddr, rc);
446 
447     return rc;
448 }
449 
450 void panic(const char *string)
451 {
452     sclp_print(string);
453     for (;;) {
454         disabled_wait();
455     }
456 }
457 
458 void write_subsystem_identification(void)
459 {
460     SubChannelId *schid = (SubChannelId *) 184;
461     uint32_t *zeroes = (uint32_t *) 188;
462 
463     *schid = net_schid;
464     *zeroes = 0;
465 }
466 
467 static bool find_net_dev(Schib *schib, int dev_no)
468 {
469     int i, r;
470 
471     for (i = 0; i < 0x10000; i++) {
472         net_schid.sch_no = i;
473         r = stsch_err(net_schid, schib);
474         if (r == 3 || r == -EIO) {
475             break;
476         }
477         if (!schib->pmcw.dnv) {
478             continue;
479         }
480         enable_subchannel(net_schid);
481         if (!virtio_is_supported(net_schid)) {
482             continue;
483         }
484         if (virtio_get_device_type() != VIRTIO_ID_NET) {
485             continue;
486         }
487         if (dev_no < 0 || schib->pmcw.dev == dev_no) {
488             return true;
489         }
490     }
491 
492     return false;
493 }
494 
495 static void virtio_setup(void)
496 {
497     Schib schib;
498     int ssid;
499     bool found = false;
500     uint16_t dev_no;
501 
502     /*
503      * We unconditionally enable mss support. In every sane configuration,
504      * this will succeed; and even if it doesn't, stsch_err() can deal
505      * with the consequences.
506      */
507     enable_mss_facility();
508 
509     if (store_iplb(&iplb)) {
510         IPL_assert(iplb.pbt == S390_IPL_TYPE_CCW, "IPL_TYPE_CCW expected");
511         dev_no = iplb.ccw.devno;
512         debug_print_int("device no. ", dev_no);
513         net_schid.ssid = iplb.ccw.ssid & 0x3;
514         debug_print_int("ssid ", net_schid.ssid);
515         found = find_net_dev(&schib, dev_no);
516     } else {
517         for (ssid = 0; ssid < 0x3; ssid++) {
518             net_schid.ssid = ssid;
519             found = find_net_dev(&schib, -1);
520             if (found) {
521                 break;
522             }
523         }
524     }
525 
526     IPL_assert(found, "No virtio net device found");
527 }
528 
529 void main(void)
530 {
531     filename_ip_t fn_ip;
532     int rc, fnlen;
533 
534     sclp_setup();
535     sclp_print("Network boot starting...\n");
536 
537     virtio_setup();
538 
539     rc = net_init(&fn_ip);
540     if (rc) {
541         panic("Network initialization failed. Halting.\n");
542     }
543 
544     fnlen = strlen(fn_ip.filename);
545     if (fnlen > 0 && fn_ip.filename[fnlen - 1] != '/') {
546         rc = net_try_direct_tftp_load(&fn_ip);
547     }
548     if (rc <= 0) {
549         rc = net_try_pxelinux_cfg(&fn_ip);
550     }
551 
552     net_release(&fn_ip);
553 
554     if (rc > 0) {
555         sclp_print("Network loading done, starting kernel...\n");
556         jump_to_low_kernel();
557     }
558 
559     panic("Failed to load OS from network\n");
560 }
561