xref: /qemu/pc-bios/s390-ccw/bootmap.c (revision facd91ac1af75b657fc80189fe9cb026bb1abdbc)
1 /*
2  * QEMU S390 bootmap interpreter
3  *
4  * Copyright (c) 2009 Alexander Graf <agraf@suse.de>
5  *
6  * This work is licensed under the terms of the GNU GPL, version 2 or (at
7  * your option) any later version. See the COPYING file in the top-level
8  * directory.
9  */
10 
11 #include <string.h>
12 #include <stdio.h>
13 #include "s390-ccw.h"
14 #include "s390-arch.h"
15 #include "bootmap.h"
16 #include "virtio.h"
17 #include "bswap.h"
18 
19 #ifdef DEBUG
20 /* #define DEBUG_FALLBACK */
21 #endif
22 
23 #ifdef DEBUG_FALLBACK
24 #define dputs(txt) \
25     do { printf("zipl: " txt); } while (0)
26 #else
27 #define dputs(fmt, ...) \
28     do { } while (0)
29 #endif
30 
31 /* Scratch space */
32 static uint8_t sec[MAX_SECTOR_SIZE*4] __attribute__((__aligned__(PAGE_SIZE)));
33 
34 const uint8_t el_torito_magic[] = "EL TORITO SPECIFICATION"
35                                   "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
36 
37 /*
38  * Match two CCWs located after PSW and eight filler bytes.
39  * From libmagic and arch/s390/kernel/head.S.
40  */
41 const uint8_t linux_s390_magic[] = "\x02\x00\x00\x18\x60\x00\x00\x50\x02\x00"
42                                    "\x00\x68\x60\x00\x00\x50\x40\x40\x40\x40"
43                                    "\x40\x40\x40\x40";
44 
45 static inline bool is_iso_vd_valid(IsoVolDesc *vd)
46 {
47     const uint8_t vol_desc_magic[] = "CD001";
48 
49     return !memcmp(&vd->ident[0], vol_desc_magic, 5) &&
50            vd->version == 0x1 &&
51            vd->type <= VOL_DESC_TYPE_PARTITION;
52 }
53 
54 /***********************************************************************
55  * IPL an ECKD DASD (CDL or LDL/CMS format)
56  */
57 
58 static unsigned char _bprs[8*1024]; /* guessed "max" ECKD sector size */
59 static const int max_bprs_entries = sizeof(_bprs) / sizeof(ExtEckdBlockPtr);
60 static uint8_t _s2[MAX_SECTOR_SIZE * 3] __attribute__((__aligned__(PAGE_SIZE)));
61 static void *s2_prev_blk = _s2;
62 static void *s2_cur_blk = _s2 + MAX_SECTOR_SIZE;
63 static void *s2_next_blk = _s2 + MAX_SECTOR_SIZE * 2;
64 
65 static inline void verify_boot_info(BootInfo *bip)
66 {
67     IPL_assert(magic_match(bip->magic, ZIPL_MAGIC), "No zIPL sig in BootInfo");
68     IPL_assert(bip->version == BOOT_INFO_VERSION, "Wrong zIPL version");
69     IPL_assert(bip->bp_type == BOOT_INFO_BP_TYPE_IPL, "DASD is not for IPL");
70     IPL_assert(bip->dev_type == BOOT_INFO_DEV_TYPE_ECKD, "DASD is not ECKD");
71     IPL_assert(bip->flags == BOOT_INFO_FLAGS_ARCH, "Not for this arch");
72     IPL_assert(block_size_ok(bip->bp.ipl.bm_ptr.eckd.bptr.size),
73                "Bad block size in zIPL section of the 1st record.");
74 }
75 
76 static void eckd_format_chs(ExtEckdBlockPtr *ptr,  bool ldipl,
77                             uint64_t *c,
78                             uint64_t *h,
79                             uint64_t *s)
80 {
81     if (ldipl) {
82         *c = ptr->ldptr.chs.cylinder;
83         *h = ptr->ldptr.chs.head;
84         *s = ptr->ldptr.chs.sector;
85     } else {
86         *c = ptr->bptr.chs.cylinder;
87         *h = ptr->bptr.chs.head;
88         *s = ptr->bptr.chs.sector;
89     }
90 }
91 
92 static block_number_t eckd_chs_to_block(uint64_t c, uint64_t h, uint64_t s)
93 {
94     const uint64_t sectors = virtio_get_sectors();
95     const uint64_t heads = virtio_get_heads();
96     const uint64_t cylinder = c + ((h & 0xfff0) << 12);
97     const uint64_t head = h & 0x000f;
98     const block_number_t block = sectors * heads * cylinder
99                                + sectors * head
100                                + s - 1; /* block nr starts with zero */
101     return block;
102 }
103 
104 static block_number_t eckd_block_num(EckdCHS *chs)
105 {
106     return eckd_chs_to_block(chs->cylinder, chs->head, chs->sector);
107 }
108 
109 static block_number_t gen_eckd_block_num(ExtEckdBlockPtr *ptr, bool ldipl)
110 {
111     uint64_t cyl, head, sec;
112     eckd_format_chs(ptr, ldipl, &cyl, &head, &sec);
113     return eckd_chs_to_block(cyl, head, sec);
114 }
115 
116 static bool eckd_valid_chs(uint64_t cyl, uint64_t head, uint64_t sector)
117 {
118     if (head >= virtio_get_heads()
119         || sector > virtio_get_sectors()
120         || sector <= 0) {
121         return false;
122     }
123 
124     if (!virtio_guessed_disk_nature() &&
125         eckd_chs_to_block(cyl, head, sector) >= virtio_get_blocks()) {
126         return false;
127     }
128 
129     return true;
130 }
131 
132 static bool eckd_valid_address(ExtEckdBlockPtr *ptr, bool ldipl)
133 {
134     uint64_t cyl, head, sec;
135     eckd_format_chs(ptr, ldipl, &cyl, &head, &sec);
136     return eckd_valid_chs(cyl, head, sec);
137 }
138 
139 static block_number_t load_eckd_segments(block_number_t blk, bool ldipl,
140                                          uint64_t *address)
141 {
142     block_number_t block_nr;
143     int j, rc, count;
144     BootMapPointer *bprs = (void *)_bprs;
145     bool more_data;
146 
147     memset(_bprs, FREE_SPACE_FILLER, sizeof(_bprs));
148     if (virtio_read(blk, bprs)) {
149         puts("BPRS read failed");
150         return ERROR_BLOCK_NR;
151     }
152 
153     do {
154         more_data = false;
155         for (j = 0;; j++) {
156             block_nr = gen_eckd_block_num(&bprs[j].xeckd, ldipl);
157             if (is_null_block_number(block_nr)) { /* end of chunk */
158                 return NULL_BLOCK_NR;
159             }
160 
161             /* we need the updated blockno for the next indirect entry
162              * in the chain, but don't want to advance address
163              */
164             if (j == (max_bprs_entries - 1)) {
165                 break;
166             }
167 
168             /* List directed pointer does not store block size */
169             if (!ldipl && !block_size_ok(bprs[j].xeckd.bptr.size)) {
170                 puts("Bad chunk block size");
171                 return ERROR_BLOCK_NR;
172             }
173 
174             if (!eckd_valid_address(&bprs[j].xeckd, ldipl)) {
175                 /*
176                  * If an invalid address is found during LD-IPL then break and
177                  * retry as CCW-IPL, otherwise abort on error
178                  */
179                 if (!ldipl) {
180                     puts("Bad chunk ECKD address");
181                     return ERROR_BLOCK_NR;
182                 }
183                 break;
184             }
185 
186             if (ldipl) {
187                 count = bprs[j].xeckd.ldptr.count;
188             } else {
189                 count = bprs[j].xeckd.bptr.count;
190             }
191 
192             if (count == 0 && unused_space(&bprs[j + 1],
193                 sizeof(EckdBlockPtr))) {
194                 /* This is a "continue" pointer.
195                  * This ptr should be the last one in the current
196                  * script section.
197                  * I.e. the next ptr must point to the unused memory area
198                  */
199                 memset(_bprs, FREE_SPACE_FILLER, sizeof(_bprs));
200                 if (virtio_read(block_nr, bprs)) {
201                     puts("BPRS continuation read failed");
202                     return ERROR_BLOCK_NR;
203                 }
204                 more_data = true;
205                 break;
206             }
207 
208             /* Load (count+1) blocks of code at (block_nr)
209              * to memory (address).
210              */
211             rc = virtio_read_many(block_nr, (void *)(*address), count + 1);
212             if (rc != 0) {
213                 puts("Code chunk read failed");
214                 return ERROR_BLOCK_NR;
215             }
216 
217             *address += (count + 1) * virtio_get_block_size();
218         }
219     } while (more_data);
220     return block_nr;
221 }
222 
223 static bool find_zipl_boot_menu_banner(int *offset)
224 {
225     int i;
226 
227     /* Menu banner starts with "zIPL" */
228     for (i = 0; i <= virtio_get_block_size() - 4; i++) {
229         if (magic_match(s2_cur_blk + i, ZIPL_MAGIC_EBCDIC)) {
230             *offset = i;
231             return true;
232         }
233     }
234 
235     return false;
236 }
237 
238 static int eckd_get_boot_menu_index(block_number_t s1b_block_nr)
239 {
240     block_number_t cur_block_nr;
241     block_number_t prev_block_nr = 0;
242     block_number_t next_block_nr = 0;
243     EckdStage1b *s1b = (void *)sec;
244     int banner_offset;
245     int i;
246 
247     /* Get Stage1b data */
248     memset(sec, FREE_SPACE_FILLER, sizeof(sec));
249     if (virtio_read(s1b_block_nr, s1b)) {
250         puts("Cannot read stage1b boot loader");
251         return -EIO;
252     }
253 
254     memset(_s2, FREE_SPACE_FILLER, sizeof(_s2));
255 
256     /* Get Stage2 data */
257     for (i = 0; i < STAGE2_BLK_CNT_MAX; i++) {
258         cur_block_nr = eckd_block_num(&s1b->seek[i].chs);
259 
260         if (!cur_block_nr || is_null_block_number(cur_block_nr)) {
261             break;
262         }
263 
264         if (virtio_read(cur_block_nr, s2_cur_blk)) {
265             puts("Cannot read stage2 boot loader");
266             return -EIO;
267         }
268 
269         if (find_zipl_boot_menu_banner(&banner_offset)) {
270             /*
271              * Load the adjacent blocks to account for the
272              * possibility of menu data spanning multiple blocks.
273              */
274             if (prev_block_nr) {
275                 if (virtio_read(prev_block_nr, s2_prev_blk)) {
276                     puts("Cannot read stage2 boot loader");
277                     return -EIO;
278                 }
279             }
280 
281             if (i + 1 < STAGE2_BLK_CNT_MAX) {
282                 next_block_nr = eckd_block_num(&s1b->seek[i + 1].chs);
283             }
284 
285             if (next_block_nr && !is_null_block_number(next_block_nr)) {
286                 if (virtio_read(next_block_nr, s2_next_blk)) {
287                     puts("Cannot read stage2 boot loader");
288                     return -EIO;
289                 }
290             }
291 
292             return menu_get_zipl_boot_index(s2_cur_blk + banner_offset);
293         }
294 
295         prev_block_nr = cur_block_nr;
296     }
297 
298     printf("No zipl boot menu data found. Booting default entry.");
299     return 0;
300 }
301 
302 static int run_eckd_boot_script(block_number_t bmt_block_nr,
303                                  block_number_t s1b_block_nr)
304 {
305     int i;
306     unsigned int loadparm = get_loadparm_index();
307     block_number_t block_nr;
308     uint64_t address;
309     BootMapTable *bmt = (void *)sec;
310     BootMapScript *bms = (void *)sec;
311     /* The S1B block number is NULL_BLOCK_NR if and only if it's an LD-IPL */
312     bool ldipl = (s1b_block_nr == NULL_BLOCK_NR);
313 
314     if (menu_is_enabled_zipl() && !ldipl) {
315         loadparm = eckd_get_boot_menu_index(s1b_block_nr);
316     }
317 
318     debug_print_int("loadparm", loadparm);
319     if (loadparm >= MAX_BOOT_ENTRIES) {
320         puts("loadparm value greater than max number of boot entries allowed");
321         return -EINVAL;
322     }
323 
324     memset(sec, FREE_SPACE_FILLER, sizeof(sec));
325     if (virtio_read(bmt_block_nr, sec)) {
326         puts("Cannot read Boot Map Table");
327         return -EIO;
328     }
329 
330     block_nr = gen_eckd_block_num(&bmt->entry[loadparm].xeckd, ldipl);
331     if (block_nr == NULL_BLOCK_NR) {
332         puts("Cannot find Boot Map Table Entry");
333         return -EIO;
334     }
335 
336     memset(sec, FREE_SPACE_FILLER, sizeof(sec));
337     if (virtio_read(block_nr, sec)) {
338         puts("Cannot read Boot Map Script");
339         return -EIO;
340     }
341 
342     for (i = 0; bms->entry[i].type == BOOT_SCRIPT_LOAD ||
343                 bms->entry[i].type == BOOT_SCRIPT_SIGNATURE; i++) {
344 
345         /* We don't support secure boot yet, so we skip signature entries */
346         if (bms->entry[i].type == BOOT_SCRIPT_SIGNATURE) {
347             continue;
348         }
349 
350         address = bms->entry[i].address.load_address;
351         block_nr = gen_eckd_block_num(&bms->entry[i].blkptr.xeckd, ldipl);
352 
353         do {
354             block_nr = load_eckd_segments(block_nr, ldipl, &address);
355             if (block_nr == ERROR_BLOCK_NR) {
356                 return ldipl ? 0 : -EIO;
357             }
358         } while (block_nr != NULL_BLOCK_NR);
359     }
360 
361     if (ldipl && bms->entry[i].type != BOOT_SCRIPT_EXEC) {
362         /* Abort LD-IPL and retry as CCW-IPL */
363         return 0;
364     }
365 
366     if (bms->entry[i].type != BOOT_SCRIPT_EXEC) {
367         puts("Unknown script entry type");
368         return -EINVAL;
369     }
370     write_reset_psw(bms->entry[i].address.load_address); /* no return */
371     jump_to_IPL_code(0); /* no return */
372     return -1;
373 }
374 
375 static int ipl_eckd_cdl(void)
376 {
377     XEckdMbr *mbr;
378     EckdCdlIpl2 *ipl2 = (void *)sec;
379     IplVolumeLabel *vlbl = (void *)sec;
380     block_number_t bmt_block_nr, s1b_block_nr;
381 
382     /* we have just read the block #0 and recognized it as "IPL1" */
383     puts("CDL");
384 
385     memset(sec, FREE_SPACE_FILLER, sizeof(sec));
386     if (virtio_read(1, ipl2)) {
387         puts("Cannot read IPL2 record at block 1");
388         return -EIO;
389     }
390 
391     mbr = &ipl2->mbr;
392     if (!magic_match(mbr, ZIPL_MAGIC)) {
393         puts("No zIPL section in IPL2 record.");
394         return 0;
395     }
396     if (!block_size_ok(mbr->blockptr.xeckd.bptr.size)) {
397         puts("Bad block size in zIPL section of IPL2 record.");
398         return 0;
399     }
400     if (mbr->dev_type != DEV_TYPE_ECKD) {
401         puts("Non-ECKD device type in zIPL section of IPL2 record.");
402         return 0;
403     }
404 
405     /* save pointer to Boot Map Table */
406     bmt_block_nr = eckd_block_num(&mbr->blockptr.xeckd.bptr.chs);
407 
408     /* save pointer to Stage1b Data */
409     s1b_block_nr = eckd_block_num(&ipl2->stage1.seek[0].chs);
410 
411     memset(sec, FREE_SPACE_FILLER, sizeof(sec));
412     if (virtio_read(2, vlbl)) {
413         puts("Cannot read Volume Label at block 2");
414         return -EIO;
415     }
416     if (!magic_match(vlbl->key, VOL1_MAGIC)) {
417         puts("Invalid magic of volume label block.");
418         return 0;
419     }
420     if (!magic_match(vlbl->f.key, VOL1_MAGIC)) {
421         puts("Invalid magic of volser block.");
422         return 0;
423     }
424     print_volser(vlbl->f.volser);
425 
426     return run_eckd_boot_script(bmt_block_nr, s1b_block_nr);
427 }
428 
429 static void print_eckd_ldl_msg(ECKD_IPL_mode_t mode)
430 {
431     LDL_VTOC *vlbl = (void *)sec; /* already read, 3rd block */
432     char msg[4] = { '?', '.', '\n', '\0' };
433 
434     printf((mode == ECKD_CMS) ? "CMS" : "LDL");
435     printf(" version ");
436     switch (vlbl->LDL_version) {
437     case LDL1_VERSION:
438         msg[0] = '1';
439         break;
440     case LDL2_VERSION:
441         msg[0] = '2';
442         break;
443     default:
444         msg[0] = ebc2asc[vlbl->LDL_version];
445         msg[1] = '?';
446         break;
447     }
448     printf("%s", msg);
449     print_volser(vlbl->volser);
450 }
451 
452 static int ipl_eckd_ldl(ECKD_IPL_mode_t mode)
453 {
454     block_number_t bmt_block_nr, s1b_block_nr;
455     EckdLdlIpl1 *ipl1 = (void *)sec;
456 
457     if (mode != ECKD_LDL_UNLABELED) {
458         print_eckd_ldl_msg(mode);
459     }
460 
461     /* DO NOT read BootMap pointer (only one, xECKD) at block #2 */
462 
463     memset(sec, FREE_SPACE_FILLER, sizeof(sec));
464     if (virtio_read(0, sec)) {
465         puts("Cannot read block 0 to grab boot info.");
466         return -EIO;
467     }
468     if (mode == ECKD_LDL_UNLABELED) {
469         if (!magic_match(ipl1->bip.magic, ZIPL_MAGIC)) {
470             return 0; /* not applicable layout */
471         }
472         puts("unlabeled LDL.");
473     }
474     verify_boot_info(&ipl1->bip);
475 
476     /* save pointer to Boot Map Table */
477     bmt_block_nr = eckd_block_num(&ipl1->bip.bp.ipl.bm_ptr.eckd.bptr.chs);
478 
479     /* save pointer to Stage1b Data */
480     s1b_block_nr = eckd_block_num(&ipl1->stage1.seek[0].chs);
481 
482     return run_eckd_boot_script(bmt_block_nr, s1b_block_nr);
483 }
484 
485 static block_number_t eckd_find_bmt(ExtEckdBlockPtr *ptr)
486 {
487     block_number_t blockno;
488     uint8_t tmp_sec[MAX_SECTOR_SIZE];
489     BootRecord *br;
490 
491     blockno = gen_eckd_block_num(ptr, 0);
492     if (virtio_read(blockno, tmp_sec)) {
493         puts("Cannot read boot record");
494         return ERROR_BLOCK_NR;
495     }
496     br = (BootRecord *)tmp_sec;
497     if (!magic_match(br->magic, ZIPL_MAGIC)) {
498         /* If the boot record is invalid, return and try CCW-IPL instead */
499         return NULL_BLOCK_NR;
500     }
501 
502     return gen_eckd_block_num(&br->pgt.xeckd, 1);
503 }
504 
505 static void print_eckd_msg(void)
506 {
507     char msg[] = "Using ECKD scheme (block size *****), ";
508     char *p = &msg[34], *q = &msg[30];
509     int n = virtio_get_block_size();
510 
511     /* Fill in the block size and show up the message */
512     if (n > 0 && n <= 99999) {
513         while (n) {
514             *p-- = '0' + (n % 10);
515             n /= 10;
516         }
517         while (p >= q) {
518             *p-- = ' ';
519         }
520     }
521     printf("%s", msg);
522 }
523 
524 static int ipl_eckd(void)
525 {
526     IplVolumeLabel *vlbl = (void *)sec;
527     LDL_VTOC *vtoc = (void *)sec;
528     block_number_t ldipl_bmt; /* Boot Map Table for List-Directed IPL */
529 
530     print_eckd_msg();
531 
532     /* Block 2 can contain either the CDL VOL1 label or the LDL VTOC */
533     memset(sec, FREE_SPACE_FILLER, sizeof(sec));
534     if (virtio_read(2, vlbl)) {
535         puts("Cannot read block 2");
536         return -EIO;
537     }
538 
539     /*
540      * First check for a list-directed-format pointer which would
541      * supersede the CCW pointer.
542      */
543     if (eckd_valid_address((ExtEckdBlockPtr *)&vlbl->f.br, 0)) {
544         ldipl_bmt = eckd_find_bmt((ExtEckdBlockPtr *)&vlbl->f.br);
545         switch (ldipl_bmt) {
546         case ERROR_BLOCK_NR:
547             return -EIO;
548         case NULL_BLOCK_NR:
549             break; /* Invalid BMT but the device may still boot with CCW-IPL */
550         default:
551             puts("List-Directed");
552             /*
553              * LD-IPL does not use the S1B bock, just make it NULL_BLOCK_NR.
554              * In some failure cases retry IPL before aborting.
555              */
556             if (run_eckd_boot_script(ldipl_bmt, NULL_BLOCK_NR)) {
557                 return -EIO;
558             }
559             /* Non-fatal error, retry as CCW-IPL */
560             printf("Retrying IPL ");
561             print_eckd_msg();
562         }
563         memset(sec, FREE_SPACE_FILLER, sizeof(sec));
564         if (virtio_read(2, vtoc)) {
565             puts("Cannot read block 2");
566             return -EIO;
567         }
568     }
569 
570     /* Not list-directed */
571     if (magic_match(vtoc->magic, VOL1_MAGIC)) {
572         if (ipl_eckd_cdl()) {
573             return -1;
574         }
575     }
576 
577     if (magic_match(vtoc->magic, CMS1_MAGIC)) {
578         return ipl_eckd_ldl(ECKD_CMS);
579     }
580     if (magic_match(vtoc->magic, LNX1_MAGIC)) {
581         return ipl_eckd_ldl(ECKD_LDL);
582     }
583 
584     if (ipl_eckd_ldl(ECKD_LDL_UNLABELED)) {
585         return -1;
586     }
587     /*
588      * Ok, it is not a LDL by any means.
589      * It still might be a CDL with zero record keys for IPL1 and IPL2
590      */
591     return ipl_eckd_cdl();
592 }
593 
594 /***********************************************************************
595  * IPL a SCSI disk
596  */
597 
598 static int zipl_load_segment(ComponentEntry *entry)
599 {
600     const int max_entries = (MAX_SECTOR_SIZE / sizeof(ScsiBlockPtr));
601     ScsiBlockPtr *bprs = (void *)sec;
602     const int bprs_size = sizeof(sec);
603     block_number_t blockno;
604     uint64_t address;
605     int i;
606     char err_msg[] = "zIPL failed to read BPRS at 0xZZZZZZZZZZZZZZZZ";
607     char *blk_no = &err_msg[30]; /* where to print blockno in (those ZZs) */
608 
609     blockno = entry->data.blockno;
610     address = entry->compdat.load_addr;
611 
612     debug_print_int("loading segment at block", blockno);
613     debug_print_int("addr", address);
614 
615     do {
616         memset(bprs, FREE_SPACE_FILLER, bprs_size);
617         fill_hex_val(blk_no, &blockno, sizeof(blockno));
618         if (virtio_read(blockno, bprs)) {
619             puts(err_msg);
620             return -EIO;
621         }
622 
623         for (i = 0;; i++) {
624             uint64_t *cur_desc = (void *)&bprs[i];
625 
626             blockno = bprs[i].blockno;
627             if (!blockno) {
628                 break;
629             }
630 
631             /* we need the updated blockno for the next indirect entry in the
632                chain, but don't want to advance address */
633             if (i == (max_entries - 1)) {
634                 break;
635             }
636 
637             if (bprs[i].blockct == 0 && unused_space(&bprs[i + 1],
638                 sizeof(ScsiBlockPtr))) {
639                 /* This is a "continue" pointer.
640                  * This ptr is the last one in the current script section.
641                  * I.e. the next ptr must point to the unused memory area.
642                  * The blockno is not zero, so the upper loop must continue
643                  * reading next section of BPRS.
644                  */
645                 break;
646             }
647             address = virtio_load_direct(cur_desc[0], cur_desc[1], 0,
648                                          (void *)address);
649             if (!address) {
650                 puts("zIPL load segment failed");
651                 return -EIO;
652             }
653         }
654     } while (blockno);
655 
656     return 0;
657 }
658 
659 /* Run a zipl program */
660 static int zipl_run(ScsiBlockPtr *pte)
661 {
662     ComponentHeader *header;
663     ComponentEntry *entry;
664     uint8_t tmp_sec[MAX_SECTOR_SIZE];
665 
666     if (virtio_read(pte->blockno, tmp_sec)) {
667         puts("Cannot read header");
668         return -EIO;
669     }
670     header = (ComponentHeader *)tmp_sec;
671 
672     if (!magic_match(tmp_sec, ZIPL_MAGIC)) {
673         puts("No zIPL magic in header");
674         return -EINVAL;
675     }
676     if (header->type != ZIPL_COMP_HEADER_IPL) {
677         puts("Bad header type");
678         return -EINVAL;
679     }
680 
681     dputs("start loading images\n");
682 
683     /* Load image(s) into RAM */
684     entry = (ComponentEntry *)(&header[1]);
685     while (entry->component_type == ZIPL_COMP_ENTRY_LOAD ||
686            entry->component_type == ZIPL_COMP_ENTRY_SIGNATURE) {
687 
688         /* We don't support secure boot yet, so we skip signature entries */
689         if (entry->component_type == ZIPL_COMP_ENTRY_SIGNATURE) {
690             entry++;
691             continue;
692         }
693 
694         if (zipl_load_segment(entry)) {
695             return -1;
696         }
697 
698         entry++;
699 
700         if ((uint8_t *)(&entry[1]) > (tmp_sec + MAX_SECTOR_SIZE)) {
701             puts("Wrong entry value");
702             return -EINVAL;
703         }
704     }
705 
706     if (entry->component_type != ZIPL_COMP_ENTRY_EXEC) {
707         puts("No EXEC entry");
708         return -EINVAL;
709     }
710 
711     /* should not return */
712     write_reset_psw(entry->compdat.load_psw);
713     jump_to_IPL_code(0);
714     return -1;
715 }
716 
717 static int ipl_scsi(void)
718 {
719     ScsiMbr *mbr = (void *)sec;
720     int program_table_entries = 0;
721     BootMapTable *prog_table = (void *)sec;
722     unsigned int loadparm = get_loadparm_index();
723     bool valid_entries[MAX_BOOT_ENTRIES] = {false};
724     size_t i;
725 
726     /* Grab the MBR */
727     memset(sec, FREE_SPACE_FILLER, sizeof(sec));
728     if (virtio_read(0, mbr)) {
729         puts("Cannot read block 0");
730         return -EIO;
731     }
732 
733     if (!magic_match(mbr->magic, ZIPL_MAGIC)) {
734         return 0;
735     }
736 
737     puts("Using SCSI scheme.");
738     debug_print_int("MBR Version", mbr->version_id);
739     IPL_check(mbr->version_id == 1,
740               "Unknown MBR layout version, assuming version 1");
741     debug_print_int("program table", mbr->pt.blockno);
742     if (!mbr->pt.blockno) {
743         puts("No Program Table");
744         return -EINVAL;
745     }
746 
747     /* Parse the program table */
748     if (virtio_read(mbr->pt.blockno, sec)) {
749         puts("Error reading Program Table");
750         return -EIO;
751     }
752     if (!magic_match(sec, ZIPL_MAGIC)) {
753         puts("No zIPL magic in Program Table");
754         return -EINVAL;
755     }
756 
757     for (i = 0; i < MAX_BOOT_ENTRIES; i++) {
758         if (prog_table->entry[i].scsi.blockno) {
759             valid_entries[i] = true;
760             program_table_entries++;
761         }
762     }
763 
764     debug_print_int("program table entries", program_table_entries);
765     if (program_table_entries == 0) {
766         puts("Empty Program Table");
767         return -EINVAL;
768     }
769 
770     if (menu_is_enabled_enum()) {
771         loadparm = menu_get_enum_boot_index(valid_entries);
772     }
773 
774     debug_print_int("loadparm", loadparm);
775     if (loadparm >= MAX_BOOT_ENTRIES) {
776         puts("loadparm value greater than max number of boot entries allowed");
777         return -EINVAL;
778     }
779 
780     return zipl_run(&prog_table->entry[loadparm].scsi);
781 }
782 
783 /***********************************************************************
784  * IPL El Torito ISO9660 image or DVD
785  */
786 
787 static bool is_iso_bc_entry_compatible(IsoBcSection *s)
788 {
789     uint8_t *magic_sec = (uint8_t *)(sec + ISO_SECTOR_SIZE);
790 
791     if (s->unused || !s->sector_count) {
792         return false;
793     }
794     if (virtio_read(bswap32(s->load_rba), magic_sec)) {
795         puts("Failed to read image sector 0");
796         return false;
797     }
798 
799     /* Checking bytes 8 - 32 for S390 Linux magic */
800     return !memcmp(magic_sec + 8, linux_s390_magic, 24);
801 }
802 
803 /* Location of the current sector of the directory */
804 static uint32_t sec_loc[ISO9660_MAX_DIR_DEPTH];
805 /* Offset in the current sector of the directory */
806 static uint32_t sec_offset[ISO9660_MAX_DIR_DEPTH];
807 /* Remained directory space in bytes */
808 static uint32_t dir_rem[ISO9660_MAX_DIR_DEPTH];
809 
810 static inline long iso_get_file_size(uint32_t load_rba)
811 {
812     IsoVolDesc *vd = (IsoVolDesc *)sec;
813     IsoDirHdr *cur_record = &vd->vd.primary.rootdir;
814     uint8_t *temp = sec + ISO_SECTOR_SIZE;
815     int level = 0;
816 
817     if (virtio_read(ISO_PRIMARY_VD_SECTOR, sec)) {
818         puts("Failed to read ISO primary descriptor");
819         return -EIO;
820     }
821 
822     sec_loc[0] = iso_733_to_u32(cur_record->ext_loc);
823     dir_rem[0] = 0;
824     sec_offset[0] = 0;
825 
826     while (level >= 0) {
827         if (sec_offset[level] > ISO_SECTOR_SIZE) {
828             puts("Directory tree structure violation");
829             return -EIO;
830         }
831 
832         cur_record = (IsoDirHdr *)(temp + sec_offset[level]);
833 
834         if (sec_offset[level] == 0) {
835             if (virtio_read(sec_loc[level], temp)) {
836                 puts("Failed to read ISO directory");
837                 return -EIO;
838             }
839             if (dir_rem[level] == 0) {
840                 /* Skip self and parent records */
841                 dir_rem[level] = iso_733_to_u32(cur_record->data_len) -
842                                  cur_record->dr_len;
843                 sec_offset[level] += cur_record->dr_len;
844 
845                 cur_record = (IsoDirHdr *)(temp + sec_offset[level]);
846                 dir_rem[level] -= cur_record->dr_len;
847                 sec_offset[level] += cur_record->dr_len;
848                 continue;
849             }
850         }
851 
852         if (!cur_record->dr_len || sec_offset[level] == ISO_SECTOR_SIZE) {
853             /* Zero-padding and/or the end of current sector */
854             dir_rem[level] -= ISO_SECTOR_SIZE - sec_offset[level];
855             sec_offset[level] = 0;
856             sec_loc[level]++;
857         } else {
858             /* The directory record is valid */
859             if (load_rba == iso_733_to_u32(cur_record->ext_loc)) {
860                 return iso_733_to_u32(cur_record->data_len);
861             }
862 
863             dir_rem[level] -= cur_record->dr_len;
864             sec_offset[level] += cur_record->dr_len;
865 
866             if (cur_record->file_flags & 0x2) {
867                 /* Subdirectory */
868                 if (level == ISO9660_MAX_DIR_DEPTH - 1) {
869                     puts("ISO-9660 directory depth limit exceeded");
870                 } else {
871                     level++;
872                     sec_loc[level] = iso_733_to_u32(cur_record->ext_loc);
873                     sec_offset[level] = 0;
874                     dir_rem[level] = 0;
875                     continue;
876                 }
877             }
878         }
879 
880         if (dir_rem[level] == 0) {
881             /* Nothing remaining */
882             level--;
883             if (virtio_read(sec_loc[level], temp)) {
884                 puts("Failed to read ISO directory");
885                 return -EIO;
886             }
887         }
888     }
889 
890     return 0;
891 }
892 
893 static void load_iso_bc_entry(IsoBcSection *load)
894 {
895     IsoBcSection s = *load;
896     /*
897      * According to spec, extent for each file
898      * is padded and ISO_SECTOR_SIZE bytes aligned
899      */
900     uint32_t blks_to_load = bswap16(s.sector_count) >> ET_SECTOR_SHIFT;
901     long real_size = iso_get_file_size(bswap32(s.load_rba));
902 
903     if (real_size > 0) {
904         /* Round up blocks to load */
905         blks_to_load = (real_size + ISO_SECTOR_SIZE - 1) / ISO_SECTOR_SIZE;
906         puts("ISO boot image size verified");
907     } else {
908         puts("ISO boot image size could not be verified");
909         if (real_size < 0) {
910             return;
911         }
912     }
913 
914     if (read_iso_boot_image(bswap32(s.load_rba),
915                         (void *)((uint64_t)bswap16(s.load_segment)),
916                         blks_to_load)) {
917         return;
918     }
919 
920     jump_to_low_kernel();
921 }
922 
923 static uint32_t find_iso_bc(void)
924 {
925     IsoVolDesc *vd = (IsoVolDesc *)sec;
926     uint32_t block_num = ISO_PRIMARY_VD_SECTOR;
927 
928     if (virtio_read_many(block_num++, sec, 1)) {
929         /* If primary vd cannot be read, there is no boot catalog */
930         return 0;
931     }
932 
933     while (is_iso_vd_valid(vd) && vd->type != VOL_DESC_TERMINATOR) {
934         if (vd->type == VOL_DESC_TYPE_BOOT) {
935             IsoVdElTorito *et = &vd->vd.boot;
936 
937             if (!memcmp(&et->el_torito[0], el_torito_magic, 32)) {
938                 return bswap32(et->bc_offset);
939             }
940         }
941         if (virtio_read(block_num++, sec)) {
942             puts("Failed to read ISO volume descriptor");
943             return 0;
944         }
945     }
946 
947     return 0;
948 }
949 
950 static IsoBcSection *find_iso_bc_entry(uint32_t offset)
951 {
952     IsoBcEntry *e = (IsoBcEntry *)sec;
953     int i;
954     unsigned int loadparm = get_loadparm_index();
955 
956     if (!offset) {
957         return NULL;
958     }
959 
960     if (virtio_read(offset, sec)) {
961         puts("Failed to read El Torito boot catalog");
962         return NULL;
963     }
964 
965     if (!is_iso_bc_valid(e)) {
966         /* The validation entry is mandatory */
967         return NULL;
968     }
969 
970     /*
971      * Each entry has 32 bytes size, so one sector cannot contain > 64 entries.
972      * We consider only boot catalogs with no more than 64 entries.
973      */
974     for (i = 1; i < ISO_BC_ENTRY_PER_SECTOR; i++) {
975         if (e[i].id == ISO_BC_BOOTABLE_SECTION) {
976             if (is_iso_bc_entry_compatible(&e[i].body.sect)) {
977                 if (loadparm <= 1) {
978                     /* found, default, or unspecified */
979                     return &e[i].body.sect;
980                 }
981                 loadparm--;
982             }
983         }
984     }
985 
986     return NULL;
987 }
988 
989 static int ipl_iso_el_torito(void)
990 {
991     uint32_t offset = find_iso_bc();
992     if (!offset) {
993         return 0;
994     }
995 
996     IsoBcSection *s = find_iso_bc_entry(offset);
997 
998     if (s) {
999         load_iso_bc_entry(s); /* only return in error */
1000         return -1;
1001     }
1002 
1003     puts("No suitable boot entry found on ISO-9660 media!");
1004     return -EIO;
1005 }
1006 
1007 /**
1008  * Detect whether we're trying to boot from an .ISO image.
1009  * These always have a signature string "CD001" at offset 0x8001.
1010  */
1011 static bool has_iso_signature(void)
1012 {
1013     int blksize = virtio_get_block_size();
1014 
1015     if (!blksize || virtio_read(0x8000 / blksize, sec)) {
1016         return false;
1017     }
1018 
1019     return !memcmp("CD001", &sec[1], 5);
1020 }
1021 
1022 /***********************************************************************
1023  * Bus specific IPL sequences
1024  */
1025 
1026 static int zipl_load_vblk(void)
1027 {
1028     int blksize = virtio_get_block_size();
1029 
1030     if (blksize == VIRTIO_ISO_BLOCK_SIZE || has_iso_signature()) {
1031         if (blksize != VIRTIO_ISO_BLOCK_SIZE) {
1032             virtio_assume_iso9660();
1033         }
1034         if (ipl_iso_el_torito()) {
1035             return 0;
1036         }
1037     }
1038 
1039     if (blksize != VIRTIO_DASD_DEFAULT_BLOCK_SIZE) {
1040         puts("Using guessed DASD geometry.");
1041         virtio_assume_eckd();
1042     }
1043     return ipl_eckd();
1044 }
1045 
1046 static int zipl_load_vscsi(void)
1047 {
1048     if (virtio_get_block_size() == VIRTIO_ISO_BLOCK_SIZE) {
1049         /* Is it an ISO image in non-CD drive? */
1050         if (ipl_iso_el_torito()) {
1051             return 0;
1052         }
1053     }
1054 
1055     puts("Using guessed DASD geometry.");
1056     virtio_assume_eckd();
1057     return ipl_eckd();
1058 }
1059 
1060 /***********************************************************************
1061  * IPL starts here
1062  */
1063 
1064 void zipl_load(void)
1065 {
1066     VDev *vdev = virtio_get_device();
1067 
1068     if (vdev->is_cdrom) {
1069         ipl_iso_el_torito();
1070         panic("\n! Cannot IPL this ISO image !\n");
1071     }
1072 
1073     if (virtio_get_device_type() == VIRTIO_ID_NET) {
1074         netmain();
1075     }
1076 
1077     if (ipl_scsi()) {
1078         panic("\n! Cannot IPL this SCSI device !\n");
1079     }
1080 
1081     switch (virtio_get_device_type()) {
1082     case VIRTIO_ID_BLOCK:
1083         zipl_load_vblk();
1084         break;
1085     case VIRTIO_ID_SCSI:
1086         zipl_load_vscsi();
1087         break;
1088     default:
1089         panic("\n! Unknown IPL device type !\n");
1090     }
1091 
1092     puts("zIPL load failed.");
1093 }
1094