Index: head/sys/boot/common/commands.c =================================================================== --- head/sys/boot/common/commands.c (revision 308826) +++ head/sys/boot/common/commands.c (revision 308827) @@ -1,513 +1,511 @@ /*- * Copyright (c) 1998 Michael Smith * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include "bootstrap.h" char *command_errmsg; /* XXX should have procedural interface for setting, size limit? */ char command_errbuf[COMMAND_ERRBUFSZ]; static int page_file(char *filename); /* * Help is read from a formatted text file. * * Entries in the file are formatted as # Ttopic [Ssubtopic] Ddescription help text here # * * Note that for code simplicity's sake, the above format must be followed * exactly. * * Subtopic entries must immediately follow the topic (this is used to * produce the listing of subtopics). * * If no argument(s) are supplied by the user, the help for 'help' is displayed. */ COMMAND_SET(help, "help", "detailed help", command_help); static int help_getnext(int fd, char **topic, char **subtopic, char **desc) { char line[81], *cp, *ep; for (;;) { if (fgetstr(line, 80, fd) < 0) return(0); if ((strlen(line) < 3) || (line[0] != '#') || (line[1] != ' ')) continue; *topic = *subtopic = *desc = NULL; cp = line + 2; while((cp != NULL) && (*cp != 0)) { ep = strchr(cp, ' '); if ((*cp == 'T') && (*topic == NULL)) { if (ep != NULL) *ep++ = 0; *topic = strdup(cp + 1); } else if ((*cp == 'S') && (*subtopic == NULL)) { if (ep != NULL) *ep++ = 0; *subtopic = strdup(cp + 1); } else if (*cp == 'D') { *desc = strdup(cp + 1); ep = NULL; } cp = ep; } if (*topic == NULL) { if (*subtopic != NULL) free(*subtopic); if (*desc != NULL) free(*desc); continue; } return(1); } } static int help_emitsummary(char *topic, char *subtopic, char *desc) { int i; pager_output(" "); pager_output(topic); i = strlen(topic); if (subtopic != NULL) { pager_output(" "); pager_output(subtopic); i += strlen(subtopic) + 1; } if (desc != NULL) { do { pager_output(" "); } while (i++ < 30); pager_output(desc); } return (pager_output("\n")); } static int command_help(int argc, char *argv[]) { char buf[81]; /* XXX buffer size? */ int hfd, matched, doindex; char *topic, *subtopic, *t, *s, *d; /* page the help text from our load path */ sprintf(buf, "%s/boot/loader.help", getenv("loaddev")); if ((hfd = open(buf, O_RDONLY)) < 0) { printf("Verbose help not available, use '?' to list commands\n"); return(CMD_OK); } /* pick up request from arguments */ topic = subtopic = NULL; switch(argc) { case 3: subtopic = strdup(argv[2]); case 2: topic = strdup(argv[1]); break; case 1: topic = strdup("help"); break; default: command_errmsg = "usage is 'help []"; close(hfd); return(CMD_ERROR); } /* magic "index" keyword */ doindex = !strcmp(topic, "index"); matched = doindex; /* Scan the helpfile looking for help matching the request */ pager_open(); while(help_getnext(hfd, &t, &s, &d)) { if (doindex) { /* dink around formatting */ if (help_emitsummary(t, s, d)) break; } else if (strcmp(topic, t)) { /* topic mismatch */ if(matched) /* nothing more on this topic, stop scanning */ break; } else { /* topic matched */ matched = 1; if (((subtopic == NULL) && (s == NULL)) || ((subtopic != NULL) && (s != NULL) && !strcmp(subtopic, s))) { /* exact match, print text */ while((fgetstr(buf, 80, hfd) >= 0) && (buf[0] != '#')) { if (pager_output(buf)) break; if (pager_output("\n")) break; } } else if ((subtopic == NULL) && (s != NULL)) { /* topic match, list subtopics */ if (help_emitsummary(t, s, d)) break; } } free(t); free(s); free(d); } pager_close(); close(hfd); if (!matched) { snprintf(command_errbuf, sizeof(command_errbuf), "no help available for '%s'", topic); free(topic); if (subtopic) free(subtopic); return(CMD_ERROR); } free(topic); if (subtopic) free(subtopic); return(CMD_OK); } COMMAND_SET(commandlist, "?", "list commands", command_commandlist); /* * Please note: although we use the pager for the list of commands, * this routine is called from the ? FORTH function which then * unconditionally prints some commands. This will lead to anomalous * behavior. There's no 'pager_output' binding to FORTH to allow * things to work right, so I'm documenting the bug rather than * fixing it. */ static int command_commandlist(int argc, char *argv[]) { struct bootblk_command **cmdp; int res; char name[20]; res = 0; pager_open(); res = pager_output("Available commands:\n"); SET_FOREACH(cmdp, Xcommand_set) { if (res) break; if (((*cmdp)->c_name != NULL) && ((*cmdp)->c_desc != NULL)) { sprintf(name, " %-15s ", (*cmdp)->c_name); pager_output(name); pager_output((*cmdp)->c_desc); res = pager_output("\n"); } } pager_close(); return(CMD_OK); } /* * XXX set/show should become set/echo if we have variable * substitution happening. */ COMMAND_SET(show, "show", "show variable(s)", command_show); static int command_show(int argc, char *argv[]) { struct env_var *ev; char *cp; if (argc < 2) { /* * With no arguments, print everything. */ pager_open(); for (ev = environ; ev != NULL; ev = ev->ev_next) { pager_output(ev->ev_name); cp = getenv(ev->ev_name); if (cp != NULL) { pager_output("="); pager_output(cp); } if (pager_output("\n")) break; } pager_close(); } else { if ((cp = getenv(argv[1])) != NULL) { printf("%s\n", cp); } else { snprintf(command_errbuf, sizeof(command_errbuf), "variable '%s' not found", argv[1]); return(CMD_ERROR); } } return(CMD_OK); } COMMAND_SET(set, "set", "set a variable", command_set); static int command_set(int argc, char *argv[]) { int err; if (argc != 2) { command_errmsg = "wrong number of arguments"; return(CMD_ERROR); } else { if ((err = putenv(argv[1])) != 0) { command_errmsg = strerror(err); return(CMD_ERROR); } } return(CMD_OK); } COMMAND_SET(unset, "unset", "unset a variable", command_unset); static int command_unset(int argc, char *argv[]) { int err; if (argc != 2) { command_errmsg = "wrong number of arguments"; return(CMD_ERROR); } else { if ((err = unsetenv(argv[1])) != 0) { command_errmsg = strerror(err); return(CMD_ERROR); } } return(CMD_OK); } COMMAND_SET(echo, "echo", "echo arguments", command_echo); static int command_echo(int argc, char *argv[]) { char *s; int nl, ch; nl = 0; optind = 1; optreset = 1; while ((ch = getopt(argc, argv, "n")) != -1) { switch(ch) { case 'n': nl = 1; break; case '?': default: /* getopt has already reported an error */ return(CMD_OK); } } argv += (optind); argc -= (optind); s = unargv(argc, argv); if (s != NULL) { printf("%s", s); free(s); } if (!nl) printf("\n"); return(CMD_OK); } /* * A passable emulation of the sh(1) command of the same name. */ COMMAND_SET(read, "read", "read input from the terminal", command_read); static int command_read(int argc, char *argv[]) { char *prompt; int timeout; time_t when; char *cp; char *name; char buf[256]; /* XXX size? */ int c; timeout = -1; prompt = NULL; optind = 1; optreset = 1; while ((c = getopt(argc, argv, "p:t:")) != -1) { switch(c) { case 'p': prompt = optarg; break; case 't': timeout = strtol(optarg, &cp, 0); if (cp == optarg) { snprintf(command_errbuf, sizeof(command_errbuf), "bad timeout '%s'", optarg); return(CMD_ERROR); } break; default: return(CMD_OK); } } argv += (optind); argc -= (optind); name = (argc > 0) ? argv[0]: NULL; if (prompt != NULL) printf("%s", prompt); if (timeout >= 0) { when = time(NULL) + timeout; while (!ischar()) if (time(NULL) >= when) return(CMD_OK); /* is timeout an error? */ } ngets(buf, sizeof(buf)); if (name != NULL) setenv(name, buf, 1); return(CMD_OK); } /* * File pager */ COMMAND_SET(more, "more", "show contents of a file", command_more); static int command_more(int argc, char *argv[]) { int i; int res; char line[80]; res=0; pager_open(); for (i = 1; (i < argc) && (res == 0); i++) { sprintf(line, "*** FILE %s BEGIN ***\n", argv[i]); if (pager_output(line)) break; res = page_file(argv[i]); if (!res) { sprintf(line, "*** FILE %s END ***\n", argv[i]); res = pager_output(line); } } pager_close(); if (res == 0) return CMD_OK; else return CMD_ERROR; } static int page_file(char *filename) { int result; result = pager_file(filename); if (result == -1) { snprintf(command_errbuf, sizeof(command_errbuf), "error showing %s", filename); } return result; } /* * List all disk-like devices */ COMMAND_SET(lsdev, "lsdev", "list all devices", command_lsdev); static int command_lsdev(int argc, char *argv[]) { int verbose, ch, i; char line[80]; verbose = 0; optind = 1; optreset = 1; while ((ch = getopt(argc, argv, "v")) != -1) { switch(ch) { case 'v': verbose = 1; break; case '?': default: /* getopt has already reported an error */ return(CMD_OK); } } argv += (optind); argc -= (optind); pager_open(); for (i = 0; devsw[i] != NULL; i++) { if (devsw[i]->dv_print != NULL){ - sprintf(line, "%s devices:\n", devsw[i]->dv_name); - if (pager_output(line)) - break; - devsw[i]->dv_print(verbose); + if (devsw[i]->dv_print(verbose)) + break; } else { sprintf(line, "%s: (unknown)\n", devsw[i]->dv_name); if (pager_output(line)) break; } } pager_close(); return(CMD_OK); } Index: head/sys/boot/common/dev_net.c =================================================================== --- head/sys/boot/common/dev_net.c (revision 308826) +++ head/sys/boot/common/dev_net.c (revision 308827) @@ -1,378 +1,385 @@ /* $NetBSD: dev_net.c,v 1.23 2008/04/28 20:24:06 martin Exp $ */ /*- * Copyright (c) 1997 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Gordon W. Ross. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /*- * This module implements a "raw device" interface suitable for * use by the stand-alone I/O library NFS code. This interface * does not support any "block" access, and exists only for the * purpose of initializing the network interface, getting boot * parameters, and performing the NFS mount. * * At open time, this does: * * find interface - netif_open() * RARP for IP address - rarp_getipaddress() * RPC/bootparams - callrpc(d, RPC_BOOTPARAMS, ...) * RPC/mountd - nfs_mount(sock, ip, path) * * the root file handle from mountd is saved in a global * for use by the NFS open code (NFS/lookup). */ #include #include #include #include #include #include #include #include #include #include #include #include #include "dev_net.h" #include "bootstrap.h" #ifdef NETIF_DEBUG int debug = 0; #endif static char *netdev_name; static int netdev_sock = -1; static int netdev_opens; static int net_init(void); static int net_open(struct open_file *, ...); static int net_close(struct open_file *); static void net_cleanup(void); static int net_strategy(); static int net_print(int); static int net_getparams(int sock); struct devsw netdev = { "net", DEVT_NET, net_init, net_strategy, net_open, net_close, noioctl, net_print, net_cleanup }; static int net_init(void) { return (0); } /* * Called by devopen after it sets f->f_dev to our devsw entry. * This opens the low-level device and sets f->f_devdata. * This is declared with variable arguments... */ static int net_open(struct open_file *f, ...) { struct iodesc *d; va_list args; char *devname; /* Device part of file name (or NULL). */ int error = 0; va_start(args, f); devname = va_arg(args, char*); va_end(args); /* Before opening another interface, close the previous one first. */ if (netdev_sock >= 0 && strcmp(devname, netdev_name) != 0) net_cleanup(); /* On first open, do netif open, mount, etc. */ if (netdev_opens == 0) { /* Find network interface. */ if (netdev_sock < 0) { netdev_sock = netif_open(devname); if (netdev_sock < 0) { printf("net_open: netif_open() failed\n"); return (ENXIO); } netdev_name = strdup(devname); #ifdef NETIF_DEBUG if (debug) printf("net_open: netif_open() succeeded\n"); #endif } /* * If network params were not set by netif_open(), try to get * them via bootp, rarp, etc. */ if (rootip.s_addr == 0) { /* Get root IP address, and path, etc. */ error = net_getparams(netdev_sock); if (error) { /* getparams makes its own noise */ free(netdev_name); netif_close(netdev_sock); netdev_sock = -1; return (error); } } /* * Set the variables required by the kernel's nfs_diskless * mechanism. This is the minimum set of variables required to * mount a root filesystem without needing to obtain additional * info from bootp or other sources. */ d = socktodesc(netdev_sock); setenv("boot.netif.hwaddr", ether_sprintf(d->myea), 1); setenv("boot.netif.ip", inet_ntoa(myip), 1); setenv("boot.netif.netmask", intoa(netmask), 1); setenv("boot.netif.gateway", inet_ntoa(gateip), 1); setenv("boot.netif.server", inet_ntoa(rootip), 1); if (netproto == NET_TFTP) { setenv("boot.tftproot.server", inet_ntoa(rootip), 1); setenv("boot.tftproot.path", rootpath, 1); } else if (netproto == NET_NFS) { setenv("boot.nfsroot.server", inet_ntoa(rootip), 1); setenv("boot.nfsroot.path", rootpath, 1); } if (intf_mtu != 0) { char mtu[16]; sprintf(mtu, "%u", intf_mtu); setenv("boot.netif.mtu", mtu, 1); } } netdev_opens++; f->f_devdata = &netdev_sock; return (error); } static int net_close(struct open_file *f) { #ifdef NETIF_DEBUG if (debug) printf("net_close: opens=%d\n", netdev_opens); #endif f->f_devdata = NULL; return (0); } static void net_cleanup(void) { if (netdev_sock >= 0) { #ifdef NETIF_DEBUG if (debug) printf("net_cleanup: calling netif_close()\n"); #endif rootip.s_addr = 0; free(netdev_name); netif_close(netdev_sock); netdev_sock = -1; } } static int net_strategy() { return (EIO); } #define SUPPORT_BOOTP /* * Get info for NFS boot: our IP address, our hostname, * server IP address, and our root path on the server. * There are two ways to do this: The old, Sun way, * and the more modern, BOOTP way. (RFC951, RFC1048) * * The default is to use the Sun bootparams RPC * (because that is what the kernel will do). * MD code can make try_bootp initialied data, * which will override this common definition. */ #ifdef SUPPORT_BOOTP int try_bootp = 1; #endif extern n_long ip_convertaddr(char *p); static int net_getparams(int sock) { char buf[MAXHOSTNAMELEN]; n_long rootaddr, smask; #ifdef SUPPORT_BOOTP /* * Try to get boot info using BOOTP. If we succeed, then * the server IP address, gateway, and root path will all * be initialized. If any remain uninitialized, we will * use RARP and RPC/bootparam (the Sun way) to get them. */ if (try_bootp) bootp(sock, BOOTP_NONE); if (myip.s_addr != 0) goto exit; #ifdef NETIF_DEBUG if (debug) printf("net_open: BOOTP failed, trying RARP/RPC...\n"); #endif #endif /* * Use RARP to get our IP address. This also sets our * netmask to the "natural" default for our address. */ if (rarp_getipaddress(sock)) { printf("net_open: RARP failed\n"); return (EIO); } printf("net_open: client addr: %s\n", inet_ntoa(myip)); /* Get our hostname, server IP address, gateway. */ if (bp_whoami(sock)) { printf("net_open: bootparam/whoami RPC failed\n"); return (EIO); } #ifdef NETIF_DEBUG if (debug) printf("net_open: client name: %s\n", hostname); #endif /* * Ignore the gateway from whoami (unreliable). * Use the "gateway" parameter instead. */ smask = 0; gateip.s_addr = 0; if (bp_getfile(sock, "gateway", &gateip, buf) == 0) { /* Got it! Parse the netmask. */ smask = ip_convertaddr(buf); } if (smask) { netmask = smask; #ifdef NETIF_DEBUG if (debug) printf("net_open: subnet mask: %s\n", intoa(netmask)); #endif } #ifdef NETIF_DEBUG if (gateip.s_addr && debug) printf("net_open: net gateway: %s\n", inet_ntoa(gateip)); #endif /* Get the root server and pathname. */ if (bp_getfile(sock, "root", &rootip, rootpath)) { printf("net_open: bootparam/getfile RPC failed\n"); return (EIO); } exit: if ((rootaddr = net_parse_rootpath()) != INADDR_NONE) rootip.s_addr = rootaddr; #ifdef NETIF_DEBUG if (debug) { printf("net_open: server addr: %s\n", inet_ntoa(rootip)); printf("net_open: server path: %s\n", rootpath); } #endif return (0); } static int net_print(int verbose) { struct netif_driver *drv; int i, d, cnt; int ret = 0; + if (netif_drivers[0] == NULL) + return (ret); + + printf("%s devices:", netdev.dv_name); + if ((ret = pager_output("\n")) != 0) + return (ret); + cnt = 0; for (d = 0; netif_drivers[d]; d++) { drv = netif_drivers[d]; for (i = 0; i < drv->netif_nifs; i++) { - printf("\t%s%d:", "net", cnt++); + printf("\t%s%d:", netdev.dv_name, cnt++); if (verbose) { printf(" (%s%d)", drv->netif_bname, drv->netif_ifs[i].dif_unit); } if ((ret = pager_output("\n")) != 0) return (ret); } } return (ret); } /* * Strip the server's address off of the rootpath if present and return it in * network byte order, leaving just the pathname part in the global rootpath. */ uint32_t net_parse_rootpath() { int i; n_long addr = INADDR_NONE; netproto = NET_NFS; if (tftpip.s_addr != 0) { netproto = NET_TFTP; addr = tftpip.s_addr; } for (i = 0; rootpath[i] != '\0' && i < FNAME_SIZE; i++) if (rootpath[i] == ':') break; if (i && i != FNAME_SIZE && rootpath[i] == ':') { rootpath[i++] = '\0'; addr = inet_addr(&rootpath[0]); bcopy(&rootpath[i], rootpath, strlen(&rootpath[i])+1); } return (addr); } Index: head/sys/boot/common/md.c =================================================================== --- head/sys/boot/common/md.c (revision 308826) +++ head/sys/boot/common/md.c (revision 308827) @@ -1,151 +1,156 @@ /*- * Copyright (c) 2009 Marcel Moolenaar * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include "bootstrap.h" #define MD_BLOCK_SIZE 512 #ifndef MD_IMAGE_SIZE #error Must be compiled with MD_IMAGE_SIZE defined #endif #if (MD_IMAGE_SIZE == 0 || MD_IMAGE_SIZE % MD_BLOCK_SIZE) #error Image size must be a multiple of 512. #endif /* * Preloaded image gets put here. * Applications that patch the object with the image can determine * the size looking at the start and end markers (strings), * so we want them contiguous. */ static struct { u_char start[MD_IMAGE_SIZE]; u_char end[128]; } md_image = { .start = "MFS Filesystem goes here", .end = "MFS Filesystem had better STOP here", }; /* devsw I/F */ static int md_init(void); static int md_strategy(void *, int, daddr_t, size_t, size_t, char *, size_t *); static int md_open(struct open_file *, ...); static int md_close(struct open_file *); -static void md_print(int); +static int md_print(int); struct devsw md_dev = { "md", DEVT_DISK, md_init, md_strategy, md_open, md_close, noioctl, md_print }; static int md_init(void) { return (0); } static int md_strategy(void *devdata, int rw, daddr_t blk, size_t offset, size_t size, char *buf, size_t *rsize) { struct devdesc *dev = (struct devdesc *)devdata; size_t ofs; if (dev->d_unit != 0) return (ENXIO); if (blk < 0 || blk >= (MD_IMAGE_SIZE / MD_BLOCK_SIZE)) return (EIO); if (size % MD_BLOCK_SIZE) return (EIO); ofs = blk * MD_BLOCK_SIZE; if ((ofs + size) > MD_IMAGE_SIZE) size = MD_IMAGE_SIZE - ofs; if (rsize != 0) *rsize = size; switch (rw) { case F_READ: bcopy(md_image.start + ofs, buf, size); return (0); case F_WRITE: bcopy(buf, md_image.start + ofs, size); return (0); } return (ENODEV); } static int md_open(struct open_file *f, ...) { va_list ap; struct devdesc *dev; va_start(ap, f); dev = va_arg(ap, struct devdesc *); va_end(ap); if (dev->d_unit != 0) return (ENXIO); return (0); } static int md_close(struct open_file *f) { struct devdesc *dev; dev = (struct devdesc *)(f->f_devdata); return ((dev->d_unit != 0) ? ENXIO : 0); } -static void +static int md_print(int verbose) { - printf("MD (%u bytes)\n", MD_IMAGE_SIZE); + printf("%s devices:", md_dev.dv_name); + if (pager_output("\n") != 0) + return (1); + + printf("MD (%u bytes)", MD_IMAGE_SIZE); + return (pager_output("\n")); } Index: head/sys/boot/efi/libefi/efinet.c =================================================================== --- head/sys/boot/efi/libefi/efinet.c (revision 308826) +++ head/sys/boot/efi/libefi/efinet.c (revision 308827) @@ -1,370 +1,374 @@ /*- * Copyright (c) 2001 Doug Rabson * Copyright (c) 2002, 2006 Marcel Moolenaar * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include static EFI_GUID sn_guid = EFI_SIMPLE_NETWORK_PROTOCOL; static void efinet_end(struct netif *); static int efinet_get(struct iodesc *, void *, size_t, time_t); static void efinet_init(struct iodesc *, void *); static int efinet_match(struct netif *, void *); static int efinet_probe(struct netif *, void *); static int efinet_put(struct iodesc *, void *, size_t); struct netif_driver efinetif = { .netif_bname = "efinet", .netif_match = efinet_match, .netif_probe = efinet_probe, .netif_init = efinet_init, .netif_get = efinet_get, .netif_put = efinet_put, .netif_end = efinet_end, .netif_ifs = NULL, .netif_nifs = 0 }; #ifdef EFINET_DEBUG static void dump_mode(EFI_SIMPLE_NETWORK_MODE *mode) { int i; printf("State = %x\n", mode->State); printf("HwAddressSize = %u\n", mode->HwAddressSize); printf("MediaHeaderSize = %u\n", mode->MediaHeaderSize); printf("MaxPacketSize = %u\n", mode->MaxPacketSize); printf("NvRamSize = %u\n", mode->NvRamSize); printf("NvRamAccessSize = %u\n", mode->NvRamAccessSize); printf("ReceiveFilterMask = %x\n", mode->ReceiveFilterMask); printf("ReceiveFilterSetting = %u\n", mode->ReceiveFilterSetting); printf("MaxMCastFilterCount = %u\n", mode->MaxMCastFilterCount); printf("MCastFilterCount = %u\n", mode->MCastFilterCount); printf("MCastFilter = {"); for (i = 0; i < mode->MCastFilterCount; i++) printf(" %s", ether_sprintf(mode->MCastFilter[i].Addr)); printf(" }\n"); printf("CurrentAddress = %s\n", ether_sprintf(mode->CurrentAddress.Addr)); printf("BroadcastAddress = %s\n", ether_sprintf(mode->BroadcastAddress.Addr)); printf("PermanentAddress = %s\n", ether_sprintf(mode->PermanentAddress.Addr)); printf("IfType = %u\n", mode->IfType); printf("MacAddressChangeable = %d\n", mode->MacAddressChangeable); printf("MultipleTxSupported = %d\n", mode->MultipleTxSupported); printf("MediaPresentSupported = %d\n", mode->MediaPresentSupported); printf("MediaPresent = %d\n", mode->MediaPresent); } #endif static int efinet_match(struct netif *nif, void *machdep_hint) { struct devdesc *dev = machdep_hint; if (dev->d_unit == nif->nif_unit) return (1); return(0); } static int efinet_probe(struct netif *nif, void *machdep_hint) { return (0); } static int efinet_put(struct iodesc *desc, void *pkt, size_t len) { struct netif *nif = desc->io_netif; EFI_SIMPLE_NETWORK *net; EFI_STATUS status; void *buf; net = nif->nif_devdata; if (net == NULL) return (-1); status = net->Transmit(net, 0, len, pkt, 0, 0, 0); if (status != EFI_SUCCESS) return (-1); /* Wait for the buffer to be transmitted */ do { buf = 0; /* XXX Is this needed? */ status = net->GetStatus(net, 0, &buf); /* * XXX EFI1.1 and the E1000 card returns a different * address than we gave. Sigh. */ } while (status == EFI_SUCCESS && buf == 0); /* XXX How do we deal with status != EFI_SUCCESS now? */ return ((status == EFI_SUCCESS) ? len : -1); } static int efinet_get(struct iodesc *desc, void *pkt, size_t len, time_t timeout) { struct netif *nif = desc->io_netif; EFI_SIMPLE_NETWORK *net; EFI_STATUS status; UINTN bufsz; time_t t; char buf[2048]; net = nif->nif_devdata; if (net == NULL) return (0); t = time(0); while ((time(0) - t) < timeout) { bufsz = sizeof(buf); status = net->Receive(net, 0, &bufsz, buf, 0, 0, 0); if (status == EFI_SUCCESS) { /* * XXX EFI1.1 and the E1000 card trash our * workspace if we do not do this silly copy. * Either they are not respecting the len * value or do not like the alignment. */ if (bufsz > len) bufsz = len; bcopy(buf, pkt, bufsz); return (bufsz); } if (status != EFI_NOT_READY) return (0); } return (0); } static void efinet_init(struct iodesc *desc, void *machdep_hint) { struct netif *nif = desc->io_netif; EFI_SIMPLE_NETWORK *net; EFI_HANDLE h; EFI_STATUS status; if (nif->nif_driver->netif_ifs[nif->nif_unit].dif_unit < 0) { printf("Invalid network interface %d\n", nif->nif_unit); return; } h = nif->nif_driver->netif_ifs[nif->nif_unit].dif_private; status = BS->HandleProtocol(h, &sn_guid, (VOID **)&nif->nif_devdata); if (status != EFI_SUCCESS) { printf("net%d: cannot fetch interface data (status=%lu)\n", nif->nif_unit, EFI_ERROR_CODE(status)); return; } net = nif->nif_devdata; if (net->Mode->State == EfiSimpleNetworkStopped) { status = net->Start(net); if (status != EFI_SUCCESS) { printf("net%d: cannot start interface (status=%ld)\n", nif->nif_unit, (long)status); return; } } if (net->Mode->State != EfiSimpleNetworkInitialized) { status = net->Initialize(net, 0, 0); if (status != EFI_SUCCESS) { printf("net%d: cannot init. interface (status=%ld)\n", nif->nif_unit, (long)status); return; } } if (net->Mode->ReceiveFilterSetting == 0) { UINT32 mask = EFI_SIMPLE_NETWORK_RECEIVE_UNICAST | EFI_SIMPLE_NETWORK_RECEIVE_BROADCAST; status = net->ReceiveFilters(net, mask, 0, FALSE, 0, 0); if (status != EFI_SUCCESS) { printf("net%d: cannot set rx. filters (status=%ld)\n", nif->nif_unit, (long)status); return; } } #ifdef EFINET_DEBUG dump_mode(net->Mode); #endif bcopy(net->Mode->CurrentAddress.Addr, desc->myea, 6); desc->xid = 1; } static void efinet_end(struct netif *nif) { EFI_SIMPLE_NETWORK *net = nif->nif_devdata; if (net == NULL) return; net->Shutdown(net); } static int efinet_dev_init(void); static int efinet_dev_print(int); struct devsw efinet_dev = { .dv_name = "net", .dv_type = DEVT_NET, .dv_init = efinet_dev_init, .dv_strategy = net_strategy, .dv_open = net_open, .dv_close = net_close, .dv_ioctl = noioctl, .dv_print = efinet_dev_print, .dv_cleanup = NULL }; static int efinet_dev_init() { struct netif_dif *dif; struct netif_stats *stats; EFI_DEVICE_PATH *devpath, *node; EFI_SIMPLE_NETWORK *net; EFI_HANDLE *handles, *handles2; EFI_STATUS status; UINTN sz; int err, i, nifs; sz = 0; handles = NULL; status = BS->LocateHandle(ByProtocol, &sn_guid, 0, &sz, 0); if (status == EFI_BUFFER_TOO_SMALL) { handles = (EFI_HANDLE *)malloc(sz); status = BS->LocateHandle(ByProtocol, &sn_guid, 0, &sz, handles); if (EFI_ERROR(status)) free(handles); } if (EFI_ERROR(status)) return (efi_status_to_errno(status)); handles2 = (EFI_HANDLE *)malloc(sz); nifs = 0; for (i = 0; i < sz / sizeof(EFI_HANDLE); i++) { devpath = efi_lookup_devpath(handles[i]); if (devpath == NULL) continue; node = efi_devpath_last_node(devpath); if (DevicePathType(node) != MESSAGING_DEVICE_PATH || DevicePathSubType(node) != MSG_MAC_ADDR_DP) continue; /* * Open the network device in exclusive mode. Without this * we will be racing with the UEFI network stack. It will * pull packets off the network leading to lost packets. */ status = BS->OpenProtocol(handles[i], &sn_guid, (void **)&net, IH, 0, EFI_OPEN_PROTOCOL_EXCLUSIVE); if (status != EFI_SUCCESS) { printf("Unable to open network interface %d for " "exclusive access: %d\n", i, EFI_ERROR(status)); } handles2[nifs] = handles[i]; nifs++; } free(handles); if (nifs == 0) { free(handles2); return (ENOENT); } err = efi_register_handles(&efinet_dev, handles2, NULL, nifs); if (err != 0) { free(handles2); return (err); } efinetif.netif_nifs = nifs; efinetif.netif_ifs = calloc(nifs, sizeof(struct netif_dif)); stats = calloc(nifs, sizeof(struct netif_stats)); for (i = 0; i < nifs; i++) { dif = &efinetif.netif_ifs[i]; dif->dif_unit = i; dif->dif_nsel = 1; dif->dif_stats = &stats[i]; dif->dif_private = handles2[i]; } free(handles2); return (0); } static int efinet_dev_print(int verbose) { CHAR16 *text; EFI_HANDLE h; int unit, ret = 0; + printf("%s devices:", efinet_dev.dv_name); + if ((ret = pager_output("\n")) != 0) + return (ret); + for (unit = 0, h = efi_find_handle(&efinet_dev, 0); h != NULL; h = efi_find_handle(&efinet_dev, ++unit)) { printf(" %s%d:", efinet_dev.dv_name, unit); if (verbose) { text = efi_devpath_name(efi_lookup_devpath(h)); if (text != NULL) { printf(" %S", text); efi_free_devpath_name(text); } } if ((ret = pager_output("\n")) != 0) break; } return (ret); } Index: head/sys/boot/efi/libefi/efipart.c =================================================================== --- head/sys/boot/efi/libefi/efipart.c (revision 308826) +++ head/sys/boot/efi/libefi/efipart.c (revision 308827) @@ -1,368 +1,372 @@ /*- * Copyright (c) 2010 Marcel Moolenaar * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include static EFI_GUID blkio_guid = BLOCK_IO_PROTOCOL; static int efipart_init(void); static int efipart_strategy(void *, int, daddr_t, size_t, size_t, char *, size_t *); static int efipart_realstrategy(void *, int, daddr_t, size_t, size_t, char *, size_t *); static int efipart_open(struct open_file *, ...); static int efipart_close(struct open_file *); static int efipart_print(int); struct devsw efipart_dev = { .dv_name = "part", .dv_type = DEVT_DISK, .dv_init = efipart_init, .dv_strategy = efipart_strategy, .dv_open = efipart_open, .dv_close = efipart_close, .dv_ioctl = noioctl, .dv_print = efipart_print, .dv_cleanup = NULL }; /* * info structure to support bcache */ struct pdinfo { int pd_unit; /* unit number */ int pd_open; /* reference counter */ void *pd_bcache; /* buffer cache data */ }; static struct pdinfo *pdinfo; static int npdinfo = 0; #define PD(dev) (pdinfo[(dev)->d_unit]) static int efipart_init(void) { EFI_BLOCK_IO *blkio; EFI_DEVICE_PATH *devpath, *devpathcpy, *tmpdevpath, *node; EFI_HANDLE *hin, *hout, *aliases, handle; EFI_STATUS status; UINTN sz; u_int n, nin, nout, nrdisk; int err; sz = 0; hin = NULL; status = BS->LocateHandle(ByProtocol, &blkio_guid, 0, &sz, 0); if (status == EFI_BUFFER_TOO_SMALL) { hin = (EFI_HANDLE *)malloc(sz * 3); status = BS->LocateHandle(ByProtocol, &blkio_guid, 0, &sz, hin); if (EFI_ERROR(status)) free(hin); } if (EFI_ERROR(status)) return (efi_status_to_errno(status)); /* Filter handles to only include FreeBSD partitions. */ nin = sz / sizeof(EFI_HANDLE); hout = hin + nin; aliases = hout + nin; nout = 0; nrdisk = 0; bzero(aliases, nin * sizeof(EFI_HANDLE)); pdinfo = malloc(nin * sizeof(*pdinfo)); if (pdinfo == NULL) return (ENOMEM); for (n = 0; n < nin; n++) { devpath = efi_lookup_devpath(hin[n]); if (devpath == NULL) { continue; } status = BS->HandleProtocol(hin[n], &blkio_guid, (void**)&blkio); if (EFI_ERROR(status)) continue; if (!blkio->Media->LogicalPartition) { nrdisk++; continue; } /* * If we come across a logical partition of subtype CDROM * it doesn't refer to the CD filesystem itself, but rather * to any usable El Torito boot image on it. In this case * we try to find the parent device and add that instead as * that will be the CD filesystem. */ node = efi_devpath_last_node(devpath); if (DevicePathType(node) == MEDIA_DEVICE_PATH && DevicePathSubType(node) == MEDIA_CDROM_DP) { devpathcpy = efi_devpath_trim(devpath); tmpdevpath = devpathcpy; status = BS->LocateDevicePath(&blkio_guid, &tmpdevpath, &handle); free(devpathcpy); if (EFI_ERROR(status)) continue; hout[nout] = handle; aliases[nout] = hin[n]; } else hout[nout] = hin[n]; nout++; pdinfo[npdinfo].pd_open = 0; pdinfo[npdinfo].pd_bcache = NULL; pdinfo[npdinfo].pd_unit = npdinfo; npdinfo++; } bcache_add_dev(npdinfo); err = efi_register_handles(&efipart_dev, hout, aliases, nout); free(hin); if (nout == 0 && nrdisk > 0) printf("Found %d disk(s) but no logical partition\n", nrdisk); return (err); } static int efipart_print(int verbose) { char line[80]; EFI_BLOCK_IO *blkio; EFI_HANDLE h; EFI_STATUS status; u_int unit; int ret = 0; + printf("%s devices:", efipart_dev.dv_name); + if ((ret = pager_output("\n")) != 0) + return (ret); + for (unit = 0, h = efi_find_handle(&efipart_dev, 0); h != NULL; h = efi_find_handle(&efipart_dev, ++unit)) { snprintf(line, sizeof(line), " %s%d:", efipart_dev.dv_name, unit); if ((ret = pager_output(line)) != 0) break; status = BS->HandleProtocol(h, &blkio_guid, (void **)&blkio); if (!EFI_ERROR(status)) { snprintf(line, sizeof(line), " %llu blocks", (unsigned long long)(blkio->Media->LastBlock + 1)); if ((ret = pager_output(line)) != 0) break; if (blkio->Media->RemovableMedia) if ((ret = pager_output(" (removable)")) != 0) break; } if ((ret = pager_output("\n")) != 0) break; } return (ret); } static int efipart_open(struct open_file *f, ...) { va_list args; struct devdesc *dev; EFI_BLOCK_IO *blkio; EFI_HANDLE h; EFI_STATUS status; va_start(args, f); dev = va_arg(args, struct devdesc*); va_end(args); h = efi_find_handle(&efipart_dev, dev->d_unit); if (h == NULL) return (EINVAL); status = BS->HandleProtocol(h, &blkio_guid, (void **)&blkio); if (EFI_ERROR(status)) return (efi_status_to_errno(status)); if (!blkio->Media->MediaPresent) return (EAGAIN); dev->d_opendata = blkio; PD(dev).pd_open++; if (PD(dev).pd_bcache == NULL) PD(dev).pd_bcache = bcache_allocate(); return (0); } static int efipart_close(struct open_file *f) { struct devdesc *dev; dev = (struct devdesc *)(f->f_devdata); if (dev->d_opendata == NULL) return (EINVAL); dev->d_opendata = NULL; PD(dev).pd_open--; if (PD(dev).pd_open == 0) { bcache_free(PD(dev).pd_bcache); PD(dev).pd_bcache = NULL; } return (0); } /* * efipart_readwrite() * Internal equivalent of efipart_strategy(), which operates on the * media-native block size. This function expects all I/O requests * to be within the media size and returns an error if such is not * the case. */ static int efipart_readwrite(EFI_BLOCK_IO *blkio, int rw, daddr_t blk, daddr_t nblks, char *buf) { EFI_STATUS status; if (blkio == NULL) return (ENXIO); if (blk < 0 || blk > blkio->Media->LastBlock) return (EIO); if ((blk + nblks - 1) > blkio->Media->LastBlock) return (EIO); switch (rw) { case F_READ: status = blkio->ReadBlocks(blkio, blkio->Media->MediaId, blk, nblks * blkio->Media->BlockSize, buf); break; case F_WRITE: if (blkio->Media->ReadOnly) return (EROFS); status = blkio->WriteBlocks(blkio, blkio->Media->MediaId, blk, nblks * blkio->Media->BlockSize, buf); break; default: return (ENOSYS); } if (EFI_ERROR(status)) printf("%s: rw=%d, status=%lu\n", __func__, rw, (u_long)status); return (efi_status_to_errno(status)); } static int efipart_strategy(void *devdata, int rw, daddr_t blk, size_t offset, size_t size, char *buf, size_t *rsize) { struct bcache_devdata bcd; struct devdesc *dev; dev = (struct devdesc *)devdata; bcd.dv_strategy = efipart_realstrategy; bcd.dv_devdata = devdata; bcd.dv_cache = PD(dev).pd_bcache; return (bcache_strategy(&bcd, rw, blk, offset, size, buf, rsize)); } static int efipart_realstrategy(void *devdata, int rw, daddr_t blk, size_t offset, size_t size, char *buf, size_t *rsize) { struct devdesc *dev = (struct devdesc *)devdata; EFI_BLOCK_IO *blkio; off_t off; char *blkbuf; size_t blkoff, blksz; int error; if (dev == NULL || blk < 0) return (EINVAL); blkio = dev->d_opendata; if (blkio == NULL) return (ENXIO); if (size == 0 || (size % 512) != 0) return (EIO); off = blk * 512; /* make sure we don't read past disk end */ if ((off + size) / blkio->Media->BlockSize - 1 > blkio->Media->LastBlock) { size = blkio->Media->LastBlock + 1 - off / blkio->Media->BlockSize; size = size * blkio->Media->BlockSize; } if (rsize != NULL) *rsize = size; if ((size % blkio->Media->BlockSize == 0) && ((blk * 512) % blkio->Media->BlockSize == 0)) return (efipart_readwrite(blkio, rw, blk * 512 / blkio->Media->BlockSize, size / blkio->Media->BlockSize, buf)); /* * The block size of the media is not a multiple of I/O. */ blkbuf = malloc(blkio->Media->BlockSize); if (blkbuf == NULL) return (ENOMEM); error = 0; blk = off / blkio->Media->BlockSize; blkoff = off % blkio->Media->BlockSize; blksz = blkio->Media->BlockSize - blkoff; while (size > 0) { error = efipart_readwrite(blkio, rw, blk, 1, blkbuf); if (error) break; if (size < blksz) blksz = size; bcopy(blkbuf + blkoff, buf, blksz); buf += blksz; size -= blksz; blk++; blkoff = 0; blksz = blkio->Media->BlockSize; } free(blkbuf); return (error); } Index: head/sys/boot/i386/libfirewire/firewire.c =================================================================== --- head/sys/boot/i386/libfirewire/firewire.c (revision 308826) +++ head/sys/boot/i386/libfirewire/firewire.c (revision 308827) @@ -1,480 +1,484 @@ /*- * Copyright (c) 2004 Hidetoshi Shimokawa * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * FireWire disk device handling. * */ #include #include #include #include #include #include #include "fwohci.h" #include /* XXX */ #define BIT4x2(x,y) uint8_t y:4, x:4 #define BIT16x2(x,y) uint32_t y:16, x:16 #define _KERNEL #include extern uint32_t dcons_paddr; extern struct console dconsole; struct crom_src_buf { struct crom_src src; struct crom_chunk root; struct crom_chunk vendor; struct crom_chunk hw; /* for dcons */ struct crom_chunk unit; struct crom_chunk spec; struct crom_chunk ver; }; static int fw_init(void); static int fw_strategy(void *devdata, int flag, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize); static int fw_open(struct open_file *f, ...); static int fw_close(struct open_file *f); static int fw_print(int verbose); static void fw_cleanup(void); void fw_enable(void); struct devsw fwohci = { "FW1394", /* 7 chars at most */ DEVT_NET, fw_init, fw_strategy, fw_open, fw_close, noioctl, fw_print, fw_cleanup }; static struct fwohci_softc fwinfo[MAX_OHCI]; static int fw_initialized = 0; static void fw_probe(int index, struct fwohci_softc *sc) { int err; sc->state = FWOHCI_STATE_INIT; err = biospci_find_devclass( 0x0c0010 /* Serial:FireWire:OHCI */, index /* index */, &sc->locator); if (err != 0) { sc->state = FWOHCI_STATE_DEAD; return; } biospci_write_config(sc->locator, 0x4 /* command */, 0x6 /* enable bus master and memory mapped I/O */, 1 /* word */); biospci_read_config(sc->locator, 0x00 /*devid*/, 2 /*dword*/, &sc->devid); biospci_read_config(sc->locator, 0x10 /*base_addr*/, 2 /*dword*/, &sc->base_addr); sc->handle = (uint32_t)PTOV(sc->base_addr); sc->bus_id = OREAD(sc, OHCI_BUS_ID); return; } static int fw_init(void) { int i, avail; struct fwohci_softc *sc; if (fw_initialized) return (0); avail = 0; for (i = 0; i < MAX_OHCI; i ++) { sc = &fwinfo[i]; fw_probe(i, sc); if (sc->state == FWOHCI_STATE_DEAD) break; avail ++; break; } fw_initialized = 1; return (0); } /* * Print information about OHCI chips */ static int fw_print(int verbose) { char line[80]; int i, ret = 0; struct fwohci_softc *sc; + printf("%s devices:", fwohci.dv_name); + if ((ret = pager_output("\n")) != 0) + return (ret); + for (i = 0; i < MAX_OHCI; i ++) { sc = &fwinfo[i]; if (sc->state == FWOHCI_STATE_DEAD) break; snprintf(line, sizeof(line), "%d: locator=0x%04x devid=0x%08x" " base_addr=0x%08x handle=0x%08x bus_id=0x%08x\n", i, sc->locator, sc->devid, sc->base_addr, sc->handle, sc->bus_id); ret = pager_output(line); if (ret != 0) break; } return (ret); } static int fw_open(struct open_file *f, ...) { #if 0 va_list ap; struct i386_devdesc *dev; struct open_disk *od; int error; va_start(ap, f); dev = va_arg(ap, struct i386_devdesc *); va_end(ap); #endif return (ENXIO); } static int fw_close(struct open_file *f) { return (0); } static void fw_cleanup() { struct dcons_buf *db; /* invalidate dcons buffer */ if (dcons_paddr) { db = (struct dcons_buf *)PTOV(dcons_paddr); db->magic = 0; } } static int fw_strategy(void *devdata, int rw, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize) { return (EIO); } static void fw_init_crom(struct fwohci_softc *sc) { struct crom_src *src; printf("fw_init_crom\n"); sc->crom_src_buf = (struct crom_src_buf *) malloc(sizeof(struct crom_src_buf)); if (sc->crom_src_buf == NULL) return; src = &sc->crom_src_buf->src; bzero(src, sizeof(struct crom_src)); /* BUS info sample */ src->hdr.info_len = 4; src->businfo.bus_name = CSR_BUS_NAME_IEEE1394; src->businfo.irmc = 1; src->businfo.cmc = 1; src->businfo.isc = 1; src->businfo.bmc = 1; src->businfo.pmc = 0; src->businfo.cyc_clk_acc = 100; src->businfo.max_rec = sc->maxrec; src->businfo.max_rom = MAXROM_4; #define FW_GENERATION_CHANGEABLE 2 src->businfo.generation = FW_GENERATION_CHANGEABLE; src->businfo.link_spd = sc->speed; src->businfo.eui64.hi = sc->eui.hi; src->businfo.eui64.lo = sc->eui.lo; STAILQ_INIT(&src->chunk_list); sc->crom_src = src; sc->crom_root = &sc->crom_src_buf->root; } static void fw_reset_crom(struct fwohci_softc *sc) { struct crom_src_buf *buf; struct crom_src *src; struct crom_chunk *root; printf("fw_reset\n"); if (sc->crom_src_buf == NULL) fw_init_crom(sc); buf = sc->crom_src_buf; src = sc->crom_src; root = sc->crom_root; STAILQ_INIT(&src->chunk_list); bzero(root, sizeof(struct crom_chunk)); crom_add_chunk(src, NULL, root, 0); crom_add_entry(root, CSRKEY_NCAP, 0x0083c0); /* XXX */ /* private company_id */ crom_add_entry(root, CSRKEY_VENDOR, CSRVAL_VENDOR_PRIVATE); #ifdef __DragonFly__ crom_add_simple_text(src, root, &buf->vendor, "DragonFly Project"); #else crom_add_simple_text(src, root, &buf->vendor, "FreeBSD Project"); #endif } #define ADDR_HI(x) (((x) >> 24) & 0xffffff) #define ADDR_LO(x) ((x) & 0xffffff) static void dcons_crom(struct fwohci_softc *sc) { struct crom_src_buf *buf; struct crom_src *src; struct crom_chunk *root; buf = sc->crom_src_buf; src = sc->crom_src; root = sc->crom_root; bzero(&buf->unit, sizeof(struct crom_chunk)); crom_add_chunk(src, root, &buf->unit, CROM_UDIR); crom_add_entry(&buf->unit, CSRKEY_SPEC, CSRVAL_VENDOR_PRIVATE); crom_add_simple_text(src, &buf->unit, &buf->spec, "FreeBSD"); crom_add_entry(&buf->unit, CSRKEY_VER, DCONS_CSR_VAL_VER); crom_add_simple_text(src, &buf->unit, &buf->ver, "dcons"); crom_add_entry(&buf->unit, DCONS_CSR_KEY_HI, ADDR_HI(dcons_paddr)); crom_add_entry(&buf->unit, DCONS_CSR_KEY_LO, ADDR_LO(dcons_paddr)); } void fw_crom(struct fwohci_softc *sc) { struct crom_src *src; void *newrom; fw_reset_crom(sc); dcons_crom(sc); newrom = malloc(CROMSIZE); src = &sc->crom_src_buf->src; crom_load(src, (uint32_t *)newrom, CROMSIZE); if (bcmp(newrom, sc->config_rom, CROMSIZE) != 0) { /* Bump generation and reload. */ src->businfo.generation++; /* Handle generation count wraps. */ if (src->businfo.generation < 2) src->businfo.generation = 2; /* Recalculate CRC to account for generation change. */ crom_load(src, (uint32_t *)newrom, CROMSIZE); bcopy(newrom, (void *)sc->config_rom, CROMSIZE); } free(newrom); } static int fw_busreset(struct fwohci_softc *sc) { int count; if (sc->state < FWOHCI_STATE_ENABLED) { printf("fwohci not enabled\n"); return(CMD_OK); } fw_crom(sc); fwohci_ibr(sc); count = 0; while (sc->state< FWOHCI_STATE_NORMAL) { fwohci_poll(sc); count ++; if (count > 1000) { printf("give up to wait bus initialize\n"); return (-1); } } printf("poll count = %d\n", count); return (0); } void fw_enable(void) { struct fwohci_softc *sc; int i; if (fw_initialized == 0) fw_init(); for (i = 0; i < MAX_OHCI; i ++) { sc = &fwinfo[i]; if (sc->state != FWOHCI_STATE_INIT) break; sc->config_rom = (uint32_t *) (((uint32_t)sc->config_rom_buf + (CROMSIZE - 1)) & ~(CROMSIZE - 1)); #if 0 printf("configrom: %08p %08p\n", sc->config_rom_buf, sc->config_rom); #endif if (fwohci_init(sc, 0) == 0) { sc->state = FWOHCI_STATE_ENABLED; fw_busreset(sc); } else sc->state = FWOHCI_STATE_DEAD; } } void fw_poll(void) { struct fwohci_softc *sc; int i; if (fw_initialized == 0) return; for (i = 0; i < MAX_OHCI; i ++) { sc = &fwinfo[i]; if (sc->state < FWOHCI_STATE_ENABLED) break; fwohci_poll(sc); } } #if 0 /* for debug */ static int fw_busreset_cmd(int argc, char *argv[]) { struct fwohci_softc *sc; int i; for (i = 0; i < MAX_OHCI; i ++) { sc = &fwinfo[i]; if (sc->state < FWOHCI_STATE_INIT) break; fw_busreset(sc); } return(CMD_OK); } static int fw_poll_cmd(int argc, char *argv[]) { fw_poll(); return(CMD_OK); } static int fw_enable_cmd(int argc, char *argv[]) { fw_print(0); fw_enable(); return(CMD_OK); } static int dcons_enable(int argc, char *argv[]) { dconsole.c_init(0); fw_enable(); dconsole.c_flags |= C_ACTIVEIN | C_ACTIVEOUT; return(CMD_OK); } static int dcons_read(int argc, char *argv[]) { char c; while (dconsole.c_ready()) { c = dconsole.c_in(); printf("%c", c); } printf("\r\n"); return(CMD_OK); } static int dcons_write(int argc, char *argv[]) { int len, i; if (argc < 2) return(CMD_OK); len = strlen(argv[1]); for (i = 0; i < len; i ++) dconsole.c_out(argv[1][i]); dconsole.c_out('\r'); dconsole.c_out('\n'); return(CMD_OK); } COMMAND_SET(firewire, "firewire", "enable firewire", fw_enable_cmd); COMMAND_SET(fwbusreset, "fwbusreset", "firewire busreset", fw_busreset_cmd); COMMAND_SET(fwpoll, "fwpoll", "firewire poll", fw_poll_cmd); COMMAND_SET(dcons, "dcons", "enable dcons", dcons_enable); COMMAND_SET(dread, "dread", "read from dcons", dcons_read); COMMAND_SET(dwrite, "dwrite", "write to dcons", dcons_write); #endif Index: head/sys/boot/i386/libi386/bioscd.c =================================================================== --- head/sys/boot/i386/libi386/bioscd.c (revision 308826) +++ head/sys/boot/i386/libi386/bioscd.c (revision 308827) @@ -1,447 +1,454 @@ /*- * Copyright (c) 1998 Michael Smith * Copyright (c) 2001 John H. Baldwin * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * BIOS CD device handling for CD's that have been booted off of via no * emulation booting as defined in the El Torito standard. * * Ideas and algorithms from: * * - FreeBSD libi386/biosdisk.c * */ #include #include #include #include #include #include #include #include "libi386.h" #define BIOSCD_SECSIZE 2048 #define BUFSIZE (1 * BIOSCD_SECSIZE) #define MAXBCDEV 1 /* Major numbers for devices we frontend for. */ #define ACDMAJOR 117 #define CDMAJOR 15 #ifdef DISK_DEBUG # define DEBUG(fmt, args...) printf("%s: " fmt "\n" , __func__ , ## args) #else # define DEBUG(fmt, args...) #endif struct specification_packet { u_char sp_size; u_char sp_bootmedia; u_char sp_drive; u_char sp_controller; u_int sp_lba; u_short sp_devicespec; u_short sp_buffersegment; u_short sp_loadsegment; u_short sp_sectorcount; u_short sp_cylsec; u_char sp_head; }; /* * List of BIOS devices, translation from disk unit number to * BIOS unit number. */ static struct bcinfo { int bc_unit; /* BIOS unit number */ struct specification_packet bc_sp; int bc_open; /* reference counter */ void *bc_bcache; /* buffer cache data */ } bcinfo [MAXBCDEV]; static int nbcinfo = 0; #define BC(dev) (bcinfo[(dev)->d_unit]) static int bc_read(int unit, daddr_t dblk, int blks, caddr_t dest); static int bc_init(void); static int bc_strategy(void *devdata, int flag, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize); static int bc_realstrategy(void *devdata, int flag, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize); static int bc_open(struct open_file *f, ...); static int bc_close(struct open_file *f); static int bc_print(int verbose); struct devsw bioscd = { "cd", DEVT_CD, bc_init, bc_strategy, bc_open, bc_close, noioctl, bc_print, NULL }; /* * Translate between BIOS device numbers and our private unit numbers. */ int bc_bios2unit(int biosdev) { int i; DEBUG("looking for bios device 0x%x", biosdev); for (i = 0; i < nbcinfo; i++) { DEBUG("bc unit %d is BIOS device 0x%x", i, bcinfo[i].bc_unit); if (bcinfo[i].bc_unit == biosdev) return(i); } return(-1); } int bc_unit2bios(int unit) { if ((unit >= 0) && (unit < nbcinfo)) return(bcinfo[unit].bc_unit); return(-1); } /* * We can't quiz, we have to be told what device to use, so this functoin * doesn't do anything. Instead, the loader calls bc_add() with the BIOS * device number to add. */ static int bc_init(void) { return (0); } int bc_add(int biosdev) { if (nbcinfo >= MAXBCDEV) return (-1); bcinfo[nbcinfo].bc_unit = biosdev; v86.ctl = V86_FLAGS; v86.addr = 0x13; v86.eax = 0x4b01; v86.edx = biosdev; v86.ds = VTOPSEG(&bcinfo[nbcinfo].bc_sp); v86.esi = VTOPOFF(&bcinfo[nbcinfo].bc_sp); v86int(); if ((v86.eax & 0xff00) != 0) return (-1); printf("BIOS CD is cd%d\n", nbcinfo); nbcinfo++; bcache_add_dev(nbcinfo); /* register cd device in bcache */ return(0); } /* * Print information about disks */ static int bc_print(int verbose) { char line[80]; int i, ret = 0; + if (nbcinfo == 0) + return (0); + + printf("%s devices:", bioscd.dv_name); + if ((ret = pager_output("\n")) != 0) + return (ret); + for (i = 0; i < nbcinfo; i++) { snprintf(line, sizeof(line), " cd%d: Device 0x%x\n", i, bcinfo[i].bc_sp.sp_devicespec); if ((ret = pager_output(line)) != 0) break; } return (ret); } /* * Attempt to open the disk described by (dev) for use by (f). */ static int bc_open(struct open_file *f, ...) { va_list ap; struct i386_devdesc *dev; va_start(ap, f); dev = va_arg(ap, struct i386_devdesc *); va_end(ap); if (dev->d_unit >= nbcinfo) { DEBUG("attempt to open nonexistent disk"); return(ENXIO); } BC(dev).bc_open++; if (BC(dev).bc_bcache == NULL) BC(dev).bc_bcache = bcache_allocate(); return(0); } static int bc_close(struct open_file *f) { struct i386_devdesc *dev; dev = (struct i386_devdesc *)f->f_devdata; BC(dev).bc_open--; if (BC(dev).bc_open == 0) { bcache_free(BC(dev).bc_bcache); BC(dev).bc_bcache = NULL; } return(0); } static int bc_strategy(void *devdata, int rw, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize) { struct bcache_devdata bcd; struct i386_devdesc *dev; dev = (struct i386_devdesc *)devdata; bcd.dv_strategy = bc_realstrategy; bcd.dv_devdata = devdata; bcd.dv_cache = BC(dev).bc_bcache; return (bcache_strategy(&bcd, rw, dblk, offset, size, buf, rsize)); } static int bc_realstrategy(void *devdata, int rw, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize) { struct i386_devdesc *dev; int unit; int blks; #ifdef BD_SUPPORT_FRAGS char fragbuf[BIOSCD_SECSIZE]; size_t fragsize; fragsize = size % BIOSCD_SECSIZE; #else if (size % BIOSCD_SECSIZE) return (EINVAL); #endif if (rw != F_READ) return(EROFS); dev = (struct i386_devdesc *)devdata; unit = dev->d_unit; blks = size / BIOSCD_SECSIZE; if (dblk % (BIOSCD_SECSIZE / DEV_BSIZE) != 0) return (EINVAL); dblk /= (BIOSCD_SECSIZE / DEV_BSIZE); DEBUG("read %d from %lld to %p", blks, dblk, buf); if (rsize) *rsize = 0; if ((blks = bc_read(unit, dblk, blks, buf)) < 0) { DEBUG("read error"); return (EIO); } else { if (size / BIOSCD_SECSIZE > blks) { if (rsize) *rsize = blks * BIOSCD_SECSIZE; return (0); } } #ifdef BD_SUPPORT_FRAGS DEBUG("frag read %d from %lld+%d to %p", fragsize, dblk, blks, buf + (blks * BIOSCD_SECSIZE)); if (fragsize && bc_read(unit, dblk + blks, 1, fragbuf) != 1) { if (blks) { if (rsize) *rsize = blks * BIOSCD_SECSIZE; return (0); } DEBUG("frag read error"); return(EIO); } bcopy(fragbuf, buf + (blks * BIOSCD_SECSIZE), fragsize); #endif if (rsize) *rsize = size; return (0); } /* Max number of sectors to bounce-buffer at a time. */ #define CD_BOUNCEBUF 8 /* return negative value for an error, otherwise blocks read */ static int bc_read(int unit, daddr_t dblk, int blks, caddr_t dest) { u_int maxfer, resid, result, retry, x; caddr_t bbuf, p, xp; static struct edd_packet packet; int biosdev; #ifdef DISK_DEBUG int error; #endif /* Just in case some idiot actually tries to read -1 blocks... */ if (blks < 0) return (-1); /* If nothing to do, just return succcess. */ if (blks == 0) return (0); /* Decide whether we have to bounce */ if (VTOP(dest) >> 20 != 0) { /* * The destination buffer is above first 1MB of * physical memory so we have to arrange a suitable * bounce buffer. */ x = min(CD_BOUNCEBUF, (unsigned)blks); bbuf = alloca(x * BIOSCD_SECSIZE); maxfer = x; } else { bbuf = NULL; maxfer = 0; } biosdev = bc_unit2bios(unit); resid = blks; p = dest; while (resid > 0) { if (bbuf) xp = bbuf; else xp = p; x = resid; if (maxfer > 0) x = min(x, maxfer); /* * Loop retrying the operation a couple of times. The BIOS * may also retry. */ for (retry = 0; retry < 3; retry++) { /* If retrying, reset the drive */ if (retry > 0) { v86.ctl = V86_FLAGS; v86.addr = 0x13; v86.eax = 0; v86.edx = biosdev; v86int(); } packet.len = sizeof(struct edd_packet); packet.count = x; packet.off = VTOPOFF(xp); packet.seg = VTOPSEG(xp); packet.lba = dblk; v86.ctl = V86_FLAGS; v86.addr = 0x13; v86.eax = 0x4200; v86.edx = biosdev; v86.ds = VTOPSEG(&packet); v86.esi = VTOPOFF(&packet); v86int(); result = V86_CY(v86.efl); if (result == 0) break; /* fall back to 1 sector read */ x = 1; } #ifdef DISK_DEBUG error = (v86.eax >> 8) & 0xff; #endif DEBUG("%d sectors from %lld to %p (0x%x) %s", x, dblk, p, VTOP(p), result ? "failed" : "ok"); DEBUG("unit %d status 0x%x", unit, error); /* still an error? break off */ if (result != 0) break; if (bbuf != NULL) bcopy(bbuf, p, x * BIOSCD_SECSIZE); p += (x * BIOSCD_SECSIZE); dblk += x; resid -= x; } /* hexdump(dest, (blks * BIOSCD_SECSIZE)); */ if (blks - resid == 0) return (-1); /* read failed */ return (blks - resid); } /* * Return a suitable dev_t value for (dev). */ int bc_getdev(struct i386_devdesc *dev) { int biosdev, unit; int major; int rootdev; unit = dev->d_unit; biosdev = bc_unit2bios(unit); DEBUG("unit %d BIOS device %d", unit, biosdev); if (biosdev == -1) /* not a BIOS device */ return(-1); /* * XXX: Need to examine device spec here to figure out if SCSI or * ATAPI. No idea on how to figure out device number. All we can * really pass to the kernel is what bus and device on which bus we * were booted from, which dev_t isn't well suited to since those * number don't match to unit numbers very well. We may just need * to engage in a hack where we pass -C to the boot args if we are * the boot device. */ major = ACDMAJOR; unit = 0; /* XXX */ /* XXX: Assume partition 'a'. */ rootdev = MAKEBOOTDEV(major, 0, unit, 0); DEBUG("dev is 0x%x\n", rootdev); return(rootdev); } Index: head/sys/boot/i386/libi386/biosdisk.c =================================================================== --- head/sys/boot/i386/libi386/biosdisk.c (revision 308826) +++ head/sys/boot/i386/libi386/biosdisk.c (revision 308827) @@ -1,939 +1,946 @@ /*- * Copyright (c) 1998 Michael Smith * Copyright (c) 2012 Andrey V. Elsukov * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * BIOS disk device handling. * * Ideas and algorithms from: * * - NetBSD libi386/biosdisk.c * - FreeBSD biosboot/disk.c * */ #include #include #include #include #include #include #include #include "disk.h" #include "libi386.h" #ifdef LOADER_GELI_SUPPORT #include "cons.h" #include "drv.h" #include "gpt.h" #include "part.h" #include struct pentry { struct ptable_entry part; uint64_t flags; union { uint8_t bsd; uint8_t mbr; uuid_t gpt; uint16_t vtoc8; } type; STAILQ_ENTRY(pentry) entry; }; struct ptable { enum ptable_type type; uint16_t sectorsize; uint64_t sectors; STAILQ_HEAD(, pentry) entries; }; #include "geliboot.c" #endif /* LOADER_GELI_SUPPORT */ CTASSERT(sizeof(struct i386_devdesc) >= sizeof(struct disk_devdesc)); #define BIOS_NUMDRIVES 0x475 #define BIOSDISK_SECSIZE 512 #define BUFSIZE (1 * BIOSDISK_SECSIZE) #define DT_ATAPI 0x10 /* disk type for ATAPI floppies */ #define WDMAJOR 0 /* major numbers for devices we frontend for */ #define WFDMAJOR 1 #define FDMAJOR 2 #define DAMAJOR 4 #ifdef DISK_DEBUG # define DEBUG(fmt, args...) printf("%s: " fmt "\n" , __func__ , ## args) #else # define DEBUG(fmt, args...) #endif /* * List of BIOS devices, translation from disk unit number to * BIOS unit number. */ static struct bdinfo { int bd_unit; /* BIOS unit number */ int bd_cyl; /* BIOS geometry */ int bd_hds; int bd_sec; int bd_flags; #define BD_MODEINT13 0x0000 #define BD_MODEEDD1 0x0001 #define BD_MODEEDD3 0x0002 #define BD_MODEMASK 0x0003 #define BD_FLOPPY 0x0004 int bd_type; /* BIOS 'drive type' (floppy only) */ uint16_t bd_sectorsize; /* Sector size */ uint64_t bd_sectors; /* Disk size */ int bd_open; /* reference counter */ void *bd_bcache; /* buffer cache data */ } bdinfo [MAXBDDEV]; static int nbdinfo = 0; #define BD(dev) (bdinfo[(dev)->d_unit]) static int bd_read(struct disk_devdesc *dev, daddr_t dblk, int blks, caddr_t dest); static int bd_write(struct disk_devdesc *dev, daddr_t dblk, int blks, caddr_t dest); static int bd_int13probe(struct bdinfo *bd); static int bd_init(void); static int bd_strategy(void *devdata, int flag, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize); static int bd_realstrategy(void *devdata, int flag, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize); static int bd_open(struct open_file *f, ...); static int bd_close(struct open_file *f); static int bd_ioctl(struct open_file *f, u_long cmd, void *data); static int bd_print(int verbose); static void bd_cleanup(void); #ifdef LOADER_GELI_SUPPORT static enum isgeli { ISGELI_UNKNOWN, ISGELI_NO, ISGELI_YES }; static enum isgeli geli_status[MAXBDDEV][MAXTBLENTS]; int bios_read(void *vdev __unused, struct dsk *priv, off_t off, char *buf, size_t bytes); #endif /* LOADER_GELI_SUPPORT */ struct devsw biosdisk = { "disk", DEVT_DISK, bd_init, bd_strategy, bd_open, bd_close, bd_ioctl, bd_print, bd_cleanup }; /* * Translate between BIOS device numbers and our private unit numbers. */ int bd_bios2unit(int biosdev) { int i; DEBUG("looking for bios device 0x%x", biosdev); for (i = 0; i < nbdinfo; i++) { DEBUG("bd unit %d is BIOS device 0x%x", i, bdinfo[i].bd_unit); if (bdinfo[i].bd_unit == biosdev) return (i); } return (-1); } int bd_unit2bios(int unit) { if ((unit >= 0) && (unit < nbdinfo)) return (bdinfo[unit].bd_unit); return (-1); } /* * Quiz the BIOS for disk devices, save a little info about them. */ static int bd_init(void) { int base, unit, nfd = 0; #ifdef LOADER_GELI_SUPPORT geli_init(); #endif /* sequence 0, 0x80 */ for (base = 0; base <= 0x80; base += 0x80) { for (unit = base; (nbdinfo < MAXBDDEV); unit++) { #ifndef VIRTUALBOX /* * Check the BIOS equipment list for number * of fixed disks. */ if(base == 0x80 && (nfd >= *(unsigned char *)PTOV(BIOS_NUMDRIVES))) break; #endif bdinfo[nbdinfo].bd_open = 0; bdinfo[nbdinfo].bd_bcache = NULL; bdinfo[nbdinfo].bd_unit = unit; bdinfo[nbdinfo].bd_flags = unit < 0x80 ? BD_FLOPPY: 0; if (!bd_int13probe(&bdinfo[nbdinfo])) break; /* XXX we need "disk aliases" to make this simpler */ printf("BIOS drive %c: is disk%d\n", (unit < 0x80) ? ('A' + unit): ('C' + unit - 0x80), nbdinfo); nbdinfo++; if (base == 0x80) nfd++; } } bcache_add_dev(nbdinfo); return(0); } static void bd_cleanup(void) { disk_cleanup(&biosdisk); } /* * Try to detect a device supported by the legacy int13 BIOS */ static int bd_int13probe(struct bdinfo *bd) { struct edd_params params; int ret = 1; /* assume success */ v86.ctl = V86_FLAGS; v86.addr = 0x13; v86.eax = 0x800; v86.edx = bd->bd_unit; v86int(); /* Don't error out if we get bad sector number, try EDD as well */ if (V86_CY(v86.efl) || /* carry set */ (v86.edx & 0xff) <= (unsigned)(bd->bd_unit & 0x7f)) /* unit # bad */ return (0); /* skip device */ if ((v86.ecx & 0x3f) == 0) /* absurd sector number */ ret = 0; /* set error */ /* Convert max cyl # -> # of cylinders */ bd->bd_cyl = ((v86.ecx & 0xc0) << 2) + ((v86.ecx & 0xff00) >> 8) + 1; /* Convert max head # -> # of heads */ bd->bd_hds = ((v86.edx & 0xff00) >> 8) + 1; bd->bd_sec = v86.ecx & 0x3f; bd->bd_type = v86.ebx & 0xff; bd->bd_flags |= BD_MODEINT13; /* Calculate sectors count from the geometry */ bd->bd_sectors = bd->bd_cyl * bd->bd_hds * bd->bd_sec; bd->bd_sectorsize = BIOSDISK_SECSIZE; DEBUG("unit 0x%x geometry %d/%d/%d", bd->bd_unit, bd->bd_cyl, bd->bd_hds, bd->bd_sec); /* Determine if we can use EDD with this device. */ v86.ctl = V86_FLAGS; v86.addr = 0x13; v86.eax = 0x4100; v86.edx = bd->bd_unit; v86.ebx = 0x55aa; v86int(); if (V86_CY(v86.efl) || /* carry set */ (v86.ebx & 0xffff) != 0xaa55 || /* signature */ (v86.ecx & EDD_INTERFACE_FIXED_DISK) == 0) return (ret); /* return code from int13 AH=08 */ /* EDD supported */ bd->bd_flags |= BD_MODEEDD1; if ((v86.eax & 0xff00) >= 0x3000) bd->bd_flags |= BD_MODEEDD3; /* Get disk params */ params.len = sizeof(struct edd_params); v86.ctl = V86_FLAGS; v86.addr = 0x13; v86.eax = 0x4800; v86.edx = bd->bd_unit; v86.ds = VTOPSEG(¶ms); v86.esi = VTOPOFF(¶ms); v86int(); if (!V86_CY(v86.efl)) { uint64_t total; if (params.sectors != 0) bd->bd_sectors = params.sectors; total = (uint64_t)params.cylinders * params.heads * params.sectors_per_track; if (bd->bd_sectors < total) bd->bd_sectors = total; bd->bd_sectorsize = params.sector_size; ret = 1; } DEBUG("unit 0x%x flags %x, sectors %llu, sectorsize %u", bd->bd_unit, bd->bd_flags, bd->bd_sectors, bd->bd_sectorsize); return (ret); } /* * Print information about disks */ static int bd_print(int verbose) { static char line[80]; struct disk_devdesc dev; int i, ret = 0; + if (nbdinfo == 0) + return (0); + + printf("%s devices:", biosdisk.dv_name); + if ((ret = pager_output("\n")) != 0) + return (ret); + for (i = 0; i < nbdinfo; i++) { snprintf(line, sizeof(line), " disk%d: BIOS drive %c (%ju X %u):\n", i, (bdinfo[i].bd_unit < 0x80) ? ('A' + bdinfo[i].bd_unit): ('C' + bdinfo[i].bd_unit - 0x80), (uintmax_t)bdinfo[i].bd_sectors, bdinfo[i].bd_sectorsize); if ((ret = pager_output(line)) != 0) break; dev.d_dev = &biosdisk; dev.d_unit = i; dev.d_slice = -1; dev.d_partition = -1; if (disk_open(&dev, bdinfo[i].bd_sectorsize * bdinfo[i].bd_sectors, bdinfo[i].bd_sectorsize, (bdinfo[i].bd_flags & BD_FLOPPY) ? DISK_F_NOCACHE: 0) == 0) { snprintf(line, sizeof(line), " disk%d", i); ret = disk_print(&dev, line, verbose); disk_close(&dev); if (ret != 0) return (ret); } } return (ret); } /* * Attempt to open the disk described by (dev) for use by (f). * * Note that the philosophy here is "give them exactly what * they ask for". This is necessary because being too "smart" * about what the user might want leads to complications. * (eg. given no slice or partition value, with a disk that is * sliced - are they after the first BSD slice, or the DOS * slice before it?) */ static int bd_open(struct open_file *f, ...) { struct disk_devdesc *dev, rdev; int err, g_err; va_list ap; va_start(ap, f); dev = va_arg(ap, struct disk_devdesc *); va_end(ap); if (dev->d_unit < 0 || dev->d_unit >= nbdinfo) return (EIO); BD(dev).bd_open++; if (BD(dev).bd_bcache == NULL) BD(dev).bd_bcache = bcache_allocate(); err = disk_open(dev, BD(dev).bd_sectors * BD(dev).bd_sectorsize, BD(dev).bd_sectorsize, (BD(dev).bd_flags & BD_FLOPPY) ? DISK_F_NOCACHE: 0); #ifdef LOADER_GELI_SUPPORT static char gelipw[GELI_PW_MAXLEN]; char *passphrase; if (err) return (err); /* if we already know there is no GELI, skip the rest */ if (geli_status[dev->d_unit][dev->d_slice] != ISGELI_UNKNOWN) return (err); struct dsk dskp; struct ptable *table = NULL; struct ptable_entry part; struct pentry *entry; int geli_part = 0; dskp.drive = bd_unit2bios(dev->d_unit); dskp.type = dev->d_type; dskp.unit = dev->d_unit; dskp.slice = dev->d_slice; dskp.part = dev->d_partition; dskp.start = dev->d_offset; memcpy(&rdev, dev, sizeof(rdev)); /* to read the GPT table, we need to read the first sector */ rdev.d_offset = 0; /* We need the LBA of the end of the partition */ table = ptable_open(&rdev, BD(dev).bd_sectors, BD(dev).bd_sectorsize, ptblread); if (table == NULL) { DEBUG("Can't read partition table"); /* soft failure, return the exit status of disk_open */ return (err); } if (table->type == PTABLE_GPT) dskp.part = 255; STAILQ_FOREACH(entry, &table->entries, entry) { dskp.slice = entry->part.index; dskp.start = entry->part.start; if (is_geli(&dskp) == 0) { geli_status[dev->d_unit][dskp.slice] = ISGELI_YES; return (0); } if (geli_taste(bios_read, &dskp, entry->part.end - entry->part.start) == 0) { if ((passphrase = getenv("kern.geom.eli.passphrase")) != NULL) { /* Use the cached passphrase */ bcopy(passphrase, &gelipw, GELI_PW_MAXLEN); } if (geli_passphrase(&gelipw, dskp.unit, 'p', (dskp.slice > 0 ? dskp.slice : dskp.part), &dskp) == 0) { setenv("kern.geom.eli.passphrase", &gelipw, 1); bzero(gelipw, sizeof(gelipw)); geli_status[dev->d_unit][dskp.slice] = ISGELI_YES; geli_part++; } } else geli_status[dev->d_unit][dskp.slice] = ISGELI_NO; } /* none of the partitions on this disk have GELI */ if (geli_part == 0) { /* found no GELI */ geli_status[dev->d_unit][dev->d_slice] = ISGELI_NO; } #endif /* LOADER_GELI_SUPPORT */ return (err); } static int bd_close(struct open_file *f) { struct disk_devdesc *dev; dev = (struct disk_devdesc *)f->f_devdata; BD(dev).bd_open--; if (BD(dev).bd_open == 0) { bcache_free(BD(dev).bd_bcache); BD(dev).bd_bcache = NULL; } return (disk_close(dev)); } static int bd_ioctl(struct open_file *f, u_long cmd, void *data) { struct disk_devdesc *dev; dev = (struct disk_devdesc *)f->f_devdata; switch (cmd) { case DIOCGSECTORSIZE: *(u_int *)data = BD(dev).bd_sectorsize; break; case DIOCGMEDIASIZE: *(off_t *)data = BD(dev).bd_sectors * BD(dev).bd_sectorsize; break; default: return (ENOTTY); } return (0); } static int bd_strategy(void *devdata, int rw, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize) { struct bcache_devdata bcd; struct disk_devdesc *dev; dev = (struct disk_devdesc *)devdata; bcd.dv_strategy = bd_realstrategy; bcd.dv_devdata = devdata; bcd.dv_cache = BD(dev).bd_bcache; return (bcache_strategy(&bcd, rw, dblk + dev->d_offset, offset, size, buf, rsize)); } static int bd_realstrategy(void *devdata, int rw, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize) { struct disk_devdesc *dev = (struct disk_devdesc *)devdata; int blks, remaining; #ifdef BD_SUPPORT_FRAGS /* XXX: sector size */ char fragbuf[BIOSDISK_SECSIZE]; size_t fragsize; fragsize = size % BIOSDISK_SECSIZE; #else if (size % BD(dev).bd_sectorsize) panic("bd_strategy: %d bytes I/O not multiple of block size", size); #endif DEBUG("open_disk %p", dev); blks = size / BD(dev).bd_sectorsize; if (rsize) *rsize = 0; /* * Perform partial read to prevent read-ahead crossing * the end of disk - or any 32 bit aliases of the end. * Signed arithmetic is used to handle wrap-around cases * like we do for TCP sequence numbers. */ remaining = (int)(BD(dev).bd_sectors - dblk); /* truncate */ if (remaining > 0 && remaining < blks) { blks = remaining; size = blks * BD(dev).bd_sectorsize; DEBUG("short read %d", blks); } switch(rw){ case F_READ: DEBUG("read %d from %lld to %p", blks, dblk, buf); if (blks && bd_read(dev, dblk, blks, buf)) { DEBUG("read error"); return (EIO); } #ifdef BD_SUPPORT_FRAGS /* XXX: sector size */ DEBUG("bd_strategy: frag read %d from %d+%d to %p", fragsize, dblk, blks, buf + (blks * BIOSDISK_SECSIZE)); if (fragsize && bd_read(od, dblk + blks, 1, fragsize)) { DEBUG("frag read error"); return(EIO); } bcopy(fragbuf, buf + (blks * BIOSDISK_SECSIZE), fragsize); #endif break; case F_WRITE : DEBUG("write %d from %d to %p", blks, dblk, buf); if (blks && bd_write(dev, dblk, blks, buf)) { DEBUG("write error"); return (EIO); } #ifdef BD_SUPPORT_FRAGS if(fragsize) { DEBUG("Attempted to write a frag"); return (EIO); } #endif break; default: /* DO NOTHING */ return (EROFS); } if (rsize) *rsize = size; return (0); } /* Max number of sectors to bounce-buffer if the request crosses a 64k boundary */ #define FLOPPY_BOUNCEBUF 18 static int bd_edd_io(struct disk_devdesc *dev, daddr_t dblk, int blks, caddr_t dest, int write) { static struct edd_packet packet; packet.len = sizeof(struct edd_packet); packet.count = blks; packet.off = VTOPOFF(dest); packet.seg = VTOPSEG(dest); packet.lba = dblk; v86.ctl = V86_FLAGS; v86.addr = 0x13; if (write) /* Should we Write with verify ?? 0x4302 ? */ v86.eax = 0x4300; else v86.eax = 0x4200; v86.edx = BD(dev).bd_unit; v86.ds = VTOPSEG(&packet); v86.esi = VTOPOFF(&packet); v86int(); return (V86_CY(v86.efl)); } static int bd_chs_io(struct disk_devdesc *dev, daddr_t dblk, int blks, caddr_t dest, int write) { u_int x, bpc, cyl, hd, sec; bpc = BD(dev).bd_sec * BD(dev).bd_hds; /* blocks per cylinder */ x = dblk; cyl = x / bpc; /* block # / blocks per cylinder */ x %= bpc; /* block offset into cylinder */ hd = x / BD(dev).bd_sec; /* offset / blocks per track */ sec = x % BD(dev).bd_sec; /* offset into track */ /* correct sector number for 1-based BIOS numbering */ sec++; if (cyl > 1023) /* CHS doesn't support cylinders > 1023. */ return (1); v86.ctl = V86_FLAGS; v86.addr = 0x13; if (write) v86.eax = 0x300 | blks; else v86.eax = 0x200 | blks; v86.ecx = ((cyl & 0xff) << 8) | ((cyl & 0x300) >> 2) | sec; v86.edx = (hd << 8) | BD(dev).bd_unit; v86.es = VTOPSEG(dest); v86.ebx = VTOPOFF(dest); v86int(); return (V86_CY(v86.efl)); } static int bd_io(struct disk_devdesc *dev, daddr_t dblk, int blks, caddr_t dest, int write) { u_int x, sec, result, resid, retry, maxfer; caddr_t p, xp, bbuf, breg; /* Just in case some idiot actually tries to read/write -1 blocks... */ if (blks < 0) return (-1); resid = blks; p = dest; /* Decide whether we have to bounce */ if (VTOP(dest) >> 20 != 0 || (BD(dev).bd_unit < 0x80 && (VTOP(dest) >> 16) != (VTOP(dest + blks * BD(dev).bd_sectorsize) >> 16))) { /* * There is a 64k physical boundary somewhere in the * destination buffer, or the destination buffer is above * first 1MB of physical memory so we have to arrange a * suitable bounce buffer. Allocate a buffer twice as large * as we need to. Use the bottom half unless there is a break * there, in which case we use the top half. */ x = min(FLOPPY_BOUNCEBUF, (unsigned)blks); bbuf = alloca(x * 2 * BD(dev).bd_sectorsize); if (((u_int32_t)VTOP(bbuf) & 0xffff0000) == ((u_int32_t)VTOP(bbuf + x * BD(dev).bd_sectorsize) & 0xffff0000)) { breg = bbuf; } else { breg = bbuf + x * BD(dev).bd_sectorsize; } maxfer = x; /* limit transfers to bounce region size */ } else { breg = bbuf = NULL; maxfer = 0; } while (resid > 0) { /* * Play it safe and don't cross track boundaries. * (XXX this is probably unnecessary) */ sec = dblk % BD(dev).bd_sec; /* offset into track */ x = min(BD(dev).bd_sec - sec, resid); if (maxfer > 0) x = min(x, maxfer); /* fit bounce buffer */ /* where do we transfer to? */ xp = bbuf == NULL ? p : breg; /* * Put your Data In, Put your Data out, * Put your Data In, and shake it all about */ if (write && bbuf != NULL) bcopy(p, breg, x * BD(dev).bd_sectorsize); /* * Loop retrying the operation a couple of times. The BIOS * may also retry. */ for (retry = 0; retry < 3; retry++) { /* if retrying, reset the drive */ if (retry > 0) { v86.ctl = V86_FLAGS; v86.addr = 0x13; v86.eax = 0; v86.edx = BD(dev).bd_unit; v86int(); } if (BD(dev).bd_flags & BD_MODEEDD1) result = bd_edd_io(dev, dblk, x, xp, write); else result = bd_chs_io(dev, dblk, x, xp, write); if (result == 0) break; } if (write) DEBUG("Write %d sector(s) from %p (0x%x) to %lld %s", x, p, VTOP(p), dblk, result ? "failed" : "ok"); else DEBUG("Read %d sector(s) from %lld to %p (0x%x) %s", x, dblk, p, VTOP(p), result ? "failed" : "ok"); if (result) { return(-1); } if (!write && bbuf != NULL) bcopy(breg, p, x * BD(dev).bd_sectorsize); p += (x * BD(dev).bd_sectorsize); dblk += x; resid -= x; } /* hexdump(dest, (blks * BD(dev).bd_sectorsize)); */ return(0); } static int bd_read(struct disk_devdesc *dev, daddr_t dblk, int blks, caddr_t dest) { #ifdef LOADER_GELI_SUPPORT struct dsk dskp; off_t p_off, diff; daddr_t alignlba; int err, n, alignblks; char *tmpbuf; /* if we already know there is no GELI, skip the rest */ if (geli_status[dev->d_unit][dev->d_slice] != ISGELI_YES) return (bd_io(dev, dblk, blks, dest, 0)); if (geli_status[dev->d_unit][dev->d_slice] == ISGELI_YES) { /* * Align reads to DEV_GELIBOOT_BSIZE bytes because partial * sectors cannot be decrypted. Round the requested LBA down to * nearest multiple of DEV_GELIBOOT_BSIZE bytes. */ alignlba = rounddown2(dblk * BD(dev).bd_sectorsize, DEV_GELIBOOT_BSIZE) / BD(dev).bd_sectorsize; /* * Round number of blocks to read up to nearest multiple of * DEV_GELIBOOT_BSIZE */ diff = (dblk - alignlba) * BD(dev).bd_sectorsize; alignblks = roundup2(blks * BD(dev).bd_sectorsize + diff, DEV_GELIBOOT_BSIZE) / BD(dev).bd_sectorsize; /* * If the read is rounded up to a larger size, use a temporary * buffer here because the buffer provided by the caller may be * too small. */ if (diff == 0) { tmpbuf = dest; } else { tmpbuf = malloc(alignblks * BD(dev).bd_sectorsize); if (tmpbuf == NULL) { return (-1); } } err = bd_io(dev, alignlba, alignblks, tmpbuf, 0); if (err) return (err); dskp.drive = bd_unit2bios(dev->d_unit); dskp.type = dev->d_type; dskp.unit = dev->d_unit; dskp.slice = dev->d_slice; dskp.part = dev->d_partition; dskp.start = dev->d_offset; /* GELI needs the offset relative to the partition start */ p_off = alignlba - dskp.start; err = geli_read(&dskp, p_off * BD(dev).bd_sectorsize, tmpbuf, alignblks * BD(dev).bd_sectorsize); if (err) return (err); if (tmpbuf != dest) { bcopy(tmpbuf + diff, dest, blks * BD(dev).bd_sectorsize); free(tmpbuf); } return (0); } #endif /* LOADER_GELI_SUPPORT */ return (bd_io(dev, dblk, blks, dest, 0)); } static int bd_write(struct disk_devdesc *dev, daddr_t dblk, int blks, caddr_t dest) { return (bd_io(dev, dblk, blks, dest, 1)); } /* * Return the BIOS geometry of a given "fixed drive" in a format * suitable for the legacy bootinfo structure. Since the kernel is * expecting raw int 0x13/0x8 values for N_BIOS_GEOM drives, we * prefer to get the information directly, rather than rely on being * able to put it together from information already maintained for * different purposes and for a probably different number of drives. * * For valid drives, the geometry is expected in the format (31..0) * "000000cc cccccccc hhhhhhhh 00ssssss"; and invalid drives are * indicated by returning the geometry of a "1.2M" PC-format floppy * disk. And, incidentally, what is returned is not the geometry as * such but the highest valid cylinder, head, and sector numbers. */ u_int32_t bd_getbigeom(int bunit) { v86.ctl = V86_FLAGS; v86.addr = 0x13; v86.eax = 0x800; v86.edx = 0x80 + bunit; v86int(); if (V86_CY(v86.efl)) return 0x4f010f; return ((v86.ecx & 0xc0) << 18) | ((v86.ecx & 0xff00) << 8) | (v86.edx & 0xff00) | (v86.ecx & 0x3f); } /* * Return a suitable dev_t value for (dev). * * In the case where it looks like (dev) is a SCSI disk, we allow the number of * IDE disks to be specified in $num_ide_disks. There should be a Better Way. */ int bd_getdev(struct i386_devdesc *d) { struct disk_devdesc *dev; int biosdev; int major; int rootdev; char *nip, *cp; int i, unit; dev = (struct disk_devdesc *)d; biosdev = bd_unit2bios(dev->d_unit); DEBUG("unit %d BIOS device %d", dev->d_unit, biosdev); if (biosdev == -1) /* not a BIOS device */ return(-1); if (disk_open(dev, BD(dev).bd_sectors * BD(dev).bd_sectorsize, BD(dev).bd_sectorsize,(BD(dev).bd_flags & BD_FLOPPY) ? DISK_F_NOCACHE: 0) != 0) /* oops, not a viable device */ return (-1); else disk_close(dev); if (biosdev < 0x80) { /* floppy (or emulated floppy) or ATAPI device */ if (bdinfo[dev->d_unit].bd_type == DT_ATAPI) { /* is an ATAPI disk */ major = WFDMAJOR; } else { /* is a floppy disk */ major = FDMAJOR; } } else { /* assume an IDE disk */ major = WDMAJOR; } /* default root disk unit number */ unit = biosdev & 0x7f; /* XXX a better kludge to set the root disk unit number */ if ((nip = getenv("root_disk_unit")) != NULL) { i = strtol(nip, &cp, 0); /* check for parse error */ if ((cp != nip) && (*cp == 0)) unit = i; } rootdev = MAKEBOOTDEV(major, dev->d_slice + 1, unit, dev->d_partition); DEBUG("dev is 0x%x\n", rootdev); return(rootdev); } #ifdef LOADER_GELI_SUPPORT int bios_read(void *vdev __unused, struct dsk *priv, off_t off, char *buf, size_t bytes) { struct disk_devdesc dev; dev.d_dev = &biosdisk; dev.d_type = priv->type; dev.d_unit = priv->unit; dev.d_slice = priv->slice; dev.d_partition = priv->part; dev.d_offset = priv->start; off = off / BD(&dev).bd_sectorsize; /* GELI gives us the offset relative to the partition start */ off += dev.d_offset; bytes = bytes / BD(&dev).bd_sectorsize; return (bd_io(&dev, off, bytes, buf, 0)); } #endif /* LOADER_GELI_SUPPORT */ Index: head/sys/boot/i386/libi386/pxe.c =================================================================== --- head/sys/boot/i386/libi386/pxe.c (revision 308826) +++ head/sys/boot/i386/libi386/pxe.c (revision 308827) @@ -1,724 +1,727 @@ /*- * Copyright (c) 2000 Alfred Perlstein * Copyright (c) 2000 Paul Saab * Copyright (c) 2000 John Baldwin * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include "btxv86.h" #include "pxe.h" /* * Allocate the PXE buffers statically instead of sticking grimy fingers into * BTX's private data area. The scratch buffer is used to send information to * the PXE BIOS, and the data buffer is used to receive data from the PXE BIOS. */ #define PXE_BUFFER_SIZE 0x2000 #define PXE_TFTP_BUFFER_SIZE 512 static char scratch_buffer[PXE_BUFFER_SIZE]; static char data_buffer[PXE_BUFFER_SIZE]; static pxenv_t *pxenv_p = NULL; /* PXENV+ */ static pxe_t *pxe_p = NULL; /* !PXE */ static BOOTPLAYER bootplayer; /* PXE Cached information. */ static int pxe_debug = 0; static int pxe_sock = -1; static int pxe_opens = 0; void pxe_enable(void *pxeinfo); static void (*pxe_call)(int func); static void pxenv_call(int func); static void bangpxe_call(int func); static int pxe_init(void); static int pxe_strategy(void *devdata, int flag, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize); static int pxe_open(struct open_file *f, ...); static int pxe_close(struct open_file *f); static int pxe_print(int verbose); static void pxe_cleanup(void); static void pxe_setnfshandle(char *rootpath); static void pxe_perror(int error); static int pxe_netif_match(struct netif *nif, void *machdep_hint); static int pxe_netif_probe(struct netif *nif, void *machdep_hint); static void pxe_netif_init(struct iodesc *desc, void *machdep_hint); static int pxe_netif_get(struct iodesc *desc, void *pkt, size_t len, time_t timeout); static int pxe_netif_put(struct iodesc *desc, void *pkt, size_t len); static void pxe_netif_end(struct netif *nif); #ifdef OLD_NFSV2 int nfs_getrootfh(struct iodesc*, char*, u_char*); #else int nfs_getrootfh(struct iodesc*, char*, uint32_t*, u_char*); #endif extern struct netif_stats pxe_st[]; extern u_int16_t __bangpxeseg; extern u_int16_t __bangpxeoff; extern void __bangpxeentry(void); extern u_int16_t __pxenvseg; extern u_int16_t __pxenvoff; extern void __pxenventry(void); struct netif_dif pxe_ifs[] = { /* dif_unit dif_nsel dif_stats dif_private */ {0, 1, &pxe_st[0], 0} }; struct netif_stats pxe_st[NENTS(pxe_ifs)]; struct netif_driver pxenetif = { "pxenet", pxe_netif_match, pxe_netif_probe, pxe_netif_init, pxe_netif_get, pxe_netif_put, pxe_netif_end, pxe_ifs, NENTS(pxe_ifs) }; struct netif_driver *netif_drivers[] = { &pxenetif, NULL }; struct devsw pxedisk = { "pxe", DEVT_NET, pxe_init, pxe_strategy, pxe_open, pxe_close, noioctl, pxe_print, pxe_cleanup }; /* * This function is called by the loader to enable PXE support if we * are booted by PXE. The passed in pointer is a pointer to the * PXENV+ structure. */ void pxe_enable(void *pxeinfo) { pxenv_p = (pxenv_t *)pxeinfo; pxe_p = (pxe_t *)PTOV(pxenv_p->PXEPtr.segment * 16 + pxenv_p->PXEPtr.offset); pxe_call = NULL; } /* * return true if pxe structures are found/initialized, * also figures out our IP information via the pxe cached info struct */ static int pxe_init(void) { t_PXENV_GET_CACHED_INFO *gci_p; int counter; uint8_t checksum; uint8_t *checkptr; if(pxenv_p == NULL) return (0); /* look for "PXENV+" */ if (bcmp((void *)pxenv_p->Signature, S_SIZE("PXENV+"))) { pxenv_p = NULL; return (0); } /* make sure the size is something we can handle */ if (pxenv_p->Length > sizeof(*pxenv_p)) { printf("PXENV+ structure too large, ignoring\n"); pxenv_p = NULL; return (0); } /* * do byte checksum: * add up each byte in the structure, the total should be 0 */ checksum = 0; checkptr = (uint8_t *) pxenv_p; for (counter = 0; counter < pxenv_p->Length; counter++) checksum += *checkptr++; if (checksum != 0) { printf("PXENV+ structure failed checksum, ignoring\n"); pxenv_p = NULL; return (0); } /* * PXENV+ passed, so use that if !PXE is not available or * the checksum fails. */ pxe_call = pxenv_call; if (pxenv_p->Version >= 0x0200) { for (;;) { if (bcmp((void *)pxe_p->Signature, S_SIZE("!PXE"))) { pxe_p = NULL; break; } checksum = 0; checkptr = (uint8_t *)pxe_p; for (counter = 0; counter < pxe_p->StructLength; counter++) checksum += *checkptr++; if (checksum != 0) { pxe_p = NULL; break; } pxe_call = bangpxe_call; break; } } printf("\nPXE version %d.%d, real mode entry point ", (uint8_t) (pxenv_p->Version >> 8), (uint8_t) (pxenv_p->Version & 0xFF)); if (pxe_call == bangpxe_call) printf("@%04x:%04x\n", pxe_p->EntryPointSP.segment, pxe_p->EntryPointSP.offset); else printf("@%04x:%04x\n", pxenv_p->RMEntry.segment, pxenv_p->RMEntry.offset); gci_p = (t_PXENV_GET_CACHED_INFO *) scratch_buffer; bzero(gci_p, sizeof(*gci_p)); gci_p->PacketType = PXENV_PACKET_TYPE_BINL_REPLY; pxe_call(PXENV_GET_CACHED_INFO); if (gci_p->Status != 0) { pxe_perror(gci_p->Status); pxe_p = NULL; return (0); } bcopy(PTOV((gci_p->Buffer.segment << 4) + gci_p->Buffer.offset), &bootplayer, gci_p->BufferSize); return (1); } static int pxe_strategy(void *devdata, int flag, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize) { return (EIO); } static int pxe_open(struct open_file *f, ...) { va_list args; char *devname; /* Device part of file name (or NULL). */ char temp[FNAME_SIZE]; int error = 0; int i; va_start(args, f); devname = va_arg(args, char*); va_end(args); /* On first open, do netif open, mount, etc. */ if (pxe_opens == 0) { /* Find network interface. */ if (pxe_sock < 0) { pxe_sock = netif_open(devname); if (pxe_sock < 0) { printf("pxe_open: netif_open() failed\n"); return (ENXIO); } if (pxe_debug) printf("pxe_open: netif_open() succeeded\n"); } if (rootip.s_addr == 0) { /* * Do a bootp/dhcp request to find out where our * NFS/TFTP server is. Even if we dont get back * the proper information, fall back to the server * which brought us to life and a default rootpath. */ bootp(pxe_sock, BOOTP_PXE); if (rootip.s_addr == 0) rootip.s_addr = bootplayer.sip; netproto = NET_NFS; if (tftpip.s_addr != 0) { netproto = NET_TFTP; rootip.s_addr = tftpip.s_addr; } if (netproto == NET_NFS && !rootpath[0]) strcpy(rootpath, PXENFSROOTPATH); for (i = 0; rootpath[i] != '\0' && i < FNAME_SIZE; i++) if (rootpath[i] == ':') break; if (i && i != FNAME_SIZE && rootpath[i] == ':') { rootpath[i++] = '\0'; if (inet_addr(&rootpath[0]) != INADDR_NONE) rootip.s_addr = inet_addr(&rootpath[0]); bcopy(&rootpath[i], &temp[0], strlen(&rootpath[i])+1); bcopy(&temp[0], &rootpath[0], strlen(&rootpath[i])+1); } setenv("boot.netif.ip", inet_ntoa(myip), 1); setenv("boot.netif.netmask", intoa(netmask), 1); setenv("boot.netif.gateway", inet_ntoa(gateip), 1); setenv("boot.netif.server", inet_ntoa(rootip), 1); if (bootplayer.Hardware == ETHER_TYPE) { sprintf(temp, "%6D", bootplayer.CAddr, ":"); setenv("boot.netif.hwaddr", temp, 1); } if (intf_mtu != 0) { char mtu[16]; sprintf(mtu, "%u", intf_mtu); setenv("boot.netif.mtu", mtu, 1); } printf("pxe_open: server addr: %s\n", inet_ntoa(rootip)); printf("pxe_open: server path: %s\n", rootpath); printf("pxe_open: gateway ip: %s\n", inet_ntoa(gateip)); if (netproto == NET_TFTP) { setenv("boot.tftproot.server", inet_ntoa(rootip), 1); setenv("boot.tftproot.path", rootpath, 1); } else if (netproto == NET_NFS) { setenv("boot.nfsroot.server", inet_ntoa(rootip), 1); setenv("boot.nfsroot.path", rootpath, 1); } setenv("dhcp.host-name", hostname, 1); setenv("pxeboot.ip", inet_ntoa(myip), 1); if (bootplayer.Hardware == ETHER_TYPE) { sprintf(temp, "%6D", bootplayer.CAddr, ":"); setenv("pxeboot.hwaddr", temp, 1); } } } pxe_opens++; f->f_devdata = &pxe_sock; return (error); } static int pxe_close(struct open_file *f) { #ifdef PXE_DEBUG if (pxe_debug) printf("pxe_close: opens=%d\n", pxe_opens); #endif /* On last close, do netif close, etc. */ f->f_devdata = NULL; /* Extra close call? */ if (pxe_opens <= 0) return (0); pxe_opens--; /* Not last close? */ if (pxe_opens > 0) return(0); if (netproto == NET_NFS) { /* get an NFS filehandle for our root filesystem */ pxe_setnfshandle(rootpath); } if (pxe_sock >= 0) { #ifdef PXE_DEBUG if (pxe_debug) printf("pxe_close: calling netif_close()\n"); #endif netif_close(pxe_sock); pxe_sock = -1; } return (0); } static int pxe_print(int verbose) { char line[255]; if (pxe_call == NULL) return (0); + printf("%s devices:", pxedisk.dv_name); + if (pager_output("\n") != 0) + return (1); if (verbose) { snprintf(line, sizeof(line), " pxe0: %s:%s\n", inet_ntoa(rootip), rootpath); } else { snprintf(line, sizeof(line), " pxe0:\n"); } return (pager_output(line)); } static void pxe_cleanup(void) { #ifdef PXE_DEBUG t_PXENV_UNLOAD_STACK *unload_stack_p = (t_PXENV_UNLOAD_STACK *)scratch_buffer; t_PXENV_UNDI_SHUTDOWN *undi_shutdown_p = (t_PXENV_UNDI_SHUTDOWN *)scratch_buffer; #endif if (pxe_call == NULL) return; pxe_call(PXENV_UNDI_SHUTDOWN); #ifdef PXE_DEBUG if (pxe_debug && undi_shutdown_p->Status != 0) printf("pxe_cleanup: UNDI_SHUTDOWN failed %x\n", undi_shutdown_p->Status); #endif pxe_call(PXENV_UNLOAD_STACK); #ifdef PXE_DEBUG if (pxe_debug && unload_stack_p->Status != 0) printf("pxe_cleanup: UNLOAD_STACK failed %x\n", unload_stack_p->Status); #endif } void pxe_perror(int err) { return; } /* * Reach inside the libstand NFS code and dig out an NFS handle * for the root filesystem. */ #ifdef OLD_NFSV2 struct nfs_iodesc { struct iodesc *iodesc; off_t off; u_char fh[NFS_FHSIZE]; /* structure truncated here */ }; extern struct nfs_iodesc nfs_root_node; extern int rpc_port; static void pxe_rpcmountcall() { struct iodesc *d; int error; if (!(d = socktodesc(pxe_sock))) return; d->myport = htons(--rpc_port); d->destip = rootip; if ((error = nfs_getrootfh(d, rootpath, nfs_root_node.fh)) != 0) printf("NFS MOUNT RPC error: %d\n", error); nfs_root_node.iodesc = d; } static void pxe_setnfshandle(char *rootpath) { int i; u_char *fh; char buf[2 * NFS_FHSIZE + 3], *cp; /* * If NFS files were never opened, we need to do mount call * ourselves. Use nfs_root_node.iodesc as flag indicating * previous NFS usage. */ if (nfs_root_node.iodesc == NULL) pxe_rpcmountcall(); fh = &nfs_root_node.fh[0]; buf[0] = 'X'; cp = &buf[1]; for (i = 0; i < NFS_FHSIZE; i++, cp += 2) sprintf(cp, "%02x", fh[i]); sprintf(cp, "X"); setenv("boot.nfsroot.nfshandle", buf, 1); } #else /* !OLD_NFSV2 */ #define NFS_V3MAXFHSIZE 64 struct nfs_iodesc { struct iodesc *iodesc; off_t off; uint32_t fhsize; u_char fh[NFS_V3MAXFHSIZE]; /* structure truncated */ }; extern struct nfs_iodesc nfs_root_node; extern int rpc_port; static void pxe_rpcmountcall() { struct iodesc *d; int error; if (!(d = socktodesc(pxe_sock))) return; d->myport = htons(--rpc_port); d->destip = rootip; if ((error = nfs_getrootfh(d, rootpath, &nfs_root_node.fhsize, nfs_root_node.fh)) != 0) { printf("NFS MOUNT RPC error: %d\n", error); nfs_root_node.fhsize = 0; } nfs_root_node.iodesc = d; } static void pxe_setnfshandle(char *rootpath) { int i; u_char *fh; char buf[2 * NFS_V3MAXFHSIZE + 3], *cp; /* * If NFS files were never opened, we need to do mount call * ourselves. Use nfs_root_node.iodesc as flag indicating * previous NFS usage. */ if (nfs_root_node.iodesc == NULL) pxe_rpcmountcall(); fh = &nfs_root_node.fh[0]; buf[0] = 'X'; cp = &buf[1]; for (i = 0; i < nfs_root_node.fhsize; i++, cp += 2) sprintf(cp, "%02x", fh[i]); sprintf(cp, "X"); setenv("boot.nfsroot.nfshandle", buf, 1); sprintf(buf, "%d", nfs_root_node.fhsize); setenv("boot.nfsroot.nfshandlelen", buf, 1); } #endif /* OLD_NFSV2 */ void pxenv_call(int func) { #ifdef PXE_DEBUG if (pxe_debug) printf("pxenv_call %x\n", func); #endif bzero(&v86, sizeof(v86)); bzero(data_buffer, sizeof(data_buffer)); __pxenvseg = pxenv_p->RMEntry.segment; __pxenvoff = pxenv_p->RMEntry.offset; v86.ctl = V86_ADDR | V86_CALLF | V86_FLAGS; v86.es = VTOPSEG(scratch_buffer); v86.edi = VTOPOFF(scratch_buffer); v86.addr = (VTOPSEG(__pxenventry) << 16) | VTOPOFF(__pxenventry); v86.ebx = func; v86int(); v86.ctl = V86_FLAGS; } void bangpxe_call(int func) { #ifdef PXE_DEBUG if (pxe_debug) printf("bangpxe_call %x\n", func); #endif bzero(&v86, sizeof(v86)); bzero(data_buffer, sizeof(data_buffer)); __bangpxeseg = pxe_p->EntryPointSP.segment; __bangpxeoff = pxe_p->EntryPointSP.offset; v86.ctl = V86_ADDR | V86_CALLF | V86_FLAGS; v86.edx = VTOPSEG(scratch_buffer); v86.eax = VTOPOFF(scratch_buffer); v86.addr = (VTOPSEG(__bangpxeentry) << 16) | VTOPOFF(__bangpxeentry); v86.ebx = func; v86int(); v86.ctl = V86_FLAGS; } time_t getsecs(void) { time_t n = 0; time(&n); return n; } static int pxe_netif_match(struct netif *nif, void *machdep_hint) { return 1; } static int pxe_netif_probe(struct netif *nif, void *machdep_hint) { t_PXENV_UDP_OPEN *udpopen_p = (t_PXENV_UDP_OPEN *)scratch_buffer; if (pxe_call == NULL) return -1; bzero(udpopen_p, sizeof(*udpopen_p)); udpopen_p->src_ip = bootplayer.yip; pxe_call(PXENV_UDP_OPEN); if (udpopen_p->status != 0) { printf("pxe_netif_probe: failed %x\n", udpopen_p->status); return -1; } return 0; } static void pxe_netif_end(struct netif *nif) { t_PXENV_UDP_CLOSE *udpclose_p = (t_PXENV_UDP_CLOSE *)scratch_buffer; bzero(udpclose_p, sizeof(*udpclose_p)); pxe_call(PXENV_UDP_CLOSE); if (udpclose_p->status != 0) printf("pxe_end failed %x\n", udpclose_p->status); } static void pxe_netif_init(struct iodesc *desc, void *machdep_hint) { int i; for (i = 0; i < 6; ++i) desc->myea[i] = bootplayer.CAddr[i]; desc->xid = bootplayer.ident; } static int pxe_netif_get(struct iodesc *desc, void *pkt, size_t len, time_t timeout) { return len; } static int pxe_netif_put(struct iodesc *desc, void *pkt, size_t len) { return len; } ssize_t sendudp(struct iodesc *h, void *pkt, size_t len) { t_PXENV_UDP_WRITE *udpwrite_p = (t_PXENV_UDP_WRITE *)scratch_buffer; bzero(udpwrite_p, sizeof(*udpwrite_p)); udpwrite_p->ip = h->destip.s_addr; udpwrite_p->dst_port = h->destport; udpwrite_p->src_port = h->myport; udpwrite_p->buffer_size = len; udpwrite_p->buffer.segment = VTOPSEG(pkt); udpwrite_p->buffer.offset = VTOPOFF(pkt); if (netmask == 0 || SAMENET(myip, h->destip, netmask)) udpwrite_p->gw = 0; else udpwrite_p->gw = gateip.s_addr; pxe_call(PXENV_UDP_WRITE); #if 0 /* XXX - I dont know why we need this. */ delay(1000); #endif if (udpwrite_p->status != 0) { /* XXX: This happens a lot. It shouldn't. */ if (udpwrite_p->status != 1) printf("sendudp failed %x\n", udpwrite_p->status); return -1; } return len; } ssize_t readudp(struct iodesc *h, void *pkt, size_t len, time_t timeout) { t_PXENV_UDP_READ *udpread_p = (t_PXENV_UDP_READ *)scratch_buffer; struct udphdr *uh = NULL; uh = (struct udphdr *) pkt - 1; bzero(udpread_p, sizeof(*udpread_p)); udpread_p->dest_ip = h->myip.s_addr; udpread_p->d_port = h->myport; udpread_p->buffer_size = len; udpread_p->buffer.segment = VTOPSEG(data_buffer); udpread_p->buffer.offset = VTOPOFF(data_buffer); pxe_call(PXENV_UDP_READ); #if 0 /* XXX - I dont know why we need this. */ delay(1000); #endif if (udpread_p->status != 0) { /* XXX: This happens a lot. It shouldn't. */ if (udpread_p->status != 1) printf("readudp failed %x\n", udpread_p->status); return -1; } bcopy(data_buffer, pkt, udpread_p->buffer_size); uh->uh_sport = udpread_p->s_port; return udpread_p->buffer_size; } Index: head/sys/boot/mips/beri/loader/beri_disk_cfi.c =================================================================== --- head/sys/boot/mips/beri/loader/beri_disk_cfi.c (revision 308826) +++ head/sys/boot/mips/beri/loader/beri_disk_cfi.c (revision 308827) @@ -1,145 +1,149 @@ /*- * Copyright (c) 2013-2014 Robert N. M. Watson * All rights reserved. * * This software was developed by SRI International and the University of * Cambridge Computer Laboratory under DARPA/AFRL contract (FA8750-10-C-0237) * ("CTSRD"), as part of the DARPA CRASH research programme. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include static int beri_cfi_disk_init(void); static int beri_cfi_disk_open(struct open_file *, ...); static int beri_cfi_disk_close(struct open_file *); static void beri_cfi_disk_cleanup(void); static int beri_cfi_disk_strategy(void *, int, daddr_t, size_t, size_t, char *, size_t *); static int beri_cfi_disk_print(int); struct devsw beri_cfi_disk = { .dv_name = "cfi", .dv_type = DEVT_DISK, .dv_init = beri_cfi_disk_init, .dv_strategy = beri_cfi_disk_strategy, .dv_open = beri_cfi_disk_open, .dv_close = beri_cfi_disk_close, .dv_ioctl = noioctl, .dv_print = beri_cfi_disk_print, .dv_cleanup = beri_cfi_disk_cleanup, }; static int beri_cfi_disk_init(void) { return (0); } static int beri_cfi_disk_strategy(void *devdata, int flag, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsizep) { int error; if (flag == F_WRITE) return (EROFS); if (flag != F_READ) return (EINVAL); if (rsizep != NULL) *rsizep = 0; error = cfi_read(buf, dblk, size >> 9); if (error == 0 && rsizep != NULL) *rsizep = size; else if (error != 0) printf("%s: error %d\n", __func__, error); return (error); } static int beri_cfi_disk_open(struct open_file *f, ...) { va_list ap; struct disk_devdesc *dev; va_start(ap, f); dev = va_arg(ap, struct disk_devdesc *); va_end(ap); if (dev->d_unit != 0) return (EIO); return (disk_open(dev, cfi_get_mediasize(), cfi_get_sectorsize(), 0)); } static int beri_cfi_disk_close(struct open_file *f) { struct disk_devdesc *dev; dev = (struct disk_devdesc *)f->f_devdata; return (disk_close(dev)); } static int beri_cfi_disk_print(int verbose) { struct disk_devdesc dev; char line[80]; int ret; + printf("%s devices:", beri_cfi_disk.dv_name); + if ((ret = pager_output("\n")) != 0) + return (ret); + snprintf(line, sizeof(line), " cfi%d CFI flash device\n", 0); ret = pager_output(line); if (ret != 0) return (ret); dev.d_dev = &beri_cfi_disk; dev.d_unit = 0; dev.d_slice = -1; dev.d_partition = -1; if (disk_open(&dev, cfi_get_mediasize(), cfi_get_sectorsize(), 0) == 0) { snprintf(line, sizeof(line), " cfi%d", 0); ret = disk_print(&dev, line, verbose); disk_close(&dev); } return (ret); } static void beri_cfi_disk_cleanup(void) { disk_cleanup(&beri_cfi_disk); } Index: head/sys/boot/mips/beri/loader/beri_disk_sdcard.c =================================================================== --- head/sys/boot/mips/beri/loader/beri_disk_sdcard.c (revision 308826) +++ head/sys/boot/mips/beri/loader/beri_disk_sdcard.c (revision 308827) @@ -1,150 +1,154 @@ /*- * Copyright (c) 2013-2014 Robert N. M. Watson * All rights reserved. * * This software was developed by SRI International and the University of * Cambridge Computer Laboratory under DARPA/AFRL contract (FA8750-10-C-0237) * ("CTSRD"), as part of the DARPA CRASH research programme. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include static int beri_sdcard_disk_init(void); static int beri_sdcard_disk_open(struct open_file *, ...); static int beri_sdcard_disk_close(struct open_file *); static void beri_sdcard_disk_cleanup(void); static int beri_sdcard_disk_strategy(void *, int, daddr_t, size_t, size_t, char *, size_t *); static int beri_sdcard_disk_print(int); struct devsw beri_sdcard_disk = { .dv_name = "sdcard", .dv_type = DEVT_DISK, .dv_init = beri_sdcard_disk_init, .dv_strategy = beri_sdcard_disk_strategy, .dv_open = beri_sdcard_disk_open, .dv_close = beri_sdcard_disk_close, .dv_ioctl = noioctl, .dv_print = beri_sdcard_disk_print, .dv_cleanup = beri_sdcard_disk_cleanup, }; static int beri_sdcard_disk_init(void) { return (0); } static int beri_sdcard_disk_strategy(void *devdata, int flag, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsizep) { int error; if (flag == F_WRITE) return (EROFS); if (flag != F_READ) return (EINVAL); if (rsizep != NULL) *rsizep = 0; error = altera_sdcard_read(buf, dblk, size >> 9); if (error == 0 && rsizep != NULL) *rsizep = size; else if (error != 0) printf("%s: error %d\n", __func__, error); return (error); } static int beri_sdcard_disk_open(struct open_file *f, ...) { va_list ap; struct disk_devdesc *dev; va_start(ap, f); dev = va_arg(ap, struct disk_devdesc *); va_end(ap); if (!(altera_sdcard_get_present())) { printf("SD card not present or not supported\n"); return (ENXIO); } if (dev->d_unit != 0) return (EIO); return (disk_open(dev, altera_sdcard_get_mediasize(), altera_sdcard_get_sectorsize(), 0)); } static int beri_sdcard_disk_close(struct open_file *f) { struct disk_devdesc *dev; dev = (struct disk_devdesc *)f->f_devdata; return (disk_close(dev)); } static int beri_sdcard_disk_print(int verbose) { struct disk_devdesc dev; char line[80]; int ret; + printf("%s devices:", beri_sdcard_disk.dv_name); + if ((ret = pager_output("\n")) != 0) + return (ret); + snprintf(line, sizeof(line), " sdcard%d Altera SD card drive\n", 0); ret = pager_output(line); if (ret != 0) return (ret); dev.d_dev = &beri_sdcard_disk; dev.d_unit = 0; dev.d_slice = -1; dev.d_partition = -1; if (disk_open(&dev, altera_sdcard_get_mediasize(), altera_sdcard_get_sectorsize(), 0) == 0) { snprintf(line, sizeof(line), " sdcard%d", 0); ret = disk_print(&dev, line, verbose); disk_close(&dev); } return (ret); } static void beri_sdcard_disk_cleanup(void) { disk_cleanup(&beri_sdcard_disk); } Index: head/sys/boot/pc98/libpc98/bioscd.c =================================================================== --- head/sys/boot/pc98/libpc98/bioscd.c (revision 308826) +++ head/sys/boot/pc98/libpc98/bioscd.c (revision 308827) @@ -1,413 +1,420 @@ /*- * Copyright (c) 1998 Michael Smith * Copyright (c) 2001 John H. Baldwin * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * BIOS CD device handling for CD's that have been booted off of via no * emulation booting as defined in the El Torito standard. * * Ideas and algorithms from: * * - FreeBSD libi386/biosdisk.c * */ #include #include #include #include #include #include #include "libi386.h" #define BIOSCD_SECSIZE 2048 #define BUFSIZE (1 * BIOSCD_SECSIZE) #define MAXBCDEV 1 /* Major numbers for devices we frontend for. */ #define ACDMAJOR 117 #define CDMAJOR 15 #ifdef DISK_DEBUG # define DEBUG(fmt, args...) printf("%s: " fmt "\n" , __func__ , ## args) #else # define DEBUG(fmt, args...) #endif struct specification_packet { u_char sp_size; u_char sp_bootmedia; u_char sp_drive; u_char sp_controller; u_int sp_lba; u_short sp_devicespec; u_short sp_buffersegment; u_short sp_loadsegment; u_short sp_sectorcount; u_short sp_cylsec; u_char sp_head; }; /* * List of BIOS devices, translation from disk unit number to * BIOS unit number. */ static struct bcinfo { int bc_unit; /* BIOS unit number */ struct specification_packet bc_sp; int bc_open; /* reference counter */ void *bc_bcache; /* buffer cache data */ } bcinfo [MAXBCDEV]; static int nbcinfo = 0; #define BC(dev) (bcinfo[(dev)->d_unit]) static int bc_read(int unit, daddr_t dblk, int blks, caddr_t dest); static int bc_init(void); static int bc_strategy(void *devdata, int flag, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize); static int bc_realstrategy(void *devdata, int flag, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize); static int bc_open(struct open_file *f, ...); static int bc_close(struct open_file *f); static int bc_print(int verbose); struct devsw bioscd = { "cd", DEVT_CD, bc_init, bc_strategy, bc_open, bc_close, noioctl, bc_print, NULL }; /* * Translate between BIOS device numbers and our private unit numbers. */ int bc_bios2unit(int biosdev) { int i; DEBUG("looking for bios device 0x%x", biosdev); for (i = 0; i < nbcinfo; i++) { DEBUG("bc unit %d is BIOS device 0x%x", i, bcinfo[i].bc_unit); if (bcinfo[i].bc_unit == biosdev) return(i); } return(-1); } int bc_unit2bios(int unit) { if ((unit >= 0) && (unit < nbcinfo)) return(bcinfo[unit].bc_unit); return(-1); } /* * We can't quiz, we have to be told what device to use, so this functoin * doesn't do anything. Instead, the loader calls bc_add() with the BIOS * device number to add. */ static int bc_init(void) { return (0); } int bc_add(int biosdev) { if (nbcinfo >= MAXBCDEV) return (-1); bcinfo[nbcinfo].bc_unit = biosdev; /* SCSI CD-ROM only */ if ((biosdev & 0xf0) != 0xa0) return (-1); if ((((uint32_t *)PTOV(0xA1460))[biosdev & 0x0f] & 0x1f) != 5) return (-1); printf("BIOS CD is cd%d\n", nbcinfo); nbcinfo++; bcache_add_dev(nbcinfo); /* register cd device in bcache */ return(0); } /* * Print information about disks */ static int bc_print(int verbose) { char line[80]; int i, ret = 0; + if (nbcinfo == 0) + return (0); + + printf("%s devices:", bioscd.dv_name); + if ((ret = pager_output("\n")) != 0) + return (ret); + for (i = 0; i < nbcinfo; i++) { sprintf(line, " cd%d: Device 0x%x\n", i, bcinfo[i].bc_sp.sp_devicespec); if ((ret = pager_output(line)) != 0) break; } return (ret); } /* * Attempt to open the disk described by (dev) for use by (f). */ static int bc_open(struct open_file *f, ...) { va_list ap; struct i386_devdesc *dev; va_start(ap, f); dev = va_arg(ap, struct i386_devdesc *); va_end(ap); if (dev->d_unit >= nbcinfo) { DEBUG("attempt to open nonexistent disk"); return(ENXIO); } BC(dev).bc_open++; if (BC(dev).bc_bcache == NULL) BC(dev).bc_bcache = bcache_allocate(); return(0); } static int bc_close(struct open_file *f) { struct i386_devdesc *dev; dev = (struct i386_devdesc *)f->f_devdata; BC(dev).bc_open--; if (BC(dev).bc_open == 0) { bcache_free(BC(dev).bc_bcache); BC(dev).bc_bcache = NULL; } return(0); } static int bc_strategy(void *devdata, int rw, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize) { struct bcache_devdata bcd; struct i386_devdesc *dev; dev = (struct i386_devdesc *)devdata; bcd.dv_strategy = bc_realstrategy; bcd.dv_devdata = devdata; bcd.dv_cache = BC(dev).bc_bcache; return (bcache_strategy(&bcd, rw, dblk, offset, size, buf, rsize)); } static int bc_realstrategy(void *devdata, int rw, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize) { struct i386_devdesc *dev; int unit; int blks; #ifdef BD_SUPPORT_FRAGS char fragbuf[BIOSCD_SECSIZE]; size_t fragsize; fragsize = size % BIOSCD_SECSIZE; #else if (size % BIOSCD_SECSIZE) return (EINVAL); #endif if (rw != F_READ) return(EROFS); dev = (struct i386_devdesc *)devdata; unit = dev->d_unit; blks = size / BIOSCD_SECSIZE; if (dblk % (BIOSCD_SECSIZE / DEV_BSIZE) != 0) return (EINVAL); dblk /= (BIOSCD_SECSIZE / DEV_BSIZE); DEBUG("read %d from %lld to %p", blks, dblk, buf); if (rsize) *rsize = 0; if (blks && bc_read(unit, dblk, blks, buf)) { DEBUG("read error"); return (EIO); } #ifdef BD_SUPPORT_FRAGS DEBUG("frag read %d from %lld+%d to %p", fragsize, dblk, blks, buf + (blks * BIOSCD_SECSIZE)); if (fragsize && bc_read(unit, dblk + blks, 1, fragbuf)) { DEBUG("frag read error"); return(EIO); } bcopy(fragbuf, buf + (blks * BIOSCD_SECSIZE), fragsize); #endif if (rsize) *rsize = size; return (0); } /* Max number of sectors to bounce-buffer at a time. */ #define CD_BOUNCEBUF 8 static int bc_read(int unit, daddr_t dblk, int blks, caddr_t dest) { u_int maxfer, resid, result, retry, x; caddr_t bbuf, p, xp; int biosdev; #ifdef DISK_DEBUG int error; #endif /* Just in case some idiot actually tries to read -1 blocks... */ if (blks < 0) return (-1); /* If nothing to do, just return succcess. */ if (blks == 0) return (0); /* Decide whether we have to bounce */ if (VTOP(dest) >> 20 != 0) { /* * The destination buffer is above first 1MB of * physical memory so we have to arrange a suitable * bounce buffer. */ x = min(CD_BOUNCEBUF, (unsigned)blks); bbuf = alloca(x * BIOSCD_SECSIZE); maxfer = x; } else { bbuf = NULL; maxfer = 0; } biosdev = bc_unit2bios(unit); resid = blks; p = dest; while (resid > 0) { if (bbuf) xp = bbuf; else xp = p; x = resid; if (maxfer > 0) x = min(x, maxfer); /* * Loop retrying the operation a couple of times. The BIOS * may also retry. */ for (retry = 0; retry < 3; retry++) { /* If retrying, reset the drive */ if (retry > 0) { v86.ctl = V86_FLAGS; v86.addr = 0x1b; v86.eax = 0x0300 | biosdev; v86int(); } v86.ctl = V86_FLAGS; v86.addr = 0x1b; v86.eax = 0x0600 | (biosdev & 0x7f); v86.ebx = x * BIOSCD_SECSIZE; v86.ecx = dblk & 0xffff; v86.edx = (dblk >> 16) & 0xffff; v86.ebp = VTOPOFF(xp); v86.es = VTOPSEG(xp); v86int(); result = V86_CY(v86.efl); if (result == 0) break; } #ifdef DISK_DEBUG error = (v86.eax >> 8) & 0xff; #endif DEBUG("%d sectors from %lld to %p (0x%x) %s", x, dblk, p, VTOP(p), result ? "failed" : "ok"); DEBUG("unit %d status 0x%x", unit, error); if (bbuf != NULL) bcopy(bbuf, p, x * BIOSCD_SECSIZE); p += (x * BIOSCD_SECSIZE); dblk += x; resid -= x; } /* hexdump(dest, (blks * BIOSCD_SECSIZE)); */ return(0); } /* * Return a suitable dev_t value for (dev). */ int bc_getdev(struct i386_devdesc *dev) { int biosdev, unit, device; int major; int rootdev; unit = dev->d_unit; biosdev = bc_unit2bios(unit); DEBUG("unit %d BIOS device %d", unit, biosdev); if (biosdev == -1) /* not a BIOS device */ return(-1); device = biosdev & 0xf0; if (device == 0x80) major = ACDMAJOR; else if (device == 0xa0) major = CDMAJOR; else return (-1); unit = 0; /* XXX */ /* XXX: Assume partition 'a'. */ rootdev = MAKEBOOTDEV(major, 0, unit, 0); DEBUG("dev is 0x%x\n", rootdev); return(rootdev); } Index: head/sys/boot/pc98/libpc98/biosdisk.c =================================================================== --- head/sys/boot/pc98/libpc98/biosdisk.c (revision 308826) +++ head/sys/boot/pc98/libpc98/biosdisk.c (revision 308827) @@ -1,1114 +1,1121 @@ /*- * Copyright (c) 1998 Michael Smith * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * BIOS disk device handling. * * Ideas and algorithms from: * * - NetBSD libi386/biosdisk.c * - FreeBSD biosboot/disk.c * */ #include #include #include #include #include #include #include #include "libi386.h" #define BIOS_NUMDRIVES 0x475 #define BIOSDISK_SECSIZE 512 #define BUFSIZE (1 * BIOSDISK_SECSIZE) #define DT_ATAPI 0x10 /* disk type for ATAPI floppies */ #define WDMAJOR 0 /* major numbers for devices we frontend for */ #define WFDMAJOR 1 #define FDMAJOR 2 #define DAMAJOR 4 #ifdef DISK_DEBUG # define DEBUG(fmt, args...) printf("%s: " fmt "\n" , __func__ , ## args) #else # define DEBUG(fmt, args...) #endif struct open_disk { int od_dkunit; /* disk unit number */ int od_unit; /* BIOS unit number */ int od_cyl; /* BIOS geometry */ int od_hds; int od_sec; int od_boff; /* block offset from beginning of BIOS disk */ int od_flags; #define BD_MODEINT13 0x0000 #define BD_MODEEDD1 0x0001 #define BD_MODEEDD3 0x0002 #define BD_MODEMASK 0x0003 #define BD_FLOPPY 0x0004 #define BD_LABELOK 0x0008 #define BD_PARTTABOK 0x0010 #define BD_OPTICAL 0x0020 struct disklabel od_disklabel; int od_nslices; /* slice count */ struct pc98_partition od_slicetab[PC98_NPARTS]; }; /* * List of BIOS devices, translation from disk unit number to * BIOS unit number. */ static struct bdinfo { int bd_unit; /* BIOS unit number */ int bd_flags; int bd_type; /* BIOS 'drive type' (floppy only) */ int bd_da_unit; /* kernel unit number for da */ int bd_open; /* reference counter */ void *bd_bcache; /* buffer cache data */ } bdinfo [MAXBDDEV]; static int nbdinfo = 0; #define BD(dev) (bdinfo[(dev)->d_unit]) static int bd_getgeom(struct open_disk *od); static int bd_read(struct open_disk *od, daddr_t dblk, int blks, caddr_t dest); static int bd_write(struct open_disk *od, daddr_t dblk, int blks, caddr_t dest); static int bd_int13probe(struct bdinfo *bd); static int bd_printslice(struct open_disk *od, struct pc98_partition *dp, char *prefix, int verbose); static int bd_printbsdslice(struct open_disk *od, daddr_t offset, char *prefix, int verbose); static int bd_init(void); static int bd_strategy(void *devdata, int flag, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize); static int bd_realstrategy(void *devdata, int flag, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize); static int bd_open(struct open_file *f, ...); static int bd_close(struct open_file *f); static int bd_print(int verbose); struct devsw biosdisk = { "disk", DEVT_DISK, bd_init, bd_strategy, bd_open, bd_close, noioctl, bd_print, NULL }; static int bd_opendisk(struct open_disk **odp, struct i386_devdesc *dev); static void bd_closedisk(struct open_disk *od); static int bd_open_pc98(struct open_disk *od, struct i386_devdesc *dev); static int bd_bestslice(struct open_disk *od); static void bd_checkextended(struct open_disk *od, int slicenum); /* * Translate between BIOS device numbers and our private unit numbers. */ int bd_bios2unit(int biosdev) { int i; DEBUG("looking for bios device 0x%x", biosdev); for (i = 0; i < nbdinfo; i++) { DEBUG("bd unit %d is BIOS device 0x%x", i, bdinfo[i].bd_unit); if (bdinfo[i].bd_unit == biosdev) return(i); } return(-1); } int bd_unit2bios(int unit) { if ((unit >= 0) && (unit < nbdinfo)) return(bdinfo[unit].bd_unit); return(-1); } /* * Quiz the BIOS for disk devices, save a little info about them. */ static int bd_init(void) { int base, unit; int da_drive=0, n=-0x10; /* sequence 0x90, 0x80, 0xa0 */ for (base = 0x90; base <= 0xa0; base += n, n += 0x30) { for (unit = base; (nbdinfo < MAXBDDEV) || ((unit & 0x0f) < 4); unit++) { bdinfo[nbdinfo].bd_open = 0; bdinfo[nbdinfo].bd_bcache = NULL; bdinfo[nbdinfo].bd_unit = unit; bdinfo[nbdinfo].bd_flags = (unit & 0xf0) == 0x90 ? BD_FLOPPY : 0; if (!bd_int13probe(&bdinfo[nbdinfo])){ if (((unit & 0xf0) == 0x90 && (unit & 0x0f) < 4) || ((unit & 0xf0) == 0xa0 && (unit & 0x0f) < 6)) continue; /* Target IDs are not contiguous. */ else break; } if (bdinfo[nbdinfo].bd_flags & BD_FLOPPY){ /* available 1.44MB access? */ if (*(u_char *)PTOV(0xA15AE) & (1<<(unit & 0xf))) { /* boot media 1.2MB FD? */ if ((*(u_char *)PTOV(0xA1584) & 0xf0) != 0x90) bdinfo[nbdinfo].bd_unit = 0x30 + (unit & 0xf); } } else { if ((unit & 0xF0) == 0xA0) /* SCSI HD or MO */ bdinfo[nbdinfo].bd_da_unit = da_drive++; } /* XXX we need "disk aliases" to make this simpler */ printf("BIOS drive %c: is disk%d\n", 'A' + nbdinfo, nbdinfo); nbdinfo++; } } bcache_add_dev(nbdinfo); return(0); } /* * Try to detect a device supported by the legacy int13 BIOS */ static int bd_int13probe(struct bdinfo *bd) { int addr; if (bd->bd_flags & BD_FLOPPY) { addr = 0xa155c; } else { if ((bd->bd_unit & 0xf0) == 0x80) addr = 0xa155d; else addr = 0xa1482; } if ( *(u_char *)PTOV(addr) & (1<<(bd->bd_unit & 0x0f))) { bd->bd_flags |= BD_MODEINT13; return(1); } if ((bd->bd_unit & 0xF0) == 0xA0) { int media = ((unsigned *)PTOV(0xA1460))[bd->bd_unit & 0x0F] & 0x1F; if (media == 7) { /* MO */ bd->bd_flags |= BD_MODEINT13 | BD_OPTICAL; return(1); } } return(0); } /* * Print information about disks */ static int bd_print(int verbose) { int i, j, ret = 0; char line[80]; struct i386_devdesc dev; struct open_disk *od; struct pc98_partition *dptr; + if (nbdinfo == 0) + return (0); + + printf("%s devices:", biosdisk.dv_name); + if ((ret = pager_output("\n")) != 0) + return (ret); + for (i = 0; i < nbdinfo; i++) { snprintf(line, sizeof(line), " disk%d: BIOS drive %c:\n", i, 'A' + i); if ((ret = pager_output(line)) != 0) break; /* try to open the whole disk */ dev.d_unit = i; dev.d_kind.biosdisk.slice = -1; dev.d_kind.biosdisk.partition = -1; if (!bd_opendisk(&od, &dev)) { /* Do we have a partition table? */ if (od->od_flags & BD_PARTTABOK) { dptr = &od->od_slicetab[0]; /* Check for a "dedicated" disk */ for (j = 0; j < od->od_nslices; j++) { snprintf(line, sizeof(line), " disk%ds%d", i, j + 1); if ((ret = bd_printslice(od, &dptr[j], line, verbose)) != 0) break; } } bd_closedisk(od); if (ret != 0) break; } } return (ret); } /* Given a size in 512 byte sectors, convert it to a human-readable number. */ static char * display_size(uint64_t size) { static char buf[80]; char unit; size /= 2; unit = 'K'; if (size >= 10485760000LL) { size /= 1073741824; unit = 'T'; } else if (size >= 10240000) { size /= 1048576; unit = 'G'; } else if (size >= 10000) { size /= 1024; unit = 'M'; } sprintf(buf, "%6ld%cB", (long)size, unit); return (buf); } /* * Print information about slices on a disk. For the size calculations we * assume a 512 byte sector. */ static int bd_printslice(struct open_disk *od, struct pc98_partition *dp, char *prefix, int verbose) { int cylsecs, start, size; char stats[80]; char line[80]; cylsecs = od->od_hds * od->od_sec; start = dp->dp_scyl * cylsecs + dp->dp_shd * od->od_sec + dp->dp_ssect; size = (dp->dp_ecyl - dp->dp_scyl + 1) * cylsecs; if (verbose) sprintf(stats, " %s (%d - %d)", display_size(size), start, start + size); else stats[0] = '\0'; switch(dp->dp_mid & PC98_MID_MASK) { case PC98_MID_386BSD: return (bd_printbsdslice(od, start, prefix, verbose)); case 0x00: /* unused partition */ return (0); case 0x01: sprintf(line, "%s: FAT-12%s\n", prefix, stats); break; case 0x11: case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: sprintf(line, "%s: FAT-16%s\n", prefix, stats); break; default: sprintf(line, "%s: Unknown fs: 0x%x %s\n", prefix, dp->dp_mid, stats); } return (pager_output(line)); } /* * Print out each valid partition in the disklabel of a FreeBSD slice. * For size calculations, we assume a 512 byte sector size. */ static int bd_printbsdslice(struct open_disk *od, daddr_t offset, char *prefix, int verbose) { char line[80]; char buf[BIOSDISK_SECSIZE]; struct disklabel *lp; int i; /* read disklabel */ if (bd_read(od, offset + LABELSECTOR, 1, buf)) return (0); lp =(struct disklabel *)(&buf[0]); if (lp->d_magic != DISKMAGIC) { sprintf(line, "%s: FFS bad disklabel\n", prefix); return (pager_output(line)); } /* Print partitions */ for (i = 0; i < lp->d_npartitions; i++) { /* * For each partition, make sure we know what type of fs it is. If * not, then skip it. However, since floppies often have bogus * fstypes, print the 'a' partition on a floppy even if it is marked * unused. */ if ((lp->d_partitions[i].p_fstype == FS_BSDFFS) || (lp->d_partitions[i].p_fstype == FS_SWAP) || (lp->d_partitions[i].p_fstype == FS_VINUM) || ((lp->d_partitions[i].p_fstype == FS_UNUSED) && (od->od_flags & BD_FLOPPY) && (i == 0))) { /* Only print out statistics in verbose mode */ if (verbose) sprintf(line, " %s%c: %s %s (%d - %d)\n", prefix, 'a' + i, (lp->d_partitions[i].p_fstype == FS_SWAP) ? "swap " : (lp->d_partitions[i].p_fstype == FS_VINUM) ? "vinum" : "FFS ", display_size(lp->d_partitions[i].p_size), lp->d_partitions[i].p_offset, lp->d_partitions[i].p_offset + lp->d_partitions[i].p_size); else sprintf(line, " %s%c: %s\n", prefix, 'a' + i, (lp->d_partitions[i].p_fstype == FS_SWAP) ? "swap" : (lp->d_partitions[i].p_fstype == FS_VINUM) ? "vinum" : "FFS"); if (pager_output(line)) return (1); } } return (0); } /* * Attempt to open the disk described by (dev) for use by (f). * * Note that the philosophy here is "give them exactly what * they ask for". This is necessary because being too "smart" * about what the user might want leads to complications. * (eg. given no slice or partition value, with a disk that is * sliced - are they after the first BSD slice, or the DOS * slice before it?) */ static int bd_open(struct open_file *f, ...) { va_list ap; struct i386_devdesc *dev; struct open_disk *od; int error; va_start(ap, f); dev = va_arg(ap, struct i386_devdesc *); va_end(ap); if ((error = bd_opendisk(&od, dev))) return(error); BD(dev).bd_open++; if (BD(dev).bd_bcache == NULL) BD(dev).bd_bcache = bcache_allocate(); /* * Save our context */ ((struct i386_devdesc *)(f->f_devdata))->d_kind.biosdisk.data = od; DEBUG("open_disk %p, partition at 0x%x", od, od->od_boff); return(0); } static int bd_opendisk(struct open_disk **odp, struct i386_devdesc *dev) { struct open_disk *od; int error; if (dev->d_unit >= nbdinfo) { DEBUG("attempt to open nonexistent disk"); return(ENXIO); } od = (struct open_disk *)malloc(sizeof(struct open_disk)); if (!od) { DEBUG("no memory"); return (ENOMEM); } /* Look up BIOS unit number, intialise open_disk structure */ od->od_dkunit = dev->d_unit; od->od_unit = bdinfo[od->od_dkunit].bd_unit; od->od_flags = bdinfo[od->od_dkunit].bd_flags; od->od_boff = 0; error = 0; DEBUG("open '%s', unit 0x%x slice %d partition %d", i386_fmtdev(dev), dev->d_unit, dev->d_kind.biosdisk.slice, dev->d_kind.biosdisk.partition); /* Get geometry for this open (removable device may have changed) */ if (bd_getgeom(od)) { DEBUG("can't get geometry"); error = ENXIO; goto out; } /* Determine disk layout. */ error = bd_open_pc98(od, dev); out: if (error) { free(od); } else { *odp = od; /* return the open disk */ } return(error); } static int bd_open_pc98(struct open_disk *od, struct i386_devdesc *dev) { struct pc98_partition *dptr; struct disklabel *lp; int sector, slice, i; char buf[BUFSIZE]; /* * Following calculations attempt to determine the correct value * for d->od_boff by looking for the slice and partition specified, * or searching for reasonable defaults. */ /* * Find the slice in the DOS slice table. */ od->od_nslices = 0; if (od->od_flags & BD_FLOPPY) { sector = 0; goto unsliced; } if (bd_read(od, 0, 1, buf)) { DEBUG("error reading MBR"); return (EIO); } /* * Check the slice table magic. */ if (((u_char)buf[0x1fe] != 0x55) || ((u_char)buf[0x1ff] != 0xaa)) { /* If a slice number was explicitly supplied, this is an error */ if (dev->d_kind.biosdisk.slice > 0) { DEBUG("no slice table/MBR (no magic)"); return (ENOENT); } sector = 0; goto unsliced; /* may be a floppy */ } if (bd_read(od, 1, 1, buf)) { DEBUG("error reading MBR"); return (EIO); } /* * copy the partition table, then pick up any extended partitions. */ bcopy(buf + PC98_PARTOFF, &od->od_slicetab, sizeof(struct pc98_partition) * PC98_NPARTS); od->od_nslices = PC98_NPARTS; /* extended slices start here */ od->od_flags |= BD_PARTTABOK; dptr = &od->od_slicetab[0]; /* Is this a request for the whole disk? */ if (dev->d_kind.biosdisk.slice == -1) { sector = 0; goto unsliced; } /* * if a slice number was supplied but not found, this is an error. */ if (dev->d_kind.biosdisk.slice > 0) { slice = dev->d_kind.biosdisk.slice - 1; if (slice >= od->od_nslices) { DEBUG("slice %d not found", slice); return (ENOENT); } } /* Try to auto-detect the best slice; this should always give a slice number */ if (dev->d_kind.biosdisk.slice == 0) { slice = bd_bestslice(od); if (slice == -1) { return (ENOENT); } dev->d_kind.biosdisk.slice = slice; } dptr = &od->od_slicetab[0]; /* * Accept the supplied slice number unequivocally (we may be looking * at a DOS partition). */ dptr += (dev->d_kind.biosdisk.slice - 1); /* we number 1-4, offsets are 0-3 */ sector = dptr->dp_scyl * od->od_hds * od->od_sec + dptr->dp_shd * od->od_sec + dptr->dp_ssect; { int end = dptr->dp_ecyl * od->od_hds * od->od_sec + dptr->dp_ehd * od->od_sec + dptr->dp_esect; DEBUG("slice entry %d at %d, %d sectors", dev->d_kind.biosdisk.slice - 1, sector, end-sector); } /* * If we are looking at a BSD slice, and the partition is < 0, assume the 'a' partition */ if ((dptr->dp_mid == DOSMID_386BSD) && (dev->d_kind.biosdisk.partition < 0)) dev->d_kind.biosdisk.partition = 0; unsliced: /* * Now we have the slice offset, look for the partition in the disklabel if we have * a partition to start with. * * XXX we might want to check the label checksum. */ if (dev->d_kind.biosdisk.partition < 0) { od->od_boff = sector; /* no partition, must be after the slice */ DEBUG("opening raw slice"); } else { if (bd_read(od, sector + LABELSECTOR, 1, buf)) { DEBUG("error reading disklabel"); return (EIO); } DEBUG("copy %d bytes of label from %p to %p", sizeof(struct disklabel), buf + LABELOFFSET, &od->od_disklabel); bcopy(buf + LABELOFFSET, &od->od_disklabel, sizeof(struct disklabel)); lp = &od->od_disklabel; od->od_flags |= BD_LABELOK; if (lp->d_magic != DISKMAGIC) { DEBUG("no disklabel"); return (ENOENT); } if (dev->d_kind.biosdisk.partition >= lp->d_npartitions) { DEBUG("partition '%c' exceeds partitions in table (a-'%c')", 'a' + dev->d_kind.biosdisk.partition, 'a' + lp->d_npartitions); return (EPART); } #ifdef DISK_DEBUG /* Complain if the partition is unused unless this is a floppy. */ if ((lp->d_partitions[dev->d_kind.biosdisk.partition].p_fstype == FS_UNUSED) && !(od->od_flags & BD_FLOPPY)) DEBUG("warning, partition marked as unused"); #endif od->od_boff = lp->d_partitions[dev->d_kind.biosdisk.partition].p_offset - lp->d_partitions[RAW_PART].p_offset + sector; } return (0); } /* * Search for a slice with the following preferences: * * 1: Active FreeBSD slice * 2: Non-active FreeBSD slice * 3: Active Linux slice * 4: non-active Linux slice * 5: Active FAT/FAT32 slice * 6: non-active FAT/FAT32 slice */ #define PREF_RAWDISK 0 #define PREF_FBSD_ACT 1 #define PREF_FBSD 2 #define PREF_LINUX_ACT 3 #define PREF_LINUX 4 #define PREF_DOS_ACT 5 #define PREF_DOS 6 #define PREF_NONE 7 /* * slicelimit is in the range 0 .. PC98_NPARTS */ static int bd_bestslice(struct open_disk *od) { struct pc98_partition *dp; int pref, preflevel; int i, prefslice; prefslice = 0; preflevel = PREF_NONE; dp = &od->od_slicetab[0]; for (i = 0; i < od->od_nslices; i++, dp++) { switch(dp->dp_mid & PC98_MID_MASK) { case PC98_MID_386BSD: /* FreeBSD */ if ((dp->dp_mid & PC98_MID_BOOTABLE) && (preflevel > PREF_FBSD_ACT)) { pref = i; preflevel = PREF_FBSD_ACT; } else if (preflevel > PREF_FBSD) { pref = i; preflevel = PREF_FBSD; } break; case 0x11: /* DOS/Windows */ case 0x20: case 0x21: case 0x22: case 0x23: case 0x63: if ((dp->dp_mid & PC98_MID_BOOTABLE) && (preflevel > PREF_DOS_ACT)) { pref = i; preflevel = PREF_DOS_ACT; } else if (preflevel > PREF_DOS) { pref = i; preflevel = PREF_DOS; } break; } } return (prefslice); } static int bd_close(struct open_file *f) { struct i386_devdesc *dev = f->f_devdata; struct open_disk *od = (struct open_disk *)(dev->d_kind.biosdisk.data); BD(dev).bd_open--; if (BD(dev).bd_open == 0) { bcache_free(BD(dev).bd_bcache); BD(dev).bd_bcache = NULL; } bd_closedisk(od); return(0); } static void bd_closedisk(struct open_disk *od) { DEBUG("open_disk %p", od); #if 0 /* XXX is this required? (especially if disk already open...) */ if (od->od_flags & BD_FLOPPY) delay(3000000); #endif free(od); } static int bd_strategy(void *devdata, int rw, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize) { struct bcache_devdata bcd; struct i386_devdesc *dev = devdata; struct open_disk *od = (struct open_disk *)(dev->d_kind.biosdisk.data); bcd.dv_strategy = bd_realstrategy; bcd.dv_devdata = devdata; bcd.dv_cache = BD(dev).bd_bcache; return(bcache_strategy(&bcd, rw, dblk+od->od_boff, offset, size, buf, rsize)); } static int bd_realstrategy(void *devdata, int rw, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize) { struct open_disk *od = (struct open_disk *)(((struct i386_devdesc *)devdata)->d_kind.biosdisk.data); int blks; #ifdef BD_SUPPORT_FRAGS char fragbuf[BIOSDISK_SECSIZE]; size_t fragsize; fragsize = size % BIOSDISK_SECSIZE; #else if (size % BIOSDISK_SECSIZE) panic("bd_strategy: %d bytes I/O not multiple of block size", size); #endif DEBUG("open_disk %p", od); blks = size / BIOSDISK_SECSIZE; if (rsize) *rsize = 0; switch(rw){ case F_READ: DEBUG("read %d from %d to %p", blks, dblk, buf); if (blks && bd_read(od, dblk, blks, buf)) { DEBUG("read error"); return (EIO); } #ifdef BD_SUPPORT_FRAGS DEBUG("bd_strategy: frag read %d from %d+%d to %p", fragsize, dblk, blks, buf + (blks * BIOSDISK_SECSIZE)); if (fragsize && bd_read(od, dblk + blks, 1, fragsize)) { DEBUG("frag read error"); return(EIO); } bcopy(fragbuf, buf + (blks * BIOSDISK_SECSIZE), fragsize); #endif break; case F_WRITE : DEBUG("write %d from %d to %p", blks, dblk, buf); if (blks && bd_write(od, dblk, blks, buf)) { DEBUG("write error"); return (EIO); } #ifdef BD_SUPPORT_FRAGS if(fragsize) { DEBUG("Attempted to write a frag"); return (EIO); } #endif break; default: /* DO NOTHING */ return (EROFS); } if (rsize) *rsize = size; return (0); } /* Max number of sectors to bounce-buffer if the request crosses a 64k boundary */ #define FLOPPY_BOUNCEBUF 18 static int bd_chs_io(struct open_disk *od, daddr_t dblk, int blks, caddr_t dest, int write) { u_int x, bpc, cyl, hd, sec; bpc = (od->od_sec * od->od_hds); /* blocks per cylinder */ x = dblk; cyl = x / bpc; /* block # / blocks per cylinder */ x %= bpc; /* block offset into cylinder */ hd = x / od->od_sec; /* offset / blocks per track */ sec = x % od->od_sec; /* offset into track */ v86.ctl = V86_FLAGS; v86.addr = 0x1b; if (write) v86.eax = 0x0500 | od->od_unit; else v86.eax = 0x0600 | od->od_unit; if (od->od_flags & BD_FLOPPY) { v86.eax |= 0xd000; v86.ecx = 0x0200 | (cyl & 0xff); v86.edx = (hd << 8) | (sec + 1); } else if (od->od_flags & BD_OPTICAL) { v86.eax &= 0xFF7F; v86.ecx = dblk & 0xFFFF; v86.edx = dblk >> 16; } else { v86.ecx = cyl; v86.edx = (hd << 8) | sec; } v86.ebx = blks * BIOSDISK_SECSIZE; v86.es = VTOPSEG(dest); v86.ebp = VTOPOFF(dest); v86int(); return (V86_CY(v86.efl)); } static int bd_io(struct open_disk *od, daddr_t dblk, int blks, caddr_t dest, int write) { u_int x, sec, result, resid, retry, maxfer; caddr_t p, xp, bbuf, breg; /* Just in case some idiot actually tries to read/write -1 blocks... */ if (blks < 0) return (-1); resid = blks; p = dest; /* Decide whether we have to bounce */ if (VTOP(dest) >> 20 != 0 || ((VTOP(dest) >> 16) != (VTOP(dest + blks * BIOSDISK_SECSIZE) >> 16))) { /* * There is a 64k physical boundary somewhere in the * destination buffer, or the destination buffer is above * first 1MB of physical memory so we have to arrange a * suitable bounce buffer. Allocate a buffer twice as large * as we need to. Use the bottom half unless there is a break * there, in which case we use the top half. */ x = min(od->od_sec, (unsigned)blks); bbuf = alloca(x * 2 * BIOSDISK_SECSIZE); if (((u_int32_t)VTOP(bbuf) & 0xffff0000) == ((u_int32_t)VTOP(bbuf + x * BIOSDISK_SECSIZE) & 0xffff0000)) { breg = bbuf; } else { breg = bbuf + x * BIOSDISK_SECSIZE; } maxfer = x; /* limit transfers to bounce region size */ } else { breg = bbuf = NULL; maxfer = 0; } while (resid > 0) { /* * Play it safe and don't cross track boundaries. * (XXX this is probably unnecessary) */ sec = dblk % od->od_sec; /* offset into track */ x = min(od->od_sec - sec, resid); if (maxfer > 0) x = min(x, maxfer); /* fit bounce buffer */ /* where do we transfer to? */ xp = bbuf == NULL ? p : breg; /* * Put your Data In, Put your Data out, * Put your Data In, and shake it all about */ if (write && bbuf != NULL) bcopy(p, breg, x * BIOSDISK_SECSIZE); /* * Loop retrying the operation a couple of times. The BIOS * may also retry. */ for (retry = 0; retry < 3; retry++) { /* if retrying, reset the drive */ if (retry > 0) { v86.ctl = V86_FLAGS; v86.addr = 0x1b; v86.eax = 0x0300 | od->od_unit; v86int(); } result = bd_chs_io(od, dblk, x, xp, write); if (result == 0) break; } if (write) DEBUG("Write %d sector(s) from %p (0x%x) to %lld %s", x, p, VTOP(p), dblk, result ? "failed" : "ok"); else DEBUG("Read %d sector(s) from %lld to %p (0x%x) %s", x, dblk, p, VTOP(p), result ? "failed" : "ok"); if (result) { return(-1); } if (!write && bbuf != NULL) bcopy(breg, p, x * BIOSDISK_SECSIZE); p += (x * BIOSDISK_SECSIZE); dblk += x; resid -= x; } /* hexdump(dest, (blks * BIOSDISK_SECSIZE)); */ return(0); } static int bd_read(struct open_disk *od, daddr_t dblk, int blks, caddr_t dest) { return (bd_io(od, dblk, blks, dest, 0)); } static int bd_write(struct open_disk *od, daddr_t dblk, int blks, caddr_t dest) { return (bd_io(od, dblk, blks, dest, 1)); } static int bd_getgeom(struct open_disk *od) { if (od->od_flags & BD_FLOPPY) { od->od_cyl = 79; od->od_hds = 2; od->od_sec = (od->od_unit & 0xf0) == 0x30 ? 18 : 15; } else if (od->od_flags & BD_OPTICAL) { od->od_cyl = 0xFFFE; od->od_hds = 8; od->od_sec = 32; } else { v86.ctl = V86_FLAGS; v86.addr = 0x1b; v86.eax = 0x8400 | od->od_unit; v86int(); od->od_cyl = v86.ecx; od->od_hds = (v86.edx >> 8) & 0xff; od->od_sec = v86.edx & 0xff; if (V86_CY(v86.efl)) return(1); } DEBUG("unit 0x%x geometry %d/%d/%d", od->od_unit, od->od_cyl, od->od_hds, od->od_sec); return(0); } /* * Return the BIOS geometry of a given "fixed drive" in a format * suitable for the legacy bootinfo structure. Since the kernel is * expecting raw int 0x13/0x8 values for N_BIOS_GEOM drives, we * prefer to get the information directly, rather than rely on being * able to put it together from information already maintained for * different purposes and for a probably different number of drives. * * For valid drives, the geometry is expected in the format (31..0) * "000000cc cccccccc hhhhhhhh 00ssssss"; and invalid drives are * indicated by returning the geometry of a "1.2M" PC-format floppy * disk. And, incidentally, what is returned is not the geometry as * such but the highest valid cylinder, head, and sector numbers. */ u_int32_t bd_getbigeom(int bunit) { int hds = 0; int unit = 0x80; /* IDE HDD */ u_int addr = 0xA155d; while (unit < 0xa7) { if (*(u_char *)PTOV(addr) & (1 << (unit & 0x0f))) if (hds++ == bunit) break; if (unit >= 0xA0) { int media = ((unsigned *)PTOV(0xA1460))[unit & 0x0F] & 0x1F; if (media == 7 && hds++ == bunit) /* SCSI MO */ return(0xFFFE0820); /* C:65535 H:8 S:32 */ } if (++unit == 0x84) { unit = 0xA0; /* SCSI HDD */ addr = 0xA1482; } } if (unit == 0xa7) return 0x4F020F; /* 1200KB FD C:80 H:2 S:15 */ v86.ctl = V86_FLAGS; v86.addr = 0x1b; v86.eax = 0x8400 | unit; v86int(); if (V86_CY(v86.efl)) return 0x4F020F; /* 1200KB FD C:80 H:2 S:15 */ return ((v86.ecx & 0xffff) << 16) | (v86.edx & 0xffff); } /* * Return a suitable dev_t value for (dev). * * In the case where it looks like (dev) is a SCSI disk, we allow the number of * IDE disks to be specified in $num_ide_disks. There should be a Better Way. */ int bd_getdev(struct i386_devdesc *dev) { struct open_disk *od; int biosdev; int major; int rootdev; char *nip, *cp; int unitofs = 0, i, unit; biosdev = bd_unit2bios(dev->d_unit); DEBUG("unit %d BIOS device %d", dev->d_unit, biosdev); if (biosdev == -1) /* not a BIOS device */ return(-1); if (bd_opendisk(&od, dev) != 0) /* oops, not a viable device */ return(-1); if ((biosdev & 0xf0) == 0x90 || (biosdev & 0xf0) == 0x30) { /* floppy (or emulated floppy) or ATAPI device */ if (bdinfo[dev->d_unit].bd_type == DT_ATAPI) { /* is an ATAPI disk */ major = WFDMAJOR; } else { /* is a floppy disk */ major = FDMAJOR; } } else { /* harddisk */ if ((od->od_flags & BD_LABELOK) && (od->od_disklabel.d_type == DTYPE_SCSI)) { /* label OK, disk labelled as SCSI */ major = DAMAJOR; /* check for unit number correction hint, now deprecated */ if ((nip = getenv("num_ide_disks")) != NULL) { i = strtol(nip, &cp, 0); /* check for parse error */ if ((cp != nip) && (*cp == 0)) unitofs = i; } } else { /* assume an IDE disk */ major = WDMAJOR; } } /* default root disk unit number */ if ((biosdev & 0xf0) == 0xa0) unit = bdinfo[dev->d_unit].bd_da_unit; else unit = biosdev & 0xf; /* XXX a better kludge to set the root disk unit number */ if ((nip = getenv("root_disk_unit")) != NULL) { i = strtol(nip, &cp, 0); /* check for parse error */ if ((cp != nip) && (*cp == 0)) unit = i; } rootdev = MAKEBOOTDEV(major, dev->d_kind.biosdisk.slice + 1, unit, dev->d_kind.biosdisk.partition); DEBUG("dev is 0x%x\n", rootdev); return(rootdev); } Index: head/sys/boot/uboot/lib/disk.c =================================================================== --- head/sys/boot/uboot/lib/disk.c (revision 308826) +++ head/sys/boot/uboot/lib/disk.c (revision 308827) @@ -1,309 +1,316 @@ /*- * Copyright (c) 2008 Semihalf, Rafal Jaworowski * Copyright (c) 2009 Semihalf, Piotr Ziecik * Copyright (c) 2012 Andrey V. Elsukov * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ /* * Block storage I/O routines for U-Boot */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include "api_public.h" #include "bootstrap.h" #include "disk.h" #include "glue.h" #include "libuboot.h" #define stor_printf(fmt, args...) do { \ printf("%s%d: ", dev->d_dev->dv_name, dev->d_unit); \ printf(fmt, ##args); \ } while (0) #ifdef DEBUG #define debugf(fmt, args...) do { printf("%s(): ", __func__); \ printf(fmt,##args); } while (0) #else #define debugf(fmt, args...) #endif static struct { int opened; /* device is opened */ int handle; /* storage device handle */ int type; /* storage type */ off_t blocks; /* block count */ u_int bsize; /* block size */ } stor_info[UB_MAX_DEV]; #define SI(dev) (stor_info[(dev)->d_unit]) static int stor_info_no = 0; static int stor_opendev(struct disk_devdesc *); static int stor_readdev(struct disk_devdesc *, daddr_t, size_t, char *); /* devsw I/F */ static int stor_init(void); static int stor_strategy(void *, int, daddr_t, size_t, size_t, char *, size_t *); static int stor_open(struct open_file *, ...); static int stor_close(struct open_file *); static int stor_ioctl(struct open_file *f, u_long cmd, void *data); static int stor_print(int); static void stor_cleanup(void); struct devsw uboot_storage = { "disk", DEVT_DISK, stor_init, stor_strategy, stor_open, stor_close, stor_ioctl, stor_print, stor_cleanup }; static int stor_init(void) { struct device_info *di; int i; if (devs_no == 0) { printf("No U-Boot devices! Really enumerated?\n"); return (-1); } for (i = 0; i < devs_no; i++) { di = ub_dev_get(i); if ((di != NULL) && (di->type & DEV_TYP_STOR)) { if (stor_info_no >= UB_MAX_DEV) { printf("Too many storage devices: %d\n", stor_info_no); return (-1); } stor_info[stor_info_no].handle = i; stor_info[stor_info_no].opened = 0; stor_info[stor_info_no].type = di->type; stor_info[stor_info_no].blocks = di->di_stor.block_count; stor_info[stor_info_no].bsize = di->di_stor.block_size; stor_info_no++; } } if (!stor_info_no) { debugf("No storage devices\n"); return (-1); } debugf("storage devices found: %d\n", stor_info_no); return (0); } static void stor_cleanup(void) { int i; for (i = 0; i < stor_info_no; i++) if (stor_info[i].opened > 0) ub_dev_close(stor_info[i].handle); disk_cleanup(&uboot_storage); } static int stor_strategy(void *devdata, int rw, daddr_t blk, size_t offset, size_t size, char *buf, size_t *rsize) { struct disk_devdesc *dev = (struct disk_devdesc *)devdata; daddr_t bcount; int err; if (rw != F_READ) { stor_printf("write attempt, operation not supported!\n"); return (EROFS); } if (size % SI(dev).bsize) { stor_printf("size=%zu not multiple of device " "block size=%d\n", size, SI(dev).bsize); return (EIO); } bcount = size / SI(dev).bsize; if (rsize) *rsize = 0; err = stor_readdev(dev, blk + dev->d_offset, bcount, buf); if (!err && rsize) *rsize = size; return (err); } static int stor_open(struct open_file *f, ...) { va_list ap; struct disk_devdesc *dev; va_start(ap, f); dev = va_arg(ap, struct disk_devdesc *); va_end(ap); return (stor_opendev(dev)); } static int stor_opendev(struct disk_devdesc *dev) { int err; if (dev->d_unit < 0 || dev->d_unit >= stor_info_no) return (EIO); if (SI(dev).opened == 0) { err = ub_dev_open(SI(dev).handle); if (err != 0) { stor_printf("device open failed with error=%d, " "handle=%d\n", err, SI(dev).handle); return (ENXIO); } SI(dev).opened++; } return (disk_open(dev, SI(dev).blocks * SI(dev).bsize, SI(dev).bsize, 0)); } static int stor_close(struct open_file *f) { struct disk_devdesc *dev; dev = (struct disk_devdesc *)(f->f_devdata); return (disk_close(dev)); } static int stor_readdev(struct disk_devdesc *dev, daddr_t blk, size_t size, char *buf) { lbasize_t real_size; int err; debugf("reading blk=%d size=%d @ 0x%08x\n", (int)blk, size, (uint32_t)buf); err = ub_dev_read(SI(dev).handle, buf, size, blk, &real_size); if (err != 0) { stor_printf("read failed, error=%d\n", err); return (EIO); } if (real_size != size) { stor_printf("real size != size\n"); err = EIO; } return (err); } static int stor_print(int verbose) { struct disk_devdesc dev; static char line[80]; int i, ret = 0; + if (stor_info_no == 0) + return (ret); + + printf("%s devices:", uboot_storage.dv_name); + if ((ret = pager_output("\n")) != 0) + return (ret); + for (i = 0; i < stor_info_no; i++) { dev.d_dev = &uboot_storage; dev.d_unit = i; dev.d_slice = -1; dev.d_partition = -1; snprintf(line, sizeof(line), "\tdisk%d (%s)\n", i, ub_stor_type(SI(&dev).type)); if ((ret = pager_output(line)) != 0) break; if (stor_opendev(&dev) == 0) { sprintf(line, "\tdisk%d", i); ret = disk_print(&dev, line, verbose); disk_close(&dev); if (ret != 0) break; } } return (ret); } static int stor_ioctl(struct open_file *f, u_long cmd, void *data) { struct disk_devdesc *dev; dev = (struct disk_devdesc *)f->f_devdata; switch (cmd) { case DIOCGSECTORSIZE: *(u_int *)data = SI(dev).bsize; break; case DIOCGMEDIASIZE: *(off_t *)data = SI(dev).bsize * SI(dev).blocks; break; default: return (ENOTTY); } return (0); } /* * Return the device unit number for the given type and type-relative unit * number. */ int uboot_diskgetunit(int type, int type_unit) { int local_type_unit; int i; local_type_unit = 0; for (i = 0; i < stor_info_no; i++) { if ((stor_info[i].type & type) == type) { if (local_type_unit == type_unit) { return (i); } local_type_unit++; } } return (-1); } Index: head/sys/boot/usb/storage/umass_loader.c =================================================================== --- head/sys/boot/usb/storage/umass_loader.c (revision 308826) +++ head/sys/boot/usb/storage/umass_loader.c (revision 308827) @@ -1,226 +1,230 @@ /* $FreeBSD$ */ /*- * Copyright (c) 2014 Hans Petter Selasky * All rights reserved. * * This software was developed by SRI International and the University of * Cambridge Computer Laboratory under DARPA/AFRL contract (FA8750-10-C-0237) * ("CTSRD"), as part of the DARPA CRASH research programme. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include #include #include #include #define HAVE_STANDARD_DEFS #include USB_GLOBAL_INCLUDE_FILE #include "umass_common.h" static int umass_disk_init(void); static int umass_disk_open(struct open_file *,...); static int umass_disk_close(struct open_file *); static void umass_disk_cleanup(void); static int umass_disk_ioctl(struct open_file *, u_long, void *); static int umass_disk_strategy(void *, int, daddr_t, size_t, size_t, char *, size_t *); static int umass_disk_print(int); struct devsw umass_disk = { .dv_name = "umass", .dv_type = DEVT_DISK, .dv_init = umass_disk_init, .dv_strategy = umass_disk_strategy, .dv_open = umass_disk_open, .dv_close = umass_disk_close, .dv_ioctl = umass_disk_ioctl, .dv_print = umass_disk_print, .dv_cleanup = umass_disk_cleanup, }; static int umass_disk_init(void) { uint32_t time; usb_init(); usb_needs_explore_all(); /* wait 8 seconds for a USB mass storage device to appear */ for (time = 0; time < (8 * hz); time++) { usb_idle(); delay(1000000 / hz); time++; callout_process(1); if (umass_uaa.device != NULL) return (0); } return (0); } static int umass_disk_strategy(void *devdata, int flag, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsizep) { if (umass_uaa.device == NULL) return (ENXIO); if (rsizep != NULL) *rsizep = 0; if (flag == F_WRITE) { if (usb_msc_write_10(umass_uaa.device, 0, dblk, size >> 9, buf) != 0) return (EINVAL); } else if (flag == F_READ) { if (usb_msc_read_10(umass_uaa.device, 0, dblk, size >> 9, buf) != 0) return (EINVAL); } else { return (EROFS); } if (rsizep != NULL) *rsizep = size; return (0); } static int umass_disk_open_sub(struct disk_devdesc *dev) { uint32_t nblock; uint32_t blocksize; if (usb_msc_read_capacity(umass_uaa.device, 0, &nblock, &blocksize) != 0) return (EINVAL); return (disk_open(dev, ((uint64_t)nblock + 1) * (uint64_t)blocksize, blocksize, 0)); } static int umass_disk_open(struct open_file *f,...) { va_list ap; struct disk_devdesc *dev; va_start(ap, f); dev = va_arg(ap, struct disk_devdesc *); va_end(ap); if (umass_uaa.device == NULL) return (ENXIO); if (dev->d_unit != 0) return (EIO); return (umass_disk_open_sub(dev)); } static int umass_disk_ioctl(struct open_file *f __unused, u_long cmd, void *buf) { uint32_t nblock; uint32_t blocksize; switch (cmd) { case IOCTL_GET_BLOCK_SIZE: case IOCTL_GET_BLOCKS: if (usb_msc_read_capacity(umass_uaa.device, 0, &nblock, &blocksize) != 0) return (EINVAL); if (cmd == IOCTL_GET_BLOCKS) *(uint32_t*)buf = nblock; else *(uint32_t*)buf = blocksize; return (0); default: return (ENXIO); } } static int umass_disk_close(struct open_file *f) { struct disk_devdesc *dev; dev = (struct disk_devdesc *)f->f_devdata; return (disk_close(dev)); } static int umass_disk_print(int verbose) { struct disk_devdesc dev; + printf("%s devices:", umass_disk.dv_name); + if (pager_output("\n") != 0) + return (1); + memset(&dev, 0, sizeof(dev)); ret = pager_output(" umass0 UMASS device\n"); if (ret != 0) return (ret); dev.d_dev = &umass_disk; dev.d_unit = 0; dev.d_slice = -1; dev.d_partition = -1; if (umass_disk_open_sub(&dev) == 0) { ret = disk_print(&dev, " umass0", verbose); disk_close(&dev); } return (ret); } static void umass_disk_cleanup(void) { disk_cleanup(&umass_disk); usb_uninit(); } /* USB specific functions */ extern void callout_process(int); extern void usb_idle(void); extern void usb_init(void); extern void usb_uninit(void); void DELAY(unsigned int usdelay) { delay(usdelay); } int pause(const char *what, int timeout) { if (timeout == 0) timeout = 1; delay((1000000 / hz) * timeout); return (0); } Index: head/sys/boot/userboot/userboot/host.c =================================================================== --- head/sys/boot/userboot/userboot/host.c (revision 308826) +++ head/sys/boot/userboot/userboot/host.c (revision 308827) @@ -1,198 +1,202 @@ /*- * Copyright (c) 2011 Google, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * Read from the host filesystem */ #include #include #include #include #include #include #include #include "libuserboot.h" /* * Open a file. */ static int host_open(const char *upath, struct open_file *f) { if (f->f_dev != &host_dev) return (EINVAL); return (CALLBACK(open, upath, &f->f_fsdata)); } static int host_close(struct open_file *f) { CALLBACK(close, f->f_fsdata); f->f_fsdata = (void *)0; return (0); } /* * Copy a portion of a file into memory. */ static int host_read(struct open_file *f, void *start, size_t size, size_t *resid) { return (CALLBACK(read, f->f_fsdata, start, size, resid)); } /* * Don't be silly - the bootstrap has no business writing anything. */ static int host_write(struct open_file *f, void *start, size_t size, size_t *resid) { return (EROFS); } static off_t host_seek(struct open_file *f, off_t offset, int where) { return (CALLBACK(seek, f->f_fsdata, offset, where)); } static int host_stat(struct open_file *f, struct stat *sb) { int mode; int uid; int gid; uint64_t size; CALLBACK(stat, f->f_fsdata, &mode, &uid, &gid, &size); sb->st_mode = mode; sb->st_uid = uid; sb->st_gid = gid; sb->st_size = size; return (0); } static int host_readdir(struct open_file *f, struct dirent *d) { uint32_t fileno; uint8_t type; size_t namelen; int rc; rc = CALLBACK(readdir, f->f_fsdata, &fileno, &type, &namelen, d->d_name); if (rc) return (rc); d->d_fileno = fileno; d->d_type = type; d->d_namlen = namelen; return (0); } static int host_dev_init(void) { return (0); } static int host_dev_print(int verbose) { char line[80]; + printf("%s devices:", host_dev.dv_name); + if (pager_output("\n") != 0) + return (1); + snprintf(line, sizeof(line), " host%d: Host filesystem\n", 0); return (pager_output(line)); } /* * 'Open' the host device. */ static int host_dev_open(struct open_file *f, ...) { va_list args; struct devdesc *dev; va_start(args, f); dev = va_arg(args, struct devdesc*); va_end(args); return (0); } static int host_dev_close(struct open_file *f) { return (0); } static int host_dev_strategy(void *devdata, int rw, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize) { return (ENOSYS); } struct fs_ops host_fsops = { "host", host_open, host_close, host_read, host_write, host_seek, host_stat, host_readdir }; struct devsw host_dev = { .dv_name = "host", .dv_type = DEVT_NET, .dv_init = host_dev_init, .dv_strategy = host_dev_strategy, .dv_open = host_dev_open, .dv_close = host_dev_close, .dv_ioctl = noioctl, .dv_print = host_dev_print, .dv_cleanup = NULL }; Index: head/sys/boot/userboot/userboot/userboot_disk.c =================================================================== --- head/sys/boot/userboot/userboot/userboot_disk.c (revision 308826) +++ head/sys/boot/userboot/userboot/userboot_disk.c (revision 308827) @@ -1,230 +1,237 @@ /*- * Copyright (c) 2011 Google, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * Userboot disk image handling. */ #include #include #include #include #include "disk.h" #include "libuserboot.h" struct userdisk_info { uint64_t mediasize; uint16_t sectorsize; int ud_open; /* reference counter */ void *ud_bcache; /* buffer cache data */ }; int userboot_disk_maxunit = 0; static int userdisk_maxunit = 0; static struct userdisk_info *ud_info; static int userdisk_init(void); static void userdisk_cleanup(void); static int userdisk_strategy(void *devdata, int flag, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize); static int userdisk_realstrategy(void *devdata, int flag, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize); static int userdisk_open(struct open_file *f, ...); static int userdisk_close(struct open_file *f); static int userdisk_ioctl(struct open_file *f, u_long cmd, void *data); static int userdisk_print(int verbose); struct devsw userboot_disk = { "disk", DEVT_DISK, userdisk_init, userdisk_strategy, userdisk_open, userdisk_close, userdisk_ioctl, userdisk_print, userdisk_cleanup }; /* * Initialize userdisk_info structure for each disk. */ static int userdisk_init(void) { off_t mediasize; u_int sectorsize; int i; userdisk_maxunit = userboot_disk_maxunit; if (userdisk_maxunit > 0) { ud_info = malloc(sizeof(*ud_info) * userdisk_maxunit); if (ud_info == NULL) return (ENOMEM); for (i = 0; i < userdisk_maxunit; i++) { if (CALLBACK(diskioctl, i, DIOCGSECTORSIZE, §orsize) != 0 || CALLBACK(diskioctl, i, DIOCGMEDIASIZE, &mediasize) != 0) return (ENXIO); ud_info[i].mediasize = mediasize; ud_info[i].sectorsize = sectorsize; ud_info[i].ud_open = 0; ud_info[i].ud_bcache = NULL; } } bcache_add_dev(userdisk_maxunit); return(0); } static void userdisk_cleanup(void) { if (userdisk_maxunit > 0) free(ud_info); disk_cleanup(&userboot_disk); } /* * Print information about disks */ static int userdisk_print(int verbose) { struct disk_devdesc dev; char line[80]; int i, ret = 0; + if (userdisk_maxunit == 0) + return (0); + + printf("%s devices:", userboot_disk.dv_name); + if ((ret = pager_output("\n")) != 0) + return (ret); + for (i = 0; i < userdisk_maxunit; i++) { snprintf(line, sizeof(line), " disk%d: Guest drive image\n", i); ret = pager_output(line); if (ret != 0) break; dev.d_dev = &userboot_disk; dev.d_unit = i; dev.d_slice = -1; dev.d_partition = -1; if (disk_open(&dev, ud_info[i].mediasize, ud_info[i].sectorsize, 0) == 0) { snprintf(line, sizeof(line), " disk%d", i); ret = disk_print(&dev, line, verbose); disk_close(&dev); if (ret != 0) break; } } return (ret); } /* * Attempt to open the disk described by (dev) for use by (f). */ static int userdisk_open(struct open_file *f, ...) { va_list ap; struct disk_devdesc *dev; va_start(ap, f); dev = va_arg(ap, struct disk_devdesc *); va_end(ap); if (dev->d_unit < 0 || dev->d_unit >= userdisk_maxunit) return (EIO); ud_info[dev->d_unit].ud_open++; if (ud_info[dev->d_unit].ud_bcache == NULL) ud_info[dev->d_unit].ud_bcache = bcache_allocate(); return (disk_open(dev, ud_info[dev->d_unit].mediasize, ud_info[dev->d_unit].sectorsize, 0)); } static int userdisk_close(struct open_file *f) { struct disk_devdesc *dev; dev = (struct disk_devdesc *)f->f_devdata; ud_info[dev->d_unit].ud_open--; if (ud_info[dev->d_unit].ud_open == 0) { bcache_free(ud_info[dev->d_unit].ud_bcache); ud_info[dev->d_unit].ud_bcache = NULL; } return (disk_close(dev)); } static int userdisk_strategy(void *devdata, int rw, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize) { struct bcache_devdata bcd; struct disk_devdesc *dev; dev = (struct disk_devdesc *)devdata; bcd.dv_strategy = userdisk_realstrategy; bcd.dv_devdata = devdata; bcd.dv_cache = ud_info[dev->d_unit].ud_bcache; return (bcache_strategy(&bcd, rw, dblk + dev->d_offset, offset, size, buf, rsize)); } static int userdisk_realstrategy(void *devdata, int rw, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize) { struct disk_devdesc *dev = devdata; uint64_t off; size_t resid; int rc; if (rw == F_WRITE) return (EROFS); if (rw != F_READ) return (EINVAL); if (rsize) *rsize = 0; off = dblk * ud_info[dev->d_unit].sectorsize; rc = CALLBACK(diskread, dev->d_unit, off, buf, size, &resid); if (rc) return (rc); if (rsize) *rsize = size - resid; return (0); } static int userdisk_ioctl(struct open_file *f, u_long cmd, void *data) { struct disk_devdesc *dev; dev = (struct disk_devdesc *)f->f_devdata; return (CALLBACK(diskioctl, dev->d_unit, cmd, data)); } Index: head/sys/boot/zfs/zfs.c =================================================================== --- head/sys/boot/zfs/zfs.c (revision 308826) +++ head/sys/boot/zfs/zfs.c (revision 308827) @@ -1,900 +1,907 @@ /*- * Copyright (c) 2007 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #include __FBSDID("$FreeBSD$"); /* * Stand-alone file reading package. */ #include #include #include #include #include #include #include #include #include #include #include "libzfs.h" #include "zfsimpl.c" /* Define the range of indexes to be populated with ZFS Boot Environments */ #define ZFS_BE_FIRST 4 #define ZFS_BE_LAST 8 static int zfs_open(const char *path, struct open_file *f); static int zfs_write(struct open_file *f, void *buf, size_t size, size_t *resid); static int zfs_close(struct open_file *f); static int zfs_read(struct open_file *f, void *buf, size_t size, size_t *resid); static off_t zfs_seek(struct open_file *f, off_t offset, int where); static int zfs_stat(struct open_file *f, struct stat *sb); static int zfs_readdir(struct open_file *f, struct dirent *d); struct devsw zfs_dev; struct fs_ops zfs_fsops = { "zfs", zfs_open, zfs_close, zfs_read, zfs_write, zfs_seek, zfs_stat, zfs_readdir }; /* * In-core open file. */ struct file { off_t f_seekp; /* seek pointer */ dnode_phys_t f_dnode; uint64_t f_zap_type; /* zap type for readdir */ uint64_t f_num_leafs; /* number of fzap leaf blocks */ zap_leaf_phys_t *f_zap_leaf; /* zap leaf buffer */ }; static int zfs_env_index; static int zfs_env_count; SLIST_HEAD(zfs_be_list, zfs_be_entry) zfs_be_head = SLIST_HEAD_INITIALIZER(zfs_be_head); struct zfs_be_list *zfs_be_headp; struct zfs_be_entry { const char *name; SLIST_ENTRY(zfs_be_entry) entries; } *zfs_be, *zfs_be_tmp; /* * Open a file. */ static int zfs_open(const char *upath, struct open_file *f) { struct zfsmount *mount = (struct zfsmount *)f->f_devdata; struct file *fp; int rc; if (f->f_dev != &zfs_dev) return (EINVAL); /* allocate file system specific data structure */ fp = malloc(sizeof(struct file)); bzero(fp, sizeof(struct file)); f->f_fsdata = (void *)fp; rc = zfs_lookup(mount, upath, &fp->f_dnode); fp->f_seekp = 0; if (rc) { f->f_fsdata = NULL; free(fp); } return (rc); } static int zfs_close(struct open_file *f) { struct file *fp = (struct file *)f->f_fsdata; dnode_cache_obj = 0; f->f_fsdata = (void *)0; if (fp == (struct file *)0) return (0); free(fp); return (0); } /* * Copy a portion of a file into kernel memory. * Cross block boundaries when necessary. */ static int zfs_read(struct open_file *f, void *start, size_t size, size_t *resid /* out */) { const spa_t *spa = ((struct zfsmount *)f->f_devdata)->spa; struct file *fp = (struct file *)f->f_fsdata; struct stat sb; size_t n; int rc; rc = zfs_stat(f, &sb); if (rc) return (rc); n = size; if (fp->f_seekp + n > sb.st_size) n = sb.st_size - fp->f_seekp; rc = dnode_read(spa, &fp->f_dnode, fp->f_seekp, start, n); if (rc) return (rc); if (0) { int i; for (i = 0; i < n; i++) putchar(((char*) start)[i]); } fp->f_seekp += n; if (resid) *resid = size - n; return (0); } /* * Don't be silly - the bootstrap has no business writing anything. */ static int zfs_write(struct open_file *f, void *start, size_t size, size_t *resid /* out */) { return (EROFS); } static off_t zfs_seek(struct open_file *f, off_t offset, int where) { struct file *fp = (struct file *)f->f_fsdata; switch (where) { case SEEK_SET: fp->f_seekp = offset; break; case SEEK_CUR: fp->f_seekp += offset; break; case SEEK_END: { struct stat sb; int error; error = zfs_stat(f, &sb); if (error != 0) { errno = error; return (-1); } fp->f_seekp = sb.st_size - offset; break; } default: errno = EINVAL; return (-1); } return (fp->f_seekp); } static int zfs_stat(struct open_file *f, struct stat *sb) { const spa_t *spa = ((struct zfsmount *)f->f_devdata)->spa; struct file *fp = (struct file *)f->f_fsdata; return (zfs_dnode_stat(spa, &fp->f_dnode, sb)); } static int zfs_readdir(struct open_file *f, struct dirent *d) { const spa_t *spa = ((struct zfsmount *)f->f_devdata)->spa; struct file *fp = (struct file *)f->f_fsdata; mzap_ent_phys_t mze; struct stat sb; size_t bsize = fp->f_dnode.dn_datablkszsec << SPA_MINBLOCKSHIFT; int rc; rc = zfs_stat(f, &sb); if (rc) return (rc); if (!S_ISDIR(sb.st_mode)) return (ENOTDIR); /* * If this is the first read, get the zap type. */ if (fp->f_seekp == 0) { rc = dnode_read(spa, &fp->f_dnode, 0, &fp->f_zap_type, sizeof(fp->f_zap_type)); if (rc) return (rc); if (fp->f_zap_type == ZBT_MICRO) { fp->f_seekp = offsetof(mzap_phys_t, mz_chunk); } else { rc = dnode_read(spa, &fp->f_dnode, offsetof(zap_phys_t, zap_num_leafs), &fp->f_num_leafs, sizeof(fp->f_num_leafs)); if (rc) return (rc); fp->f_seekp = bsize; fp->f_zap_leaf = (zap_leaf_phys_t *)malloc(bsize); rc = dnode_read(spa, &fp->f_dnode, fp->f_seekp, fp->f_zap_leaf, bsize); if (rc) return (rc); } } if (fp->f_zap_type == ZBT_MICRO) { mzap_next: if (fp->f_seekp >= bsize) return (ENOENT); rc = dnode_read(spa, &fp->f_dnode, fp->f_seekp, &mze, sizeof(mze)); if (rc) return (rc); fp->f_seekp += sizeof(mze); if (!mze.mze_name[0]) goto mzap_next; d->d_fileno = ZFS_DIRENT_OBJ(mze.mze_value); d->d_type = ZFS_DIRENT_TYPE(mze.mze_value); strcpy(d->d_name, mze.mze_name); d->d_namlen = strlen(d->d_name); return (0); } else { zap_leaf_t zl; zap_leaf_chunk_t *zc, *nc; int chunk; size_t namelen; char *p; uint64_t value; /* * Initialise this so we can use the ZAP size * calculating macros. */ zl.l_bs = ilog2(bsize); zl.l_phys = fp->f_zap_leaf; /* * Figure out which chunk we are currently looking at * and consider seeking to the next leaf. We use the * low bits of f_seekp as a simple chunk index. */ fzap_next: chunk = fp->f_seekp & (bsize - 1); if (chunk == ZAP_LEAF_NUMCHUNKS(&zl)) { fp->f_seekp = rounddown2(fp->f_seekp, bsize) + bsize; chunk = 0; /* * Check for EOF and read the new leaf. */ if (fp->f_seekp >= bsize * fp->f_num_leafs) return (ENOENT); rc = dnode_read(spa, &fp->f_dnode, fp->f_seekp, fp->f_zap_leaf, bsize); if (rc) return (rc); } zc = &ZAP_LEAF_CHUNK(&zl, chunk); fp->f_seekp++; if (zc->l_entry.le_type != ZAP_CHUNK_ENTRY) goto fzap_next; namelen = zc->l_entry.le_name_numints; if (namelen > sizeof(d->d_name)) namelen = sizeof(d->d_name); /* * Paste the name back together. */ nc = &ZAP_LEAF_CHUNK(&zl, zc->l_entry.le_name_chunk); p = d->d_name; while (namelen > 0) { int len; len = namelen; if (len > ZAP_LEAF_ARRAY_BYTES) len = ZAP_LEAF_ARRAY_BYTES; memcpy(p, nc->l_array.la_array, len); p += len; namelen -= len; nc = &ZAP_LEAF_CHUNK(&zl, nc->l_array.la_next); } d->d_name[sizeof(d->d_name) - 1] = 0; /* * Assume the first eight bytes of the value are * a uint64_t. */ value = fzap_leaf_value(&zl, zc); d->d_fileno = ZFS_DIRENT_OBJ(value); d->d_type = ZFS_DIRENT_TYPE(value); d->d_namlen = strlen(d->d_name); return (0); } } static int vdev_read(vdev_t *vdev, void *priv, off_t offset, void *buf, size_t size) { int fd; fd = (uintptr_t) priv; lseek(fd, offset, SEEK_SET); if (read(fd, buf, size) == size) { return 0; } else { return (EIO); } } static int zfs_dev_init(void) { spa_t *spa; spa_t *next; spa_t *prev; zfs_init(); if (archsw.arch_zfs_probe == NULL) return (ENXIO); archsw.arch_zfs_probe(); prev = NULL; spa = STAILQ_FIRST(&zfs_pools); while (spa != NULL) { next = STAILQ_NEXT(spa, spa_link); if (zfs_spa_init(spa)) { if (prev == NULL) STAILQ_REMOVE_HEAD(&zfs_pools, spa_link); else STAILQ_REMOVE_AFTER(&zfs_pools, prev, spa_link); } else prev = spa; spa = next; } return (0); } struct zfs_probe_args { int fd; const char *devname; uint64_t *pool_guid; u_int secsz; }; static int zfs_diskread(void *arg, void *buf, size_t blocks, off_t offset) { struct zfs_probe_args *ppa; ppa = (struct zfs_probe_args *)arg; return (vdev_read(NULL, (void *)(uintptr_t)ppa->fd, offset * ppa->secsz, buf, blocks * ppa->secsz)); } static int zfs_probe(int fd, uint64_t *pool_guid) { spa_t *spa; int ret; ret = vdev_probe(vdev_read, (void *)(uintptr_t)fd, &spa); if (ret == 0 && pool_guid != NULL) *pool_guid = spa->spa_guid; return (ret); } static int zfs_probe_partition(void *arg, const char *partname, const struct ptable_entry *part) { struct zfs_probe_args *ppa, pa; struct ptable *table; char devname[32]; int ret; /* Probe only freebsd-zfs and freebsd partitions */ if (part->type != PART_FREEBSD && part->type != PART_FREEBSD_ZFS) return (0); ppa = (struct zfs_probe_args *)arg; strncpy(devname, ppa->devname, strlen(ppa->devname) - 1); devname[strlen(ppa->devname) - 1] = '\0'; sprintf(devname, "%s%s:", devname, partname); pa.fd = open(devname, O_RDONLY); if (pa.fd == -1) return (0); ret = zfs_probe(pa.fd, ppa->pool_guid); if (ret == 0) return (0); /* Do we have BSD label here? */ if (part->type == PART_FREEBSD) { pa.devname = devname; pa.pool_guid = ppa->pool_guid; pa.secsz = ppa->secsz; table = ptable_open(&pa, part->end - part->start + 1, ppa->secsz, zfs_diskread); if (table != NULL) { ptable_iterate(table, &pa, zfs_probe_partition); ptable_close(table); } } close(pa.fd); return (0); } int zfs_probe_dev(const char *devname, uint64_t *pool_guid) { struct ptable *table; struct zfs_probe_args pa; off_t mediasz; int ret; pa.fd = open(devname, O_RDONLY); if (pa.fd == -1) return (ENXIO); /* Probe the whole disk */ ret = zfs_probe(pa.fd, pool_guid); if (ret == 0) return (0); /* Probe each partition */ ret = ioctl(pa.fd, DIOCGMEDIASIZE, &mediasz); if (ret == 0) ret = ioctl(pa.fd, DIOCGSECTORSIZE, &pa.secsz); if (ret == 0) { pa.devname = devname; pa.pool_guid = pool_guid; table = ptable_open(&pa, mediasz / pa.secsz, pa.secsz, zfs_diskread); if (table != NULL) { ptable_iterate(table, &pa, zfs_probe_partition); ptable_close(table); } } close(pa.fd); return (ret); } /* * Print information about ZFS pools */ static int zfs_dev_print(int verbose) { spa_t *spa; char line[80]; int ret = 0; + if (STAILQ_EMPTY(&zfs_pools)) + return (0); + + printf("%s devices:", zfs_dev.dv_name); + if ((ret = pager_output("\n")) != 0) + return (ret); + if (verbose) { return (spa_all_status()); } STAILQ_FOREACH(spa, &zfs_pools, spa_link) { snprintf(line, sizeof(line), " zfs:%s\n", spa->spa_name); ret = pager_output(line); if (ret != 0) break; } return (ret); } /* * Attempt to open the pool described by (dev) for use by (f). */ static int zfs_dev_open(struct open_file *f, ...) { va_list args; struct zfs_devdesc *dev; struct zfsmount *mount; spa_t *spa; int rv; va_start(args, f); dev = va_arg(args, struct zfs_devdesc *); va_end(args); if (dev->pool_guid == 0) spa = STAILQ_FIRST(&zfs_pools); else spa = spa_find_by_guid(dev->pool_guid); if (!spa) return (ENXIO); mount = malloc(sizeof(*mount)); rv = zfs_mount(spa, dev->root_guid, mount); if (rv != 0) { free(mount); return (rv); } if (mount->objset.os_type != DMU_OST_ZFS) { printf("Unexpected object set type %ju\n", (uintmax_t)mount->objset.os_type); free(mount); return (EIO); } f->f_devdata = mount; free(dev); return (0); } static int zfs_dev_close(struct open_file *f) { free(f->f_devdata); f->f_devdata = NULL; return (0); } static int zfs_dev_strategy(void *devdata, int rw, daddr_t dblk, size_t offset, size_t size, char *buf, size_t *rsize) { return (ENOSYS); } struct devsw zfs_dev = { .dv_name = "zfs", .dv_type = DEVT_ZFS, .dv_init = zfs_dev_init, .dv_strategy = zfs_dev_strategy, .dv_open = zfs_dev_open, .dv_close = zfs_dev_close, .dv_ioctl = noioctl, .dv_print = zfs_dev_print, .dv_cleanup = NULL }; int zfs_parsedev(struct zfs_devdesc *dev, const char *devspec, const char **path) { static char rootname[ZFS_MAXNAMELEN]; static char poolname[ZFS_MAXNAMELEN]; spa_t *spa; const char *end; const char *np; const char *sep; int rv; np = devspec; if (*np != ':') return (EINVAL); np++; end = strchr(np, ':'); if (end == NULL) return (EINVAL); sep = strchr(np, '/'); if (sep == NULL || sep >= end) sep = end; memcpy(poolname, np, sep - np); poolname[sep - np] = '\0'; if (sep < end) { sep++; memcpy(rootname, sep, end - sep); rootname[end - sep] = '\0'; } else rootname[0] = '\0'; spa = spa_find_by_name(poolname); if (!spa) return (ENXIO); dev->pool_guid = spa->spa_guid; rv = zfs_lookup_dataset(spa, rootname, &dev->root_guid); if (rv != 0) return (rv); if (path != NULL) *path = (*end == '\0') ? end : end + 1; dev->d_dev = &zfs_dev; dev->d_type = zfs_dev.dv_type; return (0); } char * zfs_fmtdev(void *vdev) { static char rootname[ZFS_MAXNAMELEN]; static char buf[2 * ZFS_MAXNAMELEN + 8]; struct zfs_devdesc *dev = (struct zfs_devdesc *)vdev; spa_t *spa; buf[0] = '\0'; if (dev->d_type != DEVT_ZFS) return (buf); if (dev->pool_guid == 0) { spa = STAILQ_FIRST(&zfs_pools); dev->pool_guid = spa->spa_guid; } else spa = spa_find_by_guid(dev->pool_guid); if (spa == NULL) { printf("ZFS: can't find pool by guid\n"); return (buf); } if (dev->root_guid == 0 && zfs_get_root(spa, &dev->root_guid)) { printf("ZFS: can't find root filesystem\n"); return (buf); } if (zfs_rlookup(spa, dev->root_guid, rootname)) { printf("ZFS: can't find filesystem by guid\n"); return (buf); } if (rootname[0] == '\0') sprintf(buf, "%s:%s:", dev->d_dev->dv_name, spa->spa_name); else sprintf(buf, "%s:%s/%s:", dev->d_dev->dv_name, spa->spa_name, rootname); return (buf); } int zfs_list(const char *name) { static char poolname[ZFS_MAXNAMELEN]; uint64_t objid; spa_t *spa; const char *dsname; int len; int rv; len = strlen(name); dsname = strchr(name, '/'); if (dsname != NULL) { len = dsname - name; dsname++; } else dsname = ""; memcpy(poolname, name, len); poolname[len] = '\0'; spa = spa_find_by_name(poolname); if (!spa) return (ENXIO); rv = zfs_lookup_dataset(spa, dsname, &objid); if (rv != 0) return (rv); return (zfs_list_dataset(spa, objid)); } void init_zfs_bootenv(char *currdev) { char *beroot; if (strlen(currdev) == 0) return; if(strncmp(currdev, "zfs:", 4) != 0) return; /* Remove the trailing : */ currdev[strlen(currdev) - 1] = '\0'; setenv("zfs_be_active", currdev, 1); setenv("zfs_be_currpage", "1", 1); /* Forward past zfs: */ currdev = strchr(currdev, ':'); currdev++; /* Remove the last element (current bootenv) */ beroot = strrchr(currdev, '/'); if (beroot != NULL) beroot[0] = '\0'; beroot = currdev; setenv("zfs_be_root", beroot, 1); } int zfs_bootenv(const char *name) { static char poolname[ZFS_MAXNAMELEN], *dsname, *root; char becount[4]; uint64_t objid; spa_t *spa; int len, rv, pages, perpage, currpage; if (name == NULL) return (EINVAL); if ((root = getenv("zfs_be_root")) == NULL) return (EINVAL); if (strcmp(name, root) != 0) { if (setenv("zfs_be_root", name, 1) != 0) return (ENOMEM); } SLIST_INIT(&zfs_be_head); zfs_env_count = 0; len = strlen(name); dsname = strchr(name, '/'); if (dsname != NULL) { len = dsname - name; dsname++; } else dsname = ""; memcpy(poolname, name, len); poolname[len] = '\0'; spa = spa_find_by_name(poolname); if (!spa) return (ENXIO); rv = zfs_lookup_dataset(spa, dsname, &objid); if (rv != 0) return (rv); rv = zfs_callback_dataset(spa, objid, zfs_belist_add); /* Calculate and store the number of pages of BEs */ perpage = (ZFS_BE_LAST - ZFS_BE_FIRST + 1); pages = (zfs_env_count / perpage) + ((zfs_env_count % perpage) > 0 ? 1 : 0); snprintf(becount, 4, "%d", pages); if (setenv("zfs_be_pages", becount, 1) != 0) return (ENOMEM); /* Roll over the page counter if it has exceeded the maximum */ currpage = strtol(getenv("zfs_be_currpage"), NULL, 10); if (currpage > pages) { if (setenv("zfs_be_currpage", "1", 1) != 0) return (ENOMEM); } /* Populate the menu environment variables */ zfs_set_env(); /* Clean up the SLIST of ZFS BEs */ while (!SLIST_EMPTY(&zfs_be_head)) { zfs_be = SLIST_FIRST(&zfs_be_head); SLIST_REMOVE_HEAD(&zfs_be_head, entries); free(zfs_be); } return (rv); } int zfs_belist_add(const char *name, uint64_t value __unused) { /* Skip special datasets that start with a $ character */ if (strncmp(name, "$", 1) == 0) { return (0); } /* Add the boot environment to the head of the SLIST */ zfs_be = malloc(sizeof(struct zfs_be_entry)); if (zfs_be == NULL) { return (ENOMEM); } zfs_be->name = name; SLIST_INSERT_HEAD(&zfs_be_head, zfs_be, entries); zfs_env_count++; return (0); } int zfs_set_env(void) { char envname[32], envval[256]; char *beroot, *pagenum; int rv, page, ctr; beroot = getenv("zfs_be_root"); if (beroot == NULL) { return (1); } pagenum = getenv("zfs_be_currpage"); if (pagenum != NULL) { page = strtol(pagenum, NULL, 10); } else { page = 1; } ctr = 1; rv = 0; zfs_env_index = ZFS_BE_FIRST; SLIST_FOREACH_SAFE(zfs_be, &zfs_be_head, entries, zfs_be_tmp) { /* Skip to the requested page number */ if (ctr <= ((ZFS_BE_LAST - ZFS_BE_FIRST + 1) * (page - 1))) { ctr++; continue; } snprintf(envname, sizeof(envname), "bootenvmenu_caption[%d]", zfs_env_index); snprintf(envval, sizeof(envval), "%s", zfs_be->name); rv = setenv(envname, envval, 1); if (rv != 0) { break; } snprintf(envname, sizeof(envname), "bootenvansi_caption[%d]", zfs_env_index); rv = setenv(envname, envval, 1); if (rv != 0){ break; } snprintf(envname, sizeof(envname), "bootenvmenu_command[%d]", zfs_env_index); rv = setenv(envname, "set_bootenv", 1); if (rv != 0){ break; } snprintf(envname, sizeof(envname), "bootenv_root[%d]", zfs_env_index); snprintf(envval, sizeof(envval), "zfs:%s/%s", beroot, zfs_be->name); rv = setenv(envname, envval, 1); if (rv != 0){ break; } zfs_env_index++; if (zfs_env_index > ZFS_BE_LAST) { break; } } for (; zfs_env_index <= ZFS_BE_LAST; zfs_env_index++) { snprintf(envname, sizeof(envname), "bootenvmenu_caption[%d]", zfs_env_index); (void)unsetenv(envname); snprintf(envname, sizeof(envname), "bootenvansi_caption[%d]", zfs_env_index); (void)unsetenv(envname); snprintf(envname, sizeof(envname), "bootenvmenu_command[%d]", zfs_env_index); (void)unsetenv(envname); snprintf(envname, sizeof(envname), "bootenv_root[%d]", zfs_env_index); (void)unsetenv(envname); } return (rv); }